OSDN Git Service

2010-06-17 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-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{^-o^/OUTPUT^} (@command{gnatelim})
10731 @item ^-o^/OUTPUT^=@var{report_file}
10732 Put @command{gnatelim} output into a specified file. If this file already exists,
10733 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10734 into @file{stderr}
10735
10736 @item ^-q^/QUIET^
10737 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10738 Quiet mode: by default @code{gnatelim} outputs to the standard error
10739 stream the number of program units left to be processed. This option turns
10740 this trace off.
10741
10742 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10743 @item ^-t^/TIME^
10744 Print out execution time.
10745
10746 @item ^-v^/VERBOSE^
10747 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10748 Verbose mode: @code{gnatelim} version information is printed as Ada
10749 comments to the standard output stream. Also, in addition to the number of
10750 program units left @code{gnatelim} will output the name of the current unit
10751 being processed.
10752
10753 @item ^-wq^/WARNINGS=QUIET^
10754 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10755 Quet warning mode - some warnings are suppressed. In particular warnings that
10756 indicate that the analysed set of sources is incomplete to make up a
10757 partition and that some subprogram bodies are missing are not generated.
10758 @end table
10759
10760 @node Processing Precompiled Libraries
10761 @subsection Processing Precompiled Libraries
10762
10763 @noindent
10764 If some program uses a precompiled Ada library, it can be processed by
10765 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10766 Eliminate pragma for a subprogram if the body of this subprogram has not
10767 been analysed, this is a typical case for subprograms from precompiled
10768 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10769 warnings about missing source files and non-analyzed subprogram bodies
10770 that can be generated when processing precompiled Ada libraries.
10771
10772 @node Correcting the List of Eliminate Pragmas
10773 @subsection Correcting the List of Eliminate Pragmas
10774
10775 @noindent
10776 In some rare cases @code{gnatelim} may try to eliminate
10777 subprograms that are actually called in the program. In this case, the
10778 compiler will generate an error message of the form:
10779
10780 @smallexample
10781 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10782 @end smallexample
10783
10784 @noindent
10785 You will need to manually remove the wrong @code{Eliminate} pragmas from
10786 the configuration file indicated in the error message. You should recompile
10787 your program from scratch after that, because you need a consistent
10788 configuration file(s) during the entire compilation.
10789
10790 @node Making Your Executables Smaller
10791 @subsection Making Your Executables Smaller
10792
10793 @noindent
10794 In order to get a smaller executable for your program you now have to
10795 recompile the program completely with the configuration file containing
10796 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10797 @file{gnat.adc} file located in your current directory, just do:
10798
10799 @smallexample
10800 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10801 @end smallexample
10802
10803 @noindent
10804 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10805 recompile everything
10806 with the set of pragmas @code{Eliminate} that you have obtained with
10807 @command{gnatelim}).
10808
10809 Be aware that the set of @code{Eliminate} pragmas is specific to each
10810 program. It is not recommended to merge sets of @code{Eliminate}
10811 pragmas created for different programs in one configuration file.
10812
10813 @node Summary of the gnatelim Usage Cycle
10814 @subsection Summary of the @code{gnatelim} Usage Cycle
10815
10816 @noindent
10817 Here is a quick summary of the steps to be taken in order to reduce
10818 the size of your executables with @code{gnatelim}. You may use
10819 other GNAT options to control the optimization level,
10820 to produce the debugging information, to set search path, etc.
10821
10822 @enumerate
10823 @item
10824 Create a complete set of @file{ALI} files (if the program has not been
10825 built already)
10826
10827 @smallexample
10828 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10829 @end smallexample
10830
10831 @item
10832 Generate a list of @code{Eliminate} pragmas in default configuration file
10833 @file{gnat.adc} in the current directory
10834 @smallexample
10835 @ifset vms
10836 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10837 @end ifset
10838 @ifclear vms
10839 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10840 @end ifclear
10841 @end smallexample
10842
10843 @item
10844 Recompile the application
10845
10846 @smallexample
10847 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10848 @end smallexample
10849
10850 @end enumerate
10851
10852 @node Reducing Size of Executables with unused subprogram/data elimination
10853 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10854 @findex unused subprogram/data elimination
10855
10856 @noindent
10857 This section describes how you can eliminate unused subprograms and data from
10858 your executable just by setting options at compilation time.
10859
10860 @menu
10861 * About unused subprogram/data elimination::
10862 * Compilation options::
10863 * Example of unused subprogram/data elimination::
10864 @end menu
10865
10866 @node About unused subprogram/data elimination
10867 @subsection About unused subprogram/data elimination
10868
10869 @noindent
10870 By default, an executable contains all code and data of its composing objects
10871 (directly linked or coming from statically linked libraries), even data or code
10872 never used by this executable.
10873
10874 This feature will allow you to eliminate such unused code from your
10875 executable, making it smaller (in disk and in memory).
10876
10877 This functionality is available on all Linux platforms except for the IA-64
10878 architecture and on all cross platforms using the ELF binary file format.
10879 In both cases GNU binutils version 2.16 or later are required to enable it.
10880
10881 @node Compilation options
10882 @subsection Compilation options
10883
10884 @noindent
10885 The operation of eliminating the unused code and data from the final executable
10886 is directly performed by the linker.
10887
10888 In order to do this, it has to work with objects compiled with the
10889 following options:
10890 @option{-ffunction-sections} @option{-fdata-sections}.
10891 @cindex @option{-ffunction-sections} (@command{gcc})
10892 @cindex @option{-fdata-sections} (@command{gcc})
10893 These options are usable with C and Ada files.
10894 They will place respectively each
10895 function or data in a separate section in the resulting object file.
10896
10897 Once the objects and static libraries are created with these options, the
10898 linker can perform the dead code elimination. You can do this by setting
10899 the @option{-Wl,--gc-sections} option to gcc command or in the
10900 @option{-largs} section of @command{gnatmake}. This will perform a
10901 garbage collection of code and data never referenced.
10902
10903 If the linker performs a partial link (@option{-r} ld linker option), then you
10904 will need to provide one or several entry point using the
10905 @option{-e} / @option{--entry} ld option.
10906
10907 Note that objects compiled without the @option{-ffunction-sections} and
10908 @option{-fdata-sections} options can still be linked with the executable.
10909 However, no dead code elimination will be performed on those objects (they will
10910 be linked as is).
10911
10912 The GNAT static library is now compiled with -ffunction-sections and
10913 -fdata-sections on some platforms. This allows you to eliminate the unused code
10914 and data of the GNAT library from your executable.
10915
10916 @node Example of unused subprogram/data elimination
10917 @subsection Example of unused subprogram/data elimination
10918
10919 @noindent
10920 Here is a simple example:
10921
10922 @smallexample @c ada
10923 with Aux;
10924
10925 procedure Test is
10926 begin
10927    Aux.Used (10);
10928 end Test;
10929
10930 package Aux is
10931    Used_Data   : Integer;
10932    Unused_Data : Integer;
10933
10934    procedure Used   (Data : Integer);
10935    procedure Unused (Data : Integer);
10936 end Aux;
10937
10938 package body Aux is
10939    procedure Used (Data : Integer) is
10940    begin
10941       Used_Data := Data;
10942    end Used;
10943
10944    procedure Unused (Data : Integer) is
10945    begin
10946       Unused_Data := Data;
10947    end Unused;
10948 end Aux;
10949 @end smallexample
10950
10951 @noindent
10952 @code{Unused} and @code{Unused_Data} are never referenced in this code
10953 excerpt, and hence they may be safely removed from the final executable.
10954
10955 @smallexample
10956 $ gnatmake test
10957
10958 $ nm test | grep used
10959 020015f0 T aux__unused
10960 02005d88 B aux__unused_data
10961 020015cc T aux__used
10962 02005d84 B aux__used_data
10963
10964 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10965      -largs -Wl,--gc-sections
10966
10967 $ nm test | grep used
10968 02005350 T aux__used
10969 0201ffe0 B aux__used_data
10970 @end smallexample
10971
10972 @noindent
10973 It can be observed that the procedure @code{Unused} and the object
10974 @code{Unused_Data} are removed by the linker when using the
10975 appropriate options.
10976
10977 @c ********************************
10978 @node Renaming Files Using gnatchop
10979 @chapter Renaming Files Using @code{gnatchop}
10980 @findex gnatchop
10981
10982 @noindent
10983 This chapter discusses how to handle files with multiple units by using
10984 the @code{gnatchop} utility. This utility is also useful in renaming
10985 files to meet the standard GNAT default file naming conventions.
10986
10987 @menu
10988 * Handling Files with Multiple Units::
10989 * Operating gnatchop in Compilation Mode::
10990 * Command Line for gnatchop::
10991 * Switches for gnatchop::
10992 * Examples of gnatchop Usage::
10993 @end menu
10994
10995 @node Handling Files with Multiple Units
10996 @section Handling Files with Multiple Units
10997
10998 @noindent
10999 The basic compilation model of GNAT requires that a file submitted to the
11000 compiler have only one unit and there be a strict correspondence
11001 between the file name and the unit name.
11002
11003 The @code{gnatchop} utility allows both of these rules to be relaxed,
11004 allowing GNAT to process files which contain multiple compilation units
11005 and files with arbitrary file names. @code{gnatchop}
11006 reads the specified file and generates one or more output files,
11007 containing one unit per file. The unit and the file name correspond,
11008 as required by GNAT.
11009
11010 If you want to permanently restructure a set of ``foreign'' files so that
11011 they match the GNAT rules, and do the remaining development using the
11012 GNAT structure, you can simply use @command{gnatchop} once, generate the
11013 new set of files and work with them from that point on.
11014
11015 Alternatively, if you want to keep your files in the ``foreign'' format,
11016 perhaps to maintain compatibility with some other Ada compilation
11017 system, you can set up a procedure where you use @command{gnatchop} each
11018 time you compile, regarding the source files that it writes as temporary
11019 files that you throw away.
11020
11021 Note that if your file containing multiple units starts with a byte order
11022 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11023 will each start with a copy of this BOM, meaning that they can be compiled
11024 automatically in UTF-8 mode without needing to specify an explicit encoding.
11025
11026 @node Operating gnatchop in Compilation Mode
11027 @section Operating gnatchop in Compilation Mode
11028
11029 @noindent
11030 The basic function of @code{gnatchop} is to take a file with multiple units
11031 and split it into separate files. The boundary between files is reasonably
11032 clear, except for the issue of comments and pragmas. In default mode, the
11033 rule is that any pragmas between units belong to the previous unit, except
11034 that configuration pragmas always belong to the following unit. Any comments
11035 belong to the following unit. These rules
11036 almost always result in the right choice of
11037 the split point without needing to mark it explicitly and most users will
11038 find this default to be what they want. In this default mode it is incorrect to
11039 submit a file containing only configuration pragmas, or one that ends in
11040 configuration pragmas, to @code{gnatchop}.
11041
11042 However, using a special option to activate ``compilation mode'',
11043 @code{gnatchop}
11044 can perform another function, which is to provide exactly the semantics
11045 required by the RM for handling of configuration pragmas in a compilation.
11046 In the absence of configuration pragmas (at the main file level), this
11047 option has no effect, but it causes such configuration pragmas to be handled
11048 in a quite different manner.
11049
11050 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11051 only configuration pragmas, then this file is appended to the
11052 @file{gnat.adc} file in the current directory. This behavior provides
11053 the required behavior described in the RM for the actions to be taken
11054 on submitting such a file to the compiler, namely that these pragmas
11055 should apply to all subsequent compilations in the same compilation
11056 environment. Using GNAT, the current directory, possibly containing a
11057 @file{gnat.adc} file is the representation
11058 of a compilation environment. For more information on the
11059 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11060
11061 Second, in compilation mode, if @code{gnatchop}
11062 is given a file that starts with
11063 configuration pragmas, and contains one or more units, then these
11064 configuration pragmas are prepended to each of the chopped files. This
11065 behavior provides the required behavior described in the RM for the
11066 actions to be taken on compiling such a file, namely that the pragmas
11067 apply to all units in the compilation, but not to subsequently compiled
11068 units.
11069
11070 Finally, if configuration pragmas appear between units, they are appended
11071 to the previous unit. This results in the previous unit being illegal,
11072 since the compiler does not accept configuration pragmas that follow
11073 a unit. This provides the required RM behavior that forbids configuration
11074 pragmas other than those preceding the first compilation unit of a
11075 compilation.
11076
11077 For most purposes, @code{gnatchop} will be used in default mode. The
11078 compilation mode described above is used only if you need exactly
11079 accurate behavior with respect to compilations, and you have files
11080 that contain multiple units and configuration pragmas. In this
11081 circumstance the use of @code{gnatchop} with the compilation mode
11082 switch provides the required behavior, and is for example the mode
11083 in which GNAT processes the ACVC tests.
11084
11085 @node Command Line for gnatchop
11086 @section Command Line for @code{gnatchop}
11087
11088 @noindent
11089 The @code{gnatchop} command has the form:
11090
11091 @smallexample
11092 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11093 @c      @ovar{directory}
11094 @c Expanding @ovar macro inline (explanation in macro def comments)
11095 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11096       @r{[}@var{directory}@r{]}
11097 @end smallexample
11098
11099 @noindent
11100 The only required argument is the file name of the file to be chopped.
11101 There are no restrictions on the form of this file name. The file itself
11102 contains one or more Ada units, in normal GNAT format, concatenated
11103 together. As shown, more than one file may be presented to be chopped.
11104
11105 When run in default mode, @code{gnatchop} generates one output file in
11106 the current directory for each unit in each of the files.
11107
11108 @var{directory}, if specified, gives the name of the directory to which
11109 the output files will be written. If it is not specified, all files are
11110 written to the current directory.
11111
11112 For example, given a
11113 file called @file{hellofiles} containing
11114
11115 @smallexample @c ada
11116 @group
11117 @cartouche
11118 procedure hello;
11119
11120 with Text_IO; use Text_IO;
11121 procedure hello is
11122 begin
11123    Put_Line ("Hello");
11124 end hello;
11125 @end cartouche
11126 @end group
11127 @end smallexample
11128
11129 @noindent
11130 the command
11131
11132 @smallexample
11133 $ gnatchop ^hellofiles^HELLOFILES.^
11134 @end smallexample
11135
11136 @noindent
11137 generates two files in the current directory, one called
11138 @file{hello.ads} containing the single line that is the procedure spec,
11139 and the other called @file{hello.adb} containing the remaining text. The
11140 original file is not affected. The generated files can be compiled in
11141 the normal manner.
11142
11143 @noindent
11144 When gnatchop is invoked on a file that is empty or that contains only empty
11145 lines and/or comments, gnatchop will not fail, but will not produce any
11146 new sources.
11147
11148 For example, given a
11149 file called @file{toto.txt} containing
11150
11151 @smallexample @c ada
11152 @group
11153 @cartouche
11154 --  Just a comment
11155 @end cartouche
11156 @end group
11157 @end smallexample
11158
11159 @noindent
11160 the command
11161
11162 @smallexample
11163 $ gnatchop ^toto.txt^TOT.TXT^
11164 @end smallexample
11165
11166 @noindent
11167 will not produce any new file and will result in the following warnings:
11168
11169 @smallexample
11170 toto.txt:1:01: warning: empty file, contains no compilation units
11171 no compilation units found
11172 no source files written
11173 @end smallexample
11174
11175 @node Switches for gnatchop
11176 @section Switches for @code{gnatchop}
11177
11178 @noindent
11179 @command{gnatchop} recognizes the following switches:
11180
11181 @table @option
11182 @c !sort!
11183
11184 @item --version
11185 @cindex @option{--version} @command{gnatchop}
11186 Display Copyright and version, then exit disregarding all other options.
11187
11188 @item --help
11189 @cindex @option{--help} @command{gnatchop}
11190 If @option{--version} was not used, display usage, then exit disregarding
11191 all other options.
11192
11193 @item ^-c^/COMPILATION^
11194 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11195 Causes @code{gnatchop} to operate in compilation mode, in which
11196 configuration pragmas are handled according to strict RM rules. See
11197 previous section for a full description of this mode.
11198
11199 @ifclear vms
11200 @item -gnat@var{xxx}
11201 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11202 used to parse the given file. Not all @var{xxx} options make sense,
11203 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11204 process a source file that uses Latin-2 coding for identifiers.
11205 @end ifclear
11206
11207 @item ^-h^/HELP^
11208 Causes @code{gnatchop} to generate a brief help summary to the standard
11209 output file showing usage information.
11210
11211 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11212 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11213 Limit generated file names to the specified number @code{mm}
11214 of characters.
11215 This is useful if the
11216 resulting set of files is required to be interoperable with systems
11217 which limit the length of file names.
11218 @ifset vms
11219 If no value is given, or
11220 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11221 a default of 39, suitable for OpenVMS Alpha
11222 Systems, is assumed
11223 @end ifset
11224 @ifclear vms
11225 No space is allowed between the @option{-k} and the numeric value. The numeric
11226 value may be omitted in which case a default of @option{-k8},
11227 suitable for use
11228 with DOS-like file systems, is used. If no @option{-k} switch
11229 is present then
11230 there is no limit on the length of file names.
11231 @end ifclear
11232
11233 @item ^-p^/PRESERVE^
11234 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11235 Causes the file ^modification^creation^ time stamp of the input file to be
11236 preserved and used for the time stamp of the output file(s). This may be
11237 useful for preserving coherency of time stamps in an environment where
11238 @code{gnatchop} is used as part of a standard build process.
11239
11240 @item ^-q^/QUIET^
11241 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11242 Causes output of informational messages indicating the set of generated
11243 files to be suppressed. Warnings and error messages are unaffected.
11244
11245 @item ^-r^/REFERENCE^
11246 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11247 @findex Source_Reference
11248 Generate @code{Source_Reference} pragmas. Use this switch if the output
11249 files are regarded as temporary and development is to be done in terms
11250 of the original unchopped file. This switch causes
11251 @code{Source_Reference} pragmas to be inserted into each of the
11252 generated files to refers back to the original file name and line number.
11253 The result is that all error messages refer back to the original
11254 unchopped file.
11255 In addition, the debugging information placed into the object file (when
11256 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11257 specified)
11258 also refers back to this original file so that tools like profilers and
11259 debuggers will give information in terms of the original unchopped file.
11260
11261 If the original file to be chopped itself contains
11262 a @code{Source_Reference}
11263 pragma referencing a third file, then gnatchop respects
11264 this pragma, and the generated @code{Source_Reference} pragmas
11265 in the chopped file refer to the original file, with appropriate
11266 line numbers. This is particularly useful when @code{gnatchop}
11267 is used in conjunction with @code{gnatprep} to compile files that
11268 contain preprocessing statements and multiple units.
11269
11270 @item ^-v^/VERBOSE^
11271 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11272 Causes @code{gnatchop} to operate in verbose mode. The version
11273 number and copyright notice are output, as well as exact copies of
11274 the gnat1 commands spawned to obtain the chop control information.
11275
11276 @item ^-w^/OVERWRITE^
11277 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11278 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11279 fatal error if there is already a file with the same name as a
11280 file it would otherwise output, in other words if the files to be
11281 chopped contain duplicated units. This switch bypasses this
11282 check, and causes all but the last instance of such duplicated
11283 units to be skipped.
11284
11285 @ifclear vms
11286 @item --GCC=@var{xxxx}
11287 @cindex @option{--GCC=} (@code{gnatchop})
11288 Specify the path of the GNAT parser to be used. When this switch is used,
11289 no attempt is made to add the prefix to the GNAT parser executable.
11290 @end ifclear
11291 @end table
11292
11293 @node Examples of gnatchop Usage
11294 @section Examples of @code{gnatchop} Usage
11295
11296 @table @code
11297 @ifset vms
11298 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11299 @end ifset
11300 @ifclear vms
11301 @item gnatchop -w hello_s.ada prerelease/files
11302 @end ifclear
11303
11304 Chops the source file @file{hello_s.ada}. The output files will be
11305 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11306 overwriting any
11307 files with matching names in that directory (no files in the current
11308 directory are modified).
11309
11310 @item gnatchop ^archive^ARCHIVE.^
11311 Chops the source file @file{^archive^ARCHIVE.^}
11312 into the current directory. One
11313 useful application of @code{gnatchop} is in sending sets of sources
11314 around, for example in email messages. The required sources are simply
11315 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11316 command), and then
11317 @command{gnatchop} is used at the other end to reconstitute the original
11318 file names.
11319
11320 @item gnatchop file1 file2 file3 direc
11321 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11322 the resulting files in the directory @file{direc}. Note that if any units
11323 occur more than once anywhere within this set of files, an error message
11324 is generated, and no files are written. To override this check, use the
11325 @option{^-w^/OVERWRITE^} switch,
11326 in which case the last occurrence in the last file will
11327 be the one that is output, and earlier duplicate occurrences for a given
11328 unit will be skipped.
11329 @end table
11330
11331 @node Configuration Pragmas
11332 @chapter Configuration Pragmas
11333 @cindex Configuration pragmas
11334 @cindex Pragmas, configuration
11335
11336 @noindent
11337 Configuration pragmas include those pragmas described as
11338 such in the Ada Reference Manual, as well as
11339 implementation-dependent pragmas that are configuration pragmas.
11340 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11341 for details on these additional GNAT-specific configuration pragmas.
11342 Most notably, the pragma @code{Source_File_Name}, which allows
11343 specifying non-default names for source files, is a configuration
11344 pragma. The following is a complete list of configuration pragmas
11345 recognized by GNAT:
11346
11347 @smallexample
11348    Ada_83
11349    Ada_95
11350    Ada_05
11351    Ada_2005
11352    Assertion_Policy
11353    Assume_No_Invalid_Values
11354    C_Pass_By_Copy
11355    Check_Name
11356    Check_Policy
11357    Compile_Time_Error
11358    Compile_Time_Warning
11359    Compiler_Unit
11360    Component_Alignment
11361    Convention_Identifier
11362    Debug_Policy
11363    Detect_Blocking
11364    Discard_Names
11365    Elaboration_Checks
11366    Eliminate
11367    Extend_System
11368    Extensions_Allowed
11369    External_Name_Casing
11370    Fast_Math
11371    Favor_Top_Level
11372    Float_Representation
11373    Implicit_Packing
11374    Initialize_Scalars
11375    Interrupt_State
11376    License
11377    Locking_Policy
11378    Long_Float
11379    No_Run_Time
11380    No_Strict_Aliasing
11381    Normalize_Scalars
11382    Optimize_Alignment
11383    Persistent_BSS
11384    Polling
11385    Priority_Specific_Dispatching
11386    Profile
11387    Profile_Warnings
11388    Propagate_Exceptions
11389    Queuing_Policy
11390    Ravenscar
11391    Restricted_Run_Time
11392    Restrictions
11393    Restrictions_Warnings
11394    Reviewable
11395    Source_File_Name
11396    Source_File_Name_Project
11397    Style_Checks
11398    Suppress
11399    Suppress_Exception_Locations
11400    Task_Dispatching_Policy
11401    Universal_Data
11402    Unsuppress
11403    Use_VADS_Size
11404    Validity_Checks
11405    Warnings
11406    Wide_Character_Encoding
11407
11408 @end smallexample
11409
11410 @menu
11411 * Handling of Configuration Pragmas::
11412 * The Configuration Pragmas Files::
11413 @end menu
11414
11415 @node Handling of Configuration Pragmas
11416 @section Handling of Configuration Pragmas
11417
11418 Configuration pragmas may either appear at the start of a compilation
11419 unit, in which case they apply only to that unit, or they may apply to
11420 all compilations performed in a given compilation environment.
11421
11422 GNAT also provides the @code{gnatchop} utility to provide an automatic
11423 way to handle configuration pragmas following the semantics for
11424 compilations (that is, files with multiple units), described in the RM.
11425 See @ref{Operating gnatchop in Compilation Mode} for details.
11426 However, for most purposes, it will be more convenient to edit the
11427 @file{gnat.adc} file that contains configuration pragmas directly,
11428 as described in the following section.
11429
11430 @node The Configuration Pragmas Files
11431 @section The Configuration Pragmas Files
11432 @cindex @file{gnat.adc}
11433
11434 @noindent
11435 In GNAT a compilation environment is defined by the current
11436 directory at the time that a compile command is given. This current
11437 directory is searched for a file whose name is @file{gnat.adc}. If
11438 this file is present, it is expected to contain one or more
11439 configuration pragmas that will be applied to the current compilation.
11440 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11441 considered.
11442
11443 Configuration pragmas may be entered into the @file{gnat.adc} file
11444 either by running @code{gnatchop} on a source file that consists only of
11445 configuration pragmas, or more conveniently  by
11446 direct editing of the @file{gnat.adc} file, which is a standard format
11447 source file.
11448
11449 In addition to @file{gnat.adc}, additional files containing configuration
11450 pragmas may be applied to the current compilation using the switch
11451 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11452 contains only configuration pragmas. These configuration pragmas are
11453 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11454 is present and switch @option{-gnatA} is not used).
11455
11456 It is allowed to specify several switches @option{-gnatec}, all of which
11457 will be taken into account.
11458
11459 If you are using project file, a separate mechanism is provided using
11460 project attributes, see @ref{Specifying Configuration Pragmas} for more
11461 details.
11462
11463 @ifset vms
11464 Of special interest to GNAT OpenVMS Alpha is the following
11465 configuration pragma:
11466
11467 @smallexample @c ada
11468 @cartouche
11469 pragma Extend_System (Aux_DEC);
11470 @end cartouche
11471 @end smallexample
11472
11473 @noindent
11474 In the presence of this pragma, GNAT adds to the definition of the
11475 predefined package SYSTEM all the additional types and subprograms that are
11476 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11477 @end ifset
11478
11479 @node Handling Arbitrary File Naming Conventions Using gnatname
11480 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11481 @cindex Arbitrary File Naming Conventions
11482
11483 @menu
11484 * Arbitrary File Naming Conventions::
11485 * Running gnatname::
11486 * Switches for gnatname::
11487 * Examples of gnatname Usage::
11488 @end menu
11489
11490 @node Arbitrary File Naming Conventions
11491 @section Arbitrary File Naming Conventions
11492
11493 @noindent
11494 The GNAT compiler must be able to know the source file name of a compilation
11495 unit.  When using the standard GNAT default file naming conventions
11496 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11497 does not need additional information.
11498
11499 @noindent
11500 When the source file names do not follow the standard GNAT default file naming
11501 conventions, the GNAT compiler must be given additional information through
11502 a configuration pragmas file (@pxref{Configuration Pragmas})
11503 or a project file.
11504 When the non-standard file naming conventions are well-defined,
11505 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11506 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11507 if the file naming conventions are irregular or arbitrary, a number
11508 of pragma @code{Source_File_Name} for individual compilation units
11509 must be defined.
11510 To help maintain the correspondence between compilation unit names and
11511 source file names within the compiler,
11512 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11513 set of files.
11514
11515 @node Running gnatname
11516 @section Running @code{gnatname}
11517
11518 @noindent
11519 The usual form of the @code{gnatname} command is
11520
11521 @smallexample
11522 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11523 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11524 @c Expanding @ovar macro inline (explanation in macro def comments)
11525 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11526       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11527 @end smallexample
11528
11529 @noindent
11530 All of the arguments are optional. If invoked without any argument,
11531 @code{gnatname} will display its usage.
11532
11533 @noindent
11534 When used with at least one naming pattern, @code{gnatname} will attempt to
11535 find all the compilation units in files that follow at least one of the
11536 naming patterns. To find these compilation units,
11537 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11538 regular files.
11539
11540 @noindent
11541 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11542 Each Naming Pattern is enclosed between double quotes.
11543 A Naming Pattern is a regular expression similar to the wildcard patterns
11544 used in file names by the Unix shells or the DOS prompt.
11545
11546 @noindent
11547 @code{gnatname} may be called with several sections of directories/patterns.
11548 Sections are separated by switch @code{--and}. In each section, there must be
11549 at least one pattern. If no directory is specified in a section, the current
11550 directory (or the project directory is @code{-P} is used) is implied.
11551 The options other that the directory switches and the patterns apply globally
11552 even if they are in different sections.
11553
11554 @noindent
11555 Examples of Naming Patterns are
11556
11557 @smallexample
11558    "*.[12].ada"
11559    "*.ad[sb]*"
11560    "body_*"    "spec_*"
11561 @end smallexample
11562
11563 @noindent
11564 For a more complete description of the syntax of Naming Patterns,
11565 see the second kind of regular expressions described in @file{g-regexp.ads}
11566 (the ``Glob'' regular expressions).
11567
11568 @noindent
11569 When invoked with no switch @code{-P}, @code{gnatname} will create a
11570 configuration pragmas file @file{gnat.adc} in the current working directory,
11571 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11572 unit.
11573
11574 @node Switches for gnatname
11575 @section Switches for @code{gnatname}
11576
11577 @noindent
11578 Switches for @code{gnatname} must precede any specified Naming Pattern.
11579
11580 @noindent
11581 You may specify any of the following switches to @code{gnatname}:
11582
11583 @table @option
11584 @c !sort!
11585
11586 @item --version
11587 @cindex @option{--version} @command{gnatname}
11588 Display Copyright and version, then exit disregarding all other options.
11589
11590 @item --help
11591 @cindex @option{--help} @command{gnatname}
11592 If @option{--version} was not used, display usage, then exit disregarding
11593 all other options.
11594
11595 @item --and
11596 Start another section of directories/patterns.
11597
11598 @item ^-c^/CONFIG_FILE=^@file{file}
11599 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11600 Create a configuration pragmas file @file{file} (instead of the default
11601 @file{gnat.adc}).
11602 @ifclear vms
11603 There may be zero, one or more space between @option{-c} and
11604 @file{file}.
11605 @end ifclear
11606 @file{file} may include directory information. @file{file} must be
11607 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11608 When a switch @option{^-c^/CONFIG_FILE^} is
11609 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11610
11611 @item ^-d^/SOURCE_DIRS=^@file{dir}
11612 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11613 Look for source files in directory @file{dir}. There may be zero, one or more
11614 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11615 When a switch @option{^-d^/SOURCE_DIRS^}
11616 is specified, the current working directory will not be searched for source
11617 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11618 or @option{^-D^/DIR_FILES^} switch.
11619 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11620 If @file{dir} is a relative path, it is relative to the directory of
11621 the configuration pragmas file specified with switch
11622 @option{^-c^/CONFIG_FILE^},
11623 or to the directory of the project file specified with switch
11624 @option{^-P^/PROJECT_FILE^} or,
11625 if neither switch @option{^-c^/CONFIG_FILE^}
11626 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11627 current working directory. The directory
11628 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11629
11630 @item ^-D^/DIRS_FILE=^@file{file}
11631 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11632 Look for source files in all directories listed in text file @file{file}.
11633 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11634 and @file{file}.
11635 @file{file} must be an existing, readable text file.
11636 Each nonempty line in @file{file} must be a directory.
11637 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11638 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11639 @file{file}.
11640
11641 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11642 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11643 Foreign patterns. Using this switch, it is possible to add sources of languages
11644 other than Ada to the list of sources of a project file.
11645 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11646 For example,
11647 @smallexample
11648 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11649 @end smallexample
11650 @noindent
11651 will look for Ada units in all files with the @file{.ada} extension,
11652 and will add to the list of file for project @file{prj.gpr} the C files
11653 with extension @file{.^c^C^}.
11654
11655 @item ^-h^/HELP^
11656 @cindex @option{^-h^/HELP^} (@code{gnatname})
11657 Output usage (help) information. The output is written to @file{stdout}.
11658
11659 @item ^-P^/PROJECT_FILE=^@file{proj}
11660 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11661 Create or update project file @file{proj}. There may be zero, one or more space
11662 between @option{-P} and @file{proj}. @file{proj} may include directory
11663 information. @file{proj} must be writable.
11664 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11665 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11666 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11667
11668 @item ^-v^/VERBOSE^
11669 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11670 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11671 This includes name of the file written, the name of the directories to search
11672 and, for each file in those directories whose name matches at least one of
11673 the Naming Patterns, an indication of whether the file contains a unit,
11674 and if so the name of the unit.
11675
11676 @item ^-v -v^/VERBOSE /VERBOSE^
11677 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11678 Very Verbose mode. In addition to the output produced in verbose mode,
11679 for each file in the searched directories whose name matches none of
11680 the Naming Patterns, an indication is given that there is no match.
11681
11682 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11683 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11684 Excluded patterns. Using this switch, it is possible to exclude some files
11685 that would match the name patterns. For example,
11686 @smallexample
11687 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11688 @end smallexample
11689 @noindent
11690 will look for Ada units in all files with the @file{.ada} extension,
11691 except those whose names end with @file{_nt.ada}.
11692
11693 @end table
11694
11695 @node Examples of gnatname Usage
11696 @section Examples of @code{gnatname} Usage
11697
11698 @ifset vms
11699 @smallexample
11700 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11701 @end smallexample
11702 @end ifset
11703
11704 @ifclear vms
11705 @smallexample
11706 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11707 @end smallexample
11708 @end ifclear
11709
11710 @noindent
11711 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11712 and be writable. In addition, the directory
11713 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11714 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11715
11716 @ifclear vms
11717 Note the optional spaces after @option{-c} and @option{-d}.
11718 @end ifclear
11719
11720 @smallexample
11721 @ifclear vms
11722 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11723   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11724 @end ifclear
11725 @ifset vms
11726 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11727   /EXCLUDED_PATTERN=*_nt_body.ada
11728   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11729   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11730 @end ifset
11731 @end smallexample
11732
11733 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11734 even in conjunction with one or several switches
11735 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11736 are used in this example.
11737
11738 @c *****************************************
11739 @c * G N A T  P r o j e c t  M a n a g e r *
11740 @c *****************************************
11741 @node GNAT Project Manager
11742 @chapter GNAT Project Manager
11743
11744 @menu
11745 * Introduction::
11746 * Examples of Project Files::
11747 * Project File Syntax::
11748 * Objects and Sources in Project Files::
11749 * Importing Projects::
11750 * Project Extension::
11751 * Project Hierarchy Extension::
11752 * External References in Project Files::
11753 * Packages in Project Files::
11754 * Variables from Imported Projects::
11755 * Naming Schemes::
11756 * Library Projects::
11757 * Stand-alone Library Projects::
11758 * Switches Related to Project Files::
11759 * Tools Supporting Project Files::
11760 * An Extended Example::
11761 * Project File Complete Syntax::
11762 @end menu
11763
11764 @c ****************
11765 @c * Introduction *
11766 @c ****************
11767
11768 @node Introduction
11769 @section Introduction
11770
11771 @noindent
11772 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11773 you to manage complex builds involving a number of source files, directories,
11774 and compilation options for different system configurations. In particular,
11775 project files allow you to specify:
11776 @itemize @bullet
11777 @item
11778 The directory or set of directories containing the source files, and/or the
11779 names of the specific source files themselves
11780 @item
11781 The directory in which the compiler's output
11782 (@file{ALI} files, object files, tree files) is to be placed
11783 @item
11784 The directory in which the executable programs is to be placed
11785 @item
11786 ^Switch^Switch^ settings for any of the project-enabled tools
11787 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11788 @code{gnatfind}); you can apply these settings either globally or to individual
11789 compilation units.
11790 @item
11791 The source files containing the main subprogram(s) to be built
11792 @item
11793 The source programming language(s) (currently Ada and/or C)
11794 @item
11795 Source file naming conventions; you can specify these either globally or for
11796 individual compilation units
11797 @end itemize
11798
11799 @menu
11800 * Project Files::
11801 @end menu
11802
11803 @node Project Files
11804 @subsection Project Files
11805
11806 @noindent
11807 Project files are written in a syntax close to that of Ada, using  familiar
11808 notions such as packages, context clauses, declarations, default values,
11809 assignments, and inheritance. Finally, project files can be built
11810 hierarchically from other project files, simplifying complex system
11811 integration and project reuse.
11812
11813 A @dfn{project} is a specific set of values for various compilation properties.
11814 The settings for a given project are described by means of
11815 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11816 Property values in project files are either strings or lists of strings.
11817 Properties that are not explicitly set receive default values.  A project
11818 file may interrogate the values of @dfn{external variables} (user-defined
11819 command-line switches or environment variables), and it may specify property
11820 settings conditionally, based on the value of such variables.
11821
11822 In simple cases, a project's source files depend only on other source files
11823 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11824 used in
11825 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11826 the Project Manager also allows more sophisticated arrangements,
11827 where the source files in one project depend on source files in other
11828 projects:
11829 @itemize @bullet
11830 @item
11831 One project can @emph{import} other projects containing needed source files.
11832 @item
11833 You can organize GNAT projects in a hierarchy: a @emph{child} project
11834 can extend a @emph{parent} project, inheriting the parent's source files and
11835 optionally overriding any of them with alternative versions
11836 @end itemize
11837
11838 @noindent
11839 More generally, the Project Manager lets you structure large development
11840 efforts into hierarchical subsystems, where build decisions are delegated
11841 to the subsystem level, and thus different compilation environments
11842 (^switch^switch^ settings) used for different subsystems.
11843
11844 The Project Manager is invoked through the
11845 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11846 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11847 @ifclear vms
11848 There may be zero, one or more spaces between @option{-P} and
11849 @option{@emph{projectfile}}.
11850 @end ifclear
11851 If you want to define (on the command line) an external variable that is
11852 queried by the project file, you must use the
11853 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11854 The Project Manager parses and interprets the project file, and drives the
11855 invoked tool based on the project settings.
11856
11857 The Project Manager supports a wide range of development strategies,
11858 for systems of all sizes.  Here are some typical practices that are
11859 easily handled:
11860 @itemize @bullet
11861 @item
11862 Using a common set of source files, but generating object files in different
11863 directories via different ^switch^switch^ settings
11864 @item
11865 Using a mostly-shared set of source files, but with different versions of
11866 some unit or units
11867 @end itemize
11868
11869 @noindent
11870 The destination of an executable can be controlled inside a project file
11871 using the @option{^-o^-o^}
11872 ^switch^switch^.
11873 In the absence of such a ^switch^switch^ either inside
11874 the project file or on the command line, any executable files generated by
11875 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11876 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11877 in the object directory of the project.
11878
11879 You can use project files to achieve some of the effects of a source
11880 versioning system (for example, defining separate projects for
11881 the different sets of sources that comprise different releases) but the
11882 Project Manager is independent of any source configuration management tools
11883 that might be used by the developers.
11884
11885 The next section introduces the main features of GNAT's project facility
11886 through a sequence of examples; subsequent sections will present the syntax
11887 and semantics in more detail. A more formal description of the project
11888 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11889 Reference Manual}.
11890
11891 @c *****************************
11892 @c * Examples of Project Files *
11893 @c *****************************
11894
11895 @node Examples of Project Files
11896 @section Examples of Project Files
11897 @noindent
11898 This section illustrates some of the typical uses of project files and
11899 explains their basic structure and behavior.
11900
11901 @menu
11902 * Common Sources with Different ^Switches^Switches^ and Directories::
11903 * Using External Variables::
11904 * Importing Other Projects::
11905 * Extending a Project::
11906 @end menu
11907
11908 @node Common Sources with Different ^Switches^Switches^ and Directories
11909 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11910
11911 @menu
11912 * Source Files::
11913 * Specifying the Object Directory::
11914 * Specifying the Exec Directory::
11915 * Project File Packages::
11916 * Specifying ^Switch^Switch^ Settings::
11917 * Main Subprograms::
11918 * Executable File Names::
11919 * Source File Naming Conventions::
11920 * Source Language(s)::
11921 @end menu
11922
11923 @noindent
11924 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11925 @file{proc.adb} are in the @file{/common} directory.  The file
11926 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11927 package @code{Pack}.  We want to compile these source files under two sets
11928 of ^switches^switches^:
11929 @itemize @bullet
11930 @item
11931 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11932 and the @option{^-gnata^-gnata^},
11933 @option{^-gnato^-gnato^},
11934 and @option{^-gnatE^-gnatE^} switches to the
11935 compiler; the compiler's output is to appear in @file{/common/debug}
11936 @item
11937 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11938 to the compiler; the compiler's output is to appear in @file{/common/release}
11939 @end itemize
11940
11941 @noindent
11942 The GNAT project files shown below, respectively @file{debug.gpr} and
11943 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11944
11945 Schematically:
11946 @smallexample
11947 @group
11948 ^/common^[COMMON]^
11949   debug.gpr
11950   release.gpr
11951   pack.ads
11952   pack.adb
11953   proc.adb
11954 @end group
11955 @group
11956 ^/common/debug^[COMMON.DEBUG]^
11957   proc.ali, proc.o
11958   pack.ali, pack.o
11959 @end group
11960 @group
11961 ^/common/release^[COMMON.RELEASE]^
11962   proc.ali, proc.o
11963   pack.ali, pack.o
11964 @end group
11965 @end smallexample
11966 Here are the corresponding project files:
11967
11968 @smallexample @c projectfile
11969 @group
11970 project Debug is
11971   for Object_Dir use "debug";
11972   for Main use ("proc");
11973
11974   package Builder is
11975     for ^Default_Switches^Default_Switches^ ("Ada")
11976         use ("^-g^-g^");
11977     for Executable ("proc.adb") use "proc1";
11978   end Builder;
11979 @end group
11980
11981 @group
11982   package Compiler is
11983     for ^Default_Switches^Default_Switches^ ("Ada")
11984        use ("-fstack-check",
11985             "^-gnata^-gnata^",
11986             "^-gnato^-gnato^",
11987             "^-gnatE^-gnatE^");
11988   end Compiler;
11989 end Debug;
11990 @end group
11991 @end smallexample
11992
11993 @smallexample @c projectfile
11994 @group
11995 project Release is
11996   for Object_Dir use "release";
11997   for Exec_Dir use ".";
11998   for Main use ("proc");
11999
12000   package Compiler is
12001     for ^Default_Switches^Default_Switches^ ("Ada")
12002         use ("^-O2^-O2^");
12003   end Compiler;
12004 end Release;
12005 @end group
12006 @end smallexample
12007
12008 @noindent
12009 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
12010 insensitive), and analogously the project defined by @file{release.gpr} is
12011 @code{"Release"}.  For consistency the file should have the same name as the
12012 project, and the project file's extension should be @code{"gpr"}. These
12013 conventions are not required, but a warning is issued if they are not followed.
12014
12015 If the current directory is @file{^/temp^[TEMP]^}, then the command
12016 @smallexample
12017 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12018 @end smallexample
12019
12020 @noindent
12021 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12022 as well as the @code{^proc1^PROC1.EXE^} executable,
12023 using the ^switch^switch^ settings defined in the project file.
12024
12025 Likewise, the command
12026 @smallexample
12027 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12028 @end smallexample
12029
12030 @noindent
12031 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12032 and the @code{^proc^PROC.EXE^}
12033 executable in @file{^/common^[COMMON]^},
12034 using the ^switch^switch^ settings from the project file.
12035
12036 @node Source Files
12037 @unnumberedsubsubsec Source Files
12038
12039 @noindent
12040 If a project file does not explicitly specify a set of source directories or
12041 a set of source files, then by default the project's source files are the
12042 Ada source files in the project file directory.  Thus @file{pack.ads},
12043 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12044
12045 @node Specifying the Object Directory
12046 @unnumberedsubsubsec Specifying the Object Directory
12047
12048 @noindent
12049 Several project properties are modeled by Ada-style @emph{attributes};
12050 a property is defined by supplying the equivalent of an Ada attribute
12051 definition clause in the project file.
12052 A project's object directory is another such a property; the corresponding
12053 attribute is @code{Object_Dir}, and its value is also a string expression,
12054 specified either as absolute or relative. In the later case,
12055 it is relative to the project file directory. Thus the compiler's
12056 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12057 (for the @code{Debug} project)
12058 and to @file{^/common/release^[COMMON.RELEASE]^}
12059 (for the @code{Release} project).
12060 If @code{Object_Dir} is not specified, then the default is the project file
12061 directory itself.
12062
12063 @node Specifying the Exec Directory
12064 @unnumberedsubsubsec Specifying the Exec Directory
12065
12066 @noindent
12067 A project's exec directory is another property; the corresponding
12068 attribute is @code{Exec_Dir}, and its value is also a string expression,
12069 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12070 then the default is the object directory (which may also be the project file
12071 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12072 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12073 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12074 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12075
12076 @node Project File Packages
12077 @unnumberedsubsubsec Project File Packages
12078
12079 @noindent
12080 A GNAT tool that is integrated with the Project Manager is modeled by a
12081 corresponding package in the project file. In the example above,
12082 The @code{Debug} project defines the packages @code{Builder}
12083 (for @command{gnatmake}) and @code{Compiler};
12084 the @code{Release} project defines only the @code{Compiler} package.
12085
12086 The Ada-like package syntax is not to be taken literally.  Although packages in
12087 project files bear a surface resemblance to packages in Ada source code, the
12088 notation is simply a way to convey a grouping of properties for a named
12089 entity.  Indeed, the package names permitted in project files are restricted
12090 to a predefined set, corresponding to the project-aware tools, and the contents
12091 of packages are limited to a small set of constructs.
12092 The packages in the example above contain attribute definitions.
12093
12094 @node Specifying ^Switch^Switch^ Settings
12095 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12096
12097 @noindent
12098 ^Switch^Switch^ settings for a project-aware tool can be specified through
12099 attributes in the package that corresponds to the tool.
12100 The example above illustrates one of the relevant attributes,
12101 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12102 in both project files.
12103 Unlike simple attributes like @code{Source_Dirs},
12104 @code{^Default_Switches^Default_Switches^} is
12105 known as an @emph{associative array}.  When you define this attribute, you must
12106 supply an ``index'' (a literal string), and the effect of the attribute
12107 definition is to set the value of the array at the specified index.
12108 For the @code{^Default_Switches^Default_Switches^} attribute,
12109 the index is a programming language (in our case, Ada),
12110 and the value specified (after @code{use}) must be a list
12111 of string expressions.
12112
12113 The attributes permitted in project files are restricted to a predefined set.
12114 Some may appear at project level, others in packages.
12115 For any attribute that is an associative array, the index must always be a
12116 literal string, but the restrictions on this string (e.g., a file name or a
12117 language name) depend on the individual attribute.
12118 Also depending on the attribute, its specified value will need to be either a
12119 string or a string list.
12120
12121 In the @code{Debug} project, we set the switches for two tools,
12122 @command{gnatmake} and the compiler, and thus we include the two corresponding
12123 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12124 attribute with index @code{"Ada"}.
12125 Note that the package corresponding to
12126 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12127 similar, but only includes the @code{Compiler} package.
12128
12129 In project @code{Debug} above, the ^switches^switches^ starting with
12130 @option{-gnat} that are specified in package @code{Compiler}
12131 could have been placed in package @code{Builder}, since @command{gnatmake}
12132 transmits all such ^switches^switches^ to the compiler.
12133
12134 @node Main Subprograms
12135 @unnumberedsubsubsec Main Subprograms
12136
12137 @noindent
12138 One of the specifiable properties of a project is a list of files that contain
12139 main subprograms.  This property is captured in the @code{Main} attribute,
12140 whose value is a list of strings.  If a project defines the @code{Main}
12141 attribute, it is not necessary to identify the main subprogram(s) when
12142 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12143
12144 @node Executable File Names
12145 @unnumberedsubsubsec Executable File Names
12146
12147 @noindent
12148 By default, the executable file name corresponding to a main source is
12149 deduced from the main source file name. Through the attributes
12150 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12151 it is possible to change this default.
12152 In project @code{Debug} above, the executable file name
12153 for main source @file{^proc.adb^PROC.ADB^} is
12154 @file{^proc1^PROC1.EXE^}.
12155 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12156 of the executable files, when no attribute @code{Executable} applies:
12157 its value replace the platform-specific executable suffix.
12158 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12159 specify a non-default executable file name when several mains are built at once
12160 in a single @command{gnatmake} command.
12161
12162 @node Source File Naming Conventions
12163 @unnumberedsubsubsec Source File Naming Conventions
12164
12165 @noindent
12166 Since the project files above do not specify any source file naming
12167 conventions, the GNAT defaults are used.  The mechanism for defining source
12168 file naming conventions -- a package named @code{Naming} --
12169 is described below (@pxref{Naming Schemes}).
12170
12171 @node Source Language(s)
12172 @unnumberedsubsubsec Source Language(s)
12173
12174 @noindent
12175 Since the project files do not specify a @code{Languages} attribute, by
12176 default the GNAT tools assume that the language of the project file is Ada.
12177 More generally, a project can comprise source files
12178 in Ada, C, and/or other languages.
12179
12180 @node Using External Variables
12181 @subsection Using External Variables
12182
12183 @noindent
12184 Instead of supplying different project files for debug and release, we can
12185 define a single project file that queries an external variable (set either
12186 on the command line or via an ^environment variable^logical name^) in order to
12187 conditionally define the appropriate settings.  Again, assume that the
12188 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12189 located in directory @file{^/common^[COMMON]^}.  The following project file,
12190 @file{build.gpr}, queries the external variable named @code{STYLE} and
12191 defines an object directory and ^switch^switch^ settings based on whether
12192 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12193 the default is @code{"deb"}.
12194
12195 @smallexample @c projectfile
12196 @group
12197 project Build is
12198   for Main use ("proc");
12199
12200   type Style_Type is ("deb", "rel");
12201   Style : Style_Type := external ("STYLE", "deb");
12202
12203   case Style is
12204     when "deb" =>
12205       for Object_Dir use "debug";
12206
12207     when "rel" =>
12208       for Object_Dir use "release";
12209       for Exec_Dir use ".";
12210   end case;
12211 @end group
12212
12213 @group
12214   package Builder is
12215
12216     case Style is
12217       when "deb" =>
12218         for ^Default_Switches^Default_Switches^ ("Ada")
12219             use ("^-g^-g^");
12220         for Executable ("proc") use "proc1";
12221       when others =>
12222         null;
12223     end case;
12224
12225   end Builder;
12226 @end group
12227
12228 @group
12229   package Compiler is
12230
12231     case Style is
12232       when "deb" =>
12233         for ^Default_Switches^Default_Switches^ ("Ada")
12234             use ("^-gnata^-gnata^",
12235                  "^-gnato^-gnato^",
12236                  "^-gnatE^-gnatE^");
12237
12238       when "rel" =>
12239         for ^Default_Switches^Default_Switches^ ("Ada")
12240             use ("^-O2^-O2^");
12241     end case;
12242
12243   end Compiler;
12244
12245 end Build;
12246 @end group
12247 @end smallexample
12248
12249 @noindent
12250 @code{Style_Type} is an example of a @emph{string type}, which is the project
12251 file analog of an Ada enumeration type but whose components are string literals
12252 rather than identifiers.  @code{Style} is declared as a variable of this type.
12253
12254 The form @code{external("STYLE", "deb")} is known as an
12255 @emph{external reference}; its first argument is the name of an
12256 @emph{external variable}, and the second argument is a default value to be
12257 used if the external variable doesn't exist.  You can define an external
12258 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12259 or you can use ^an environment variable^a logical name^
12260 as an external variable.
12261
12262 Each @code{case} construct is expanded by the Project Manager based on the
12263 value of @code{Style}. Thus the command
12264 @ifclear vms
12265 @smallexample
12266 gnatmake -P/common/build.gpr -XSTYLE=deb
12267 @end smallexample
12268 @end ifclear
12269
12270 @ifset vms
12271 @smallexample
12272 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12273 @end smallexample
12274 @end ifset
12275
12276 @noindent
12277 is equivalent to the @command{gnatmake} invocation using the project file
12278 @file{debug.gpr} in the earlier example.  So is the command
12279 @smallexample
12280 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12281 @end smallexample
12282
12283 @noindent
12284 since @code{"deb"} is the default for @code{STYLE}.
12285
12286 Analogously,
12287
12288 @ifclear vms
12289 @smallexample
12290 gnatmake -P/common/build.gpr -XSTYLE=rel
12291 @end smallexample
12292 @end ifclear
12293
12294 @ifset vms
12295 @smallexample
12296 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12297 @end smallexample
12298 @end ifset
12299
12300 @noindent
12301 is equivalent to the @command{gnatmake} invocation using the project file
12302 @file{release.gpr} in the earlier example.
12303
12304 @node Importing Other Projects
12305 @subsection Importing Other Projects
12306 @cindex @code{ADA_PROJECT_PATH}
12307 @cindex @code{GPR_PROJECT_PATH}
12308
12309 @noindent
12310 A compilation unit in a source file in one project may depend on compilation
12311 units in source files in other projects.  To compile this unit under
12312 control of a project file, the
12313 dependent project must @emph{import} the projects containing the needed source
12314 files.
12315 This effect is obtained using syntax similar to an Ada @code{with} clause,
12316 but where @code{with}ed entities are strings that denote project files.
12317
12318 As an example, suppose that the two projects @code{GUI_Proj} and
12319 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12320 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12321 and @file{^/comm^[COMM]^}, respectively.
12322 Suppose that the source files for @code{GUI_Proj} are
12323 @file{gui.ads} and @file{gui.adb}, and that the source files for
12324 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12325 files is located in its respective project file directory.  Schematically:
12326
12327 @smallexample
12328 @group
12329 ^/gui^[GUI]^
12330   gui_proj.gpr
12331   gui.ads
12332   gui.adb
12333 @end group
12334
12335 @group
12336 ^/comm^[COMM]^
12337   comm_proj.gpr
12338   comm.ads
12339   comm.adb
12340 @end group
12341 @end smallexample
12342
12343 @noindent
12344 We want to develop an application in directory @file{^/app^[APP]^} that
12345 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12346 the corresponding project files (e.g.@: the ^switch^switch^ settings
12347 and object directory).
12348 Skeletal code for a main procedure might be something like the following:
12349
12350 @smallexample @c ada
12351 @group
12352 with GUI, Comm;
12353 procedure App_Main is
12354    @dots{}
12355 begin
12356    @dots{}
12357 end App_Main;
12358 @end group
12359 @end smallexample
12360
12361 @noindent
12362 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12363 effect:
12364
12365 @smallexample @c projectfile
12366 @group
12367 with "/gui/gui_proj", "/comm/comm_proj";
12368 project App_Proj is
12369    for Main use ("app_main");
12370 end App_Proj;
12371 @end group
12372 @end smallexample
12373
12374 @noindent
12375 Building an executable is achieved through the command:
12376 @smallexample
12377 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12378 @end smallexample
12379 @noindent
12380 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12381 in the directory where @file{app_proj.gpr} resides.
12382
12383 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12384 (as illustrated above) the @code{with} clause can omit the extension.
12385
12386 Our example specified an absolute path for each imported project file.
12387 Alternatively, the directory name of an imported object can be omitted
12388 if either
12389 @itemize @bullet
12390 @item
12391 The imported project file is in the same directory as the importing project
12392 file, or
12393 @item
12394 You have defined one or two ^environment variables^logical names^
12395 that includes the directory containing
12396 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12397 @code{ADA_PROJECT_PATH} is the same as
12398 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12399 directory names separated by colons (semicolons on Windows).
12400 @end itemize
12401
12402 @noindent
12403 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12404 to include @file{^/gui^[GUI]^} and
12405 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12406 as follows:
12407
12408 @smallexample @c projectfile
12409 @group
12410 with "gui_proj", "comm_proj";
12411 project App_Proj is
12412    for Main use ("app_main");
12413 end App_Proj;
12414 @end group
12415 @end smallexample
12416
12417 @noindent
12418 Importing other projects can create ambiguities.
12419 For example, the same unit might be present in different imported projects, or
12420 it might be present in both the importing project and in an imported project.
12421 Both of these conditions are errors.  Note that in the current version of
12422 the Project Manager, it is illegal to have an ambiguous unit even if the
12423 unit is never referenced by the importing project.  This restriction may be
12424 relaxed in a future release.
12425
12426 @node Extending a Project
12427 @subsection Extending a Project
12428
12429 @noindent
12430 In large software systems it is common to have multiple
12431 implementations of a common interface; in Ada terms, multiple versions of a
12432 package body for the same spec.  For example, one implementation
12433 might be safe for use in tasking programs, while another might only be used
12434 in sequential applications.  This can be modeled in GNAT using the concept
12435 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12436 another project (the ``parent'') then by default all source files of the
12437 parent project are inherited by the child, but the child project can
12438 override any of the parent's source files with new versions, and can also
12439 add new files.  This facility is the project analog of a type extension in
12440 Object-Oriented Programming.  Project hierarchies are permitted (a child
12441 project may be the parent of yet another project), and a project that
12442 inherits one project can also import other projects.
12443
12444 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12445 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12446 @file{pack.adb}, and @file{proc.adb}:
12447
12448 @smallexample
12449 @group
12450 ^/seq^[SEQ]^
12451   pack.ads
12452   pack.adb
12453   proc.adb
12454   seq_proj.gpr
12455 @end group
12456 @end smallexample
12457
12458 @noindent
12459 Note that the project file can simply be empty (that is, no attribute or
12460 package is defined):
12461
12462 @smallexample @c projectfile
12463 @group
12464 project Seq_Proj is
12465 end Seq_Proj;
12466 @end group
12467 @end smallexample
12468
12469 @noindent
12470 implying that its source files are all the Ada source files in the project
12471 directory.
12472
12473 Suppose we want to supply an alternate version of @file{pack.adb}, in
12474 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12475 @file{pack.ads} and @file{proc.adb}.  We can define a project
12476 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12477
12478 @smallexample
12479 @group
12480 ^/tasking^[TASKING]^
12481   pack.adb
12482   tasking_proj.gpr
12483 @end group
12484
12485 @group
12486 project Tasking_Proj extends "/seq/seq_proj" is
12487 end Tasking_Proj;
12488 @end group
12489 @end smallexample
12490
12491 @noindent
12492 The version of @file{pack.adb} used in a build depends on which project file
12493 is specified.
12494
12495 Note that we could have obtained the desired behavior using project import
12496 rather than project inheritance; a @code{base} project would contain the
12497 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12498 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12499 would import @code{base} and add a different version of @file{pack.adb}.  The
12500 choice depends on whether other sources in the original project need to be
12501 overridden.  If they do, then project extension is necessary, otherwise,
12502 importing is sufficient.
12503
12504 @noindent
12505 In a project file that extends another project file, it is possible to
12506 indicate that an inherited source is not part of the sources of the extending
12507 project. This is necessary sometimes when a package spec has been overloaded
12508 and no longer requires a body: in this case, it is necessary to indicate that
12509 the inherited body is not part of the sources of the project, otherwise there
12510 will be a compilation error when compiling the spec.
12511
12512 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12513 Its value is a string list: a list of file names. It is also possible to use
12514 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12515 the file name of a text file containing a list of file names, one per line.
12516
12517 @smallexample @c @projectfile
12518 project B extends "a" is
12519    for Source_Files use ("pkg.ads");
12520    --  New spec of Pkg does not need a completion
12521    for Excluded_Source_Files use ("pkg.adb");
12522 end B;
12523 @end smallexample
12524
12525 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12526 is still needed: if it is possible to build using @command{gnatmake} when such
12527 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12528 it is possible to remove the source completely from a system that includes
12529 project P.
12530
12531 @c ***********************
12532 @c * Project File Syntax *
12533 @c ***********************
12534
12535 @node Project File Syntax
12536 @section Project File Syntax
12537
12538 @menu
12539 * Basic Syntax::
12540 * Qualified Projects::
12541 * Packages::
12542 * Expressions::
12543 * String Types::
12544 * Variables::
12545 * Attributes::
12546 * Associative Array Attributes::
12547 * case Constructions::
12548 @end menu
12549
12550 @noindent
12551 This section describes the structure of project files.
12552
12553 A project may be an @emph{independent project}, entirely defined by a single
12554 project file. Any Ada source file in an independent project depends only
12555 on the predefined library and other Ada source files in the same project.
12556
12557 @noindent
12558 A project may also @dfn{depend on} other projects, in either or both of
12559 the following ways:
12560 @itemize @bullet
12561 @item It may import any number of projects
12562 @item It may extend at most one other project
12563 @end itemize
12564
12565 @noindent
12566 The dependence relation is a directed acyclic graph (the subgraph reflecting
12567 the ``extends'' relation is a tree).
12568
12569 A project's @dfn{immediate sources} are the source files directly defined by
12570 that project, either implicitly by residing in the project file's directory,
12571 or explicitly through any of the source-related attributes described below.
12572 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12573 of @var{proj} together with the immediate sources (unless overridden) of any
12574 project on which @var{proj} depends (either directly or indirectly).
12575
12576 @node Basic Syntax
12577 @subsection Basic Syntax
12578
12579 @noindent
12580 As seen in the earlier examples, project files have an Ada-like syntax.
12581 The minimal project file is:
12582 @smallexample @c projectfile
12583 @group
12584 project Empty is
12585
12586 end Empty;
12587 @end group
12588 @end smallexample
12589
12590 @noindent
12591 The identifier @code{Empty} is the name of the project.
12592 This project name must be present after the reserved
12593 word @code{end} at the end of the project file, followed by a semi-colon.
12594
12595 Any name in a project file, such as the project name or a variable name,
12596 has the same syntax as an Ada identifier.
12597
12598 The reserved words of project files are the Ada 95 reserved words plus
12599 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12600 reserved words currently used in project file syntax are:
12601
12602 @itemize @bullet
12603 @item
12604 @code{all}
12605 @item
12606 @code{at}
12607 @item
12608 @code{case}
12609 @item
12610 @code{end}
12611 @item
12612 @code{for}
12613 @item
12614 @code{is}
12615 @item
12616 @code{limited}
12617 @item
12618 @code{null}
12619 @item
12620 @code{others}
12621 @item
12622 @code{package}
12623 @item
12624 @code{renames}
12625 @item
12626 @code{type}
12627 @item
12628 @code{use}
12629 @item
12630 @code{when}
12631 @item
12632 @code{with}
12633 @end itemize
12634
12635 @noindent
12636 Comments in project files have the same syntax as in Ada, two consecutive
12637 hyphens through the end of the line.
12638
12639 @node Qualified Projects
12640 @subsection Qualified Projects
12641
12642 @noindent
12643 Before the reserved @code{project}, there may be one or two "qualifiers", that
12644 is identifiers or other reserved words, to qualify the project.
12645
12646 The current list of qualifiers is:
12647
12648 @itemize @bullet
12649 @item
12650 @code{abstract}: qualify a project with no sources. A qualified abstract
12651 project must either have no declaration of attributes @code{Source_Dirs},
12652 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12653 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12654 as empty. If it extends another project, the project it extends must also be a
12655 qualified abstract project.
12656
12657 @item
12658 @code{standard}: a standard project is a non library project with sources.
12659
12660 @item
12661 @code{aggregate}: for future extension
12662
12663 @item
12664 @code{aggregate library}: for future extension
12665
12666 @item
12667 @code{library}: a library project must declare both attributes
12668 @code{Library_Name} and @code{Library_Dir}.
12669
12670 @item
12671 @code{configuration}: a configuration project cannot be in a project tree.
12672 @end itemize
12673
12674 @node Packages
12675 @subsection Packages
12676
12677 @noindent
12678 A project file may contain @emph{packages}. The name of a package must be one
12679 of the identifiers from the following list. A package
12680 with a given name may only appear once in a project file. Package names are
12681 case insensitive. The following package names are legal:
12682
12683 @itemize @bullet
12684 @item
12685 @code{Naming}
12686 @item
12687 @code{Builder}
12688 @item
12689 @code{Compiler}
12690 @item
12691 @code{Binder}
12692 @item
12693 @code{Linker}
12694 @item
12695 @code{Finder}
12696 @item
12697 @code{Cross_Reference}
12698 @item
12699 @code{Check}
12700 @item
12701 @code{Eliminate}
12702 @item
12703 @code{Pretty_Printer}
12704 @item
12705 @code{Metrics}
12706 @item
12707 @code{gnatls}
12708 @item
12709 @code{gnatstub}
12710 @item
12711 @code{IDE}
12712 @item
12713 @code{Language_Processing}
12714 @end itemize
12715
12716 @noindent
12717 In its simplest form, a package may be empty:
12718
12719 @smallexample @c projectfile
12720 @group
12721 project Simple is
12722   package Builder is
12723   end Builder;
12724 end Simple;
12725 @end group
12726 @end smallexample
12727
12728 @noindent
12729 A package may contain @emph{attribute declarations},
12730 @emph{variable declarations} and @emph{case constructions}, as will be
12731 described below.
12732
12733 When there is ambiguity between a project name and a package name,
12734 the name always designates the project. To avoid possible confusion, it is
12735 always a good idea to avoid naming a project with one of the
12736 names allowed for packages or any name that starts with @code{gnat}.
12737
12738 @node Expressions
12739 @subsection Expressions
12740
12741 @noindent
12742 An @emph{expression} is either a @emph{string expression} or a
12743 @emph{string list expression}.
12744
12745 A @emph{string expression} is either a @emph{simple string expression} or a
12746 @emph{compound string expression}.
12747
12748 A @emph{simple string expression} is one of the following:
12749 @itemize @bullet
12750 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12751 @item A string-valued variable reference (@pxref{Variables})
12752 @item A string-valued attribute reference (@pxref{Attributes})
12753 @item An external reference (@pxref{External References in Project Files})
12754 @end itemize
12755
12756 @noindent
12757 A @emph{compound string expression} is a concatenation of string expressions,
12758 using the operator @code{"&"}
12759 @smallexample
12760        Path & "/" & File_Name & ".ads"
12761 @end smallexample
12762
12763 @noindent
12764 A @emph{string list expression} is either a
12765 @emph{simple string list expression} or a
12766 @emph{compound string list expression}.
12767
12768 A @emph{simple string list expression} is one of the following:
12769 @itemize @bullet
12770 @item A parenthesized list of zero or more string expressions,
12771 separated by commas
12772 @smallexample
12773    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12774    Empty_List := ();
12775 @end smallexample
12776 @item A string list-valued variable reference
12777 @item A string list-valued attribute reference
12778 @end itemize
12779
12780 @noindent
12781 A @emph{compound string list expression} is the concatenation (using
12782 @code{"&"}) of a simple string list expression and an expression.  Note that
12783 each term in a compound string list expression, except the first, may be
12784 either a string expression or a string list expression.
12785
12786 @smallexample @c projectfile
12787 @group
12788    File_Name_List := () & File_Name; --  One string in this list
12789    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12790    --  Two strings
12791    Big_List := File_Name_List & Extended_File_Name_List;
12792    --  Concatenation of two string lists: three strings
12793    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12794    --  Illegal: must start with a string list
12795 @end group
12796 @end smallexample
12797
12798 @node String Types
12799 @subsection String Types
12800
12801 @noindent
12802 A @emph{string type declaration} introduces a discrete set of string literals.
12803 If a string variable is declared to have this type, its value
12804 is restricted to the given set of literals.
12805
12806 Here is an example of a string type declaration:
12807
12808 @smallexample @c projectfile
12809    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12810 @end smallexample
12811
12812 @noindent
12813 Variables of a string type are called @emph{typed variables}; all other
12814 variables are called @emph{untyped variables}. Typed variables are
12815 particularly useful in @code{case} constructions, to support conditional
12816 attribute declarations.
12817 (@pxref{case Constructions}).
12818
12819 The string literals in the list are case sensitive and must all be different.
12820 They may include any graphic characters allowed in Ada, including spaces.
12821
12822 A string type may only be declared at the project level, not inside a package.
12823
12824 A string type may be referenced by its name if it has been declared in the same
12825 project file, or by an expanded name whose prefix is the name of the project
12826 in which it is declared.
12827
12828 @node Variables
12829 @subsection Variables
12830
12831 @noindent
12832 A variable may be declared at the project file level, or within a package.
12833 Here are some examples of variable declarations:
12834
12835 @smallexample @c projectfile
12836 @group
12837    This_OS : OS := external ("OS"); --  a typed variable declaration
12838    That_OS := "GNU/Linux";          --  an untyped variable declaration
12839 @end group
12840 @end smallexample
12841
12842 @noindent
12843 The syntax of a @emph{typed variable declaration} is identical to the Ada
12844 syntax for an object declaration. By contrast, the syntax of an untyped
12845 variable declaration is identical to an Ada assignment statement. In fact,
12846 variable declarations in project files have some of the characteristics of
12847 an assignment, in that successive declarations for the same variable are
12848 allowed. Untyped variable declarations do establish the expected kind of the
12849 variable (string or string list), and successive declarations for it must
12850 respect the initial kind.
12851
12852 @noindent
12853 A string variable declaration (typed or untyped) declares a variable
12854 whose value is a string. This variable may be used as a string expression.
12855 @smallexample @c projectfile
12856    File_Name       := "readme.txt";
12857    Saved_File_Name := File_Name & ".saved";
12858 @end smallexample
12859
12860 @noindent
12861 A string list variable declaration declares a variable whose value is a list
12862 of strings. The list may contain any number (zero or more) of strings.
12863
12864 @smallexample @c projectfile
12865    Empty_List := ();
12866    List_With_One_Element := ("^-gnaty^-gnaty^");
12867    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12868    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12869                  "pack2.ada", "util_.ada", "util.ada");
12870 @end smallexample
12871
12872 @noindent
12873 The same typed variable may not be declared more than once at project level,
12874 and it may not be declared more than once in any package; it is in effect
12875 a constant.
12876
12877 The same untyped variable may be declared several times. Declarations are
12878 elaborated in the order in which they appear, so  the new value replaces
12879 the old one, and any subsequent reference to the variable uses the new value.
12880 However, as noted above, if a variable has been declared as a string, all
12881 subsequent
12882 declarations must give it a string value. Similarly, if a variable has
12883 been declared as a string list, all subsequent declarations
12884 must give it a string list value.
12885
12886 A @emph{variable reference} may take several forms:
12887
12888 @itemize @bullet
12889 @item The simple variable name, for a variable in the current package (if any)
12890 or in the current project
12891 @item An expanded name, whose prefix is a context name.
12892 @end itemize
12893
12894 @noindent
12895 A @emph{context} may be one of the following:
12896
12897 @itemize @bullet
12898 @item The name of an existing package in the current project
12899 @item The name of an imported project of the current project
12900 @item The name of an ancestor project (i.e., a project extended by the current
12901 project, either directly or indirectly)
12902 @item An expanded name whose prefix is an imported/parent project name, and
12903 whose selector is a package name in that project.
12904 @end itemize
12905
12906 @noindent
12907 A variable reference may be used in an expression.
12908
12909 @node Attributes
12910 @subsection Attributes
12911
12912 @noindent
12913 A project (and its packages) may have @emph{attributes} that define
12914 the project's properties.  Some attributes have values that are strings;
12915 others have values that are string lists.
12916
12917 There are two categories of attributes: @emph{simple attributes}
12918 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12919
12920 Legal project attribute names, and attribute names for each legal package are
12921 listed below. Attributes names are case-insensitive.
12922
12923 The following attributes are defined on projects (all are simple attributes):
12924
12925 @multitable @columnfractions .4 .3
12926 @item @emph{Attribute Name}
12927 @tab @emph{Value}
12928 @item @code{Source_Files}
12929 @tab string list
12930 @item @code{Source_Dirs}
12931 @tab string list
12932 @item @code{Source_List_File}
12933 @tab string
12934 @item @code{Object_Dir}
12935 @tab string
12936 @item @code{Exec_Dir}
12937 @tab string
12938 @item @code{Excluded_Source_Dirs}
12939 @tab string list
12940 @item @code{Excluded_Source_Files}
12941 @tab string list
12942 @item @code{Excluded_Source_List_File}
12943 @tab string
12944 @item @code{Languages}
12945 @tab string list
12946 @item @code{Main}
12947 @tab string list
12948 @item @code{Library_Dir}
12949 @tab string
12950 @item @code{Library_Name}
12951 @tab string
12952 @item @code{Library_Kind}
12953 @tab string
12954 @item @code{Library_Version}
12955 @tab string
12956 @item @code{Library_Interface}
12957 @tab string
12958 @item @code{Library_Auto_Init}
12959 @tab string
12960 @item @code{Library_Options}
12961 @tab string list
12962 @item @code{Library_Src_Dir}
12963 @tab string
12964 @item @code{Library_ALI_Dir}
12965 @tab string
12966 @item @code{Library_GCC}
12967 @tab string
12968 @item @code{Library_Symbol_File}
12969 @tab string
12970 @item @code{Library_Symbol_Policy}
12971 @tab string
12972 @item @code{Library_Reference_Symbol_File}
12973 @tab string
12974 @item @code{Externally_Built}
12975 @tab string
12976 @end multitable
12977
12978 @noindent
12979 The following attributes are defined for package  @code{Naming}
12980 (@pxref{Naming Schemes}):
12981
12982 @multitable @columnfractions .4 .2 .2 .2
12983 @item Attribute Name @tab Category @tab Index @tab Value
12984 @item @code{Spec_Suffix}
12985 @tab associative array
12986 @tab language name
12987 @tab string
12988 @item @code{Body_Suffix}
12989 @tab associative array
12990 @tab language name
12991 @tab string
12992 @item @code{Separate_Suffix}
12993 @tab simple attribute
12994 @tab n/a
12995 @tab string
12996 @item @code{Casing}
12997 @tab simple attribute
12998 @tab n/a
12999 @tab string
13000 @item @code{Dot_Replacement}
13001 @tab simple attribute
13002 @tab n/a
13003 @tab string
13004 @item @code{Spec}
13005 @tab associative array
13006 @tab Ada unit name
13007 @tab string
13008 @item @code{Body}
13009 @tab associative array
13010 @tab Ada unit name
13011 @tab string
13012 @item @code{Specification_Exceptions}
13013 @tab associative array
13014 @tab language name
13015 @tab string list
13016 @item @code{Implementation_Exceptions}
13017 @tab associative array
13018 @tab language name
13019 @tab string list
13020 @end multitable
13021
13022 @noindent
13023 The following attributes are defined for packages @code{Builder},
13024 @code{Compiler}, @code{Binder},
13025 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13026 (@pxref{^Switches^Switches^ and Project Files}).
13027
13028 @multitable @columnfractions .4 .2 .2 .2
13029 @item Attribute Name @tab Category @tab Index @tab Value
13030 @item @code{^Default_Switches^Default_Switches^}
13031 @tab associative array
13032 @tab language name
13033 @tab string list
13034 @item @code{^Switches^Switches^}
13035 @tab associative array
13036 @tab file name
13037 @tab string list
13038 @end multitable
13039
13040 @noindent
13041 In addition, package @code{Compiler} has a single string attribute
13042 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13043 string attribute @code{Global_Configuration_Pragmas}.
13044
13045 @noindent
13046 Each simple attribute has a default value: the empty string (for string-valued
13047 attributes) and the empty list (for string list-valued attributes).
13048
13049 An attribute declaration defines a new value for an attribute.
13050
13051 Examples of simple attribute declarations:
13052
13053 @smallexample @c projectfile
13054    for Object_Dir use "objects";
13055    for Source_Dirs use ("units", "test/drivers");
13056 @end smallexample
13057
13058 @noindent
13059 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13060 attribute definition clause in Ada.
13061
13062 Attributes references may be appear in expressions.
13063 The general form for such a reference is @code{<entity>'<attribute>}:
13064 Associative array attributes are functions. Associative
13065 array attribute references must have an argument that is a string literal.
13066
13067 Examples are:
13068
13069 @smallexample @c projectfile
13070   project'Object_Dir
13071   Naming'Dot_Replacement
13072   Imported_Project'Source_Dirs
13073   Imported_Project.Naming'Casing
13074   Builder'^Default_Switches^Default_Switches^("Ada")
13075 @end smallexample
13076
13077 @noindent
13078 The prefix of an attribute may be:
13079 @itemize @bullet
13080 @item @code{project} for an attribute of the current project
13081 @item The name of an existing package of the current project
13082 @item The name of an imported project
13083 @item The name of a parent project that is extended by the current project
13084 @item An expanded name whose prefix is imported/parent project name,
13085 and whose selector is a package name
13086 @end itemize
13087
13088 @noindent
13089 Example:
13090 @smallexample @c projectfile
13091 @group
13092    project Prj is
13093      for Source_Dirs use project'Source_Dirs & "units";
13094      for Source_Dirs use project'Source_Dirs & "test/drivers"
13095    end Prj;
13096 @end group
13097 @end smallexample
13098
13099 @noindent
13100 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13101 has the default value: an empty string list. After this declaration,
13102 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13103 After the second attribute declaration @code{Source_Dirs} is a string list of
13104 two elements: @code{"units"} and @code{"test/drivers"}.
13105
13106 Note: this example is for illustration only. In practice,
13107 the project file would contain only one attribute declaration:
13108
13109 @smallexample @c projectfile
13110    for Source_Dirs use ("units", "test/drivers");
13111 @end smallexample
13112
13113 @node Associative Array Attributes
13114 @subsection Associative Array Attributes
13115
13116 @noindent
13117 Some attributes are defined as @emph{associative arrays}. An associative
13118 array may be regarded as a function that takes a string as a parameter
13119 and delivers a string or string list value as its result.
13120
13121 Here are some examples of single associative array attribute associations:
13122
13123 @smallexample @c projectfile
13124    for Body ("main") use "Main.ada";
13125    for ^Switches^Switches^ ("main.ada")
13126        use ("^-v^-v^",
13127             "^-gnatv^-gnatv^");
13128    for ^Switches^Switches^ ("main.ada")
13129             use Builder'^Switches^Switches^ ("main.ada")
13130               & "^-g^-g^";
13131 @end smallexample
13132
13133 @noindent
13134 Like untyped variables and simple attributes, associative array attributes
13135 may be declared several times. Each declaration supplies a new value for the
13136 attribute, and replaces the previous setting.
13137
13138 @noindent
13139 An associative array attribute may be declared as a full associative array
13140 declaration, with the value of the same attribute in an imported or extended
13141 project.
13142
13143 @smallexample @c projectfile
13144    package Builder is
13145       for Default_Switches use Default.Builder'Default_Switches;
13146    end Builder;
13147 @end smallexample
13148
13149 @noindent
13150 In this example, @code{Default} must be either a project imported by the
13151 current project, or the project that the current project extends. If the
13152 attribute is in a package (in this case, in package @code{Builder}), the same
13153 package needs to be specified.
13154
13155 @noindent
13156 A full associative array declaration replaces any other declaration for the
13157 attribute, including other full associative array declaration. Single
13158 associative array associations may be declare after a full associative
13159 declaration, modifying the value for a single association of the attribute.
13160
13161 @node case Constructions
13162 @subsection @code{case} Constructions
13163
13164 @noindent
13165 A @code{case} construction is used in a project file to effect conditional
13166 behavior.
13167 Here is a typical example:
13168
13169 @smallexample @c projectfile
13170 @group
13171 project MyProj is
13172    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13173
13174    OS : OS_Type := external ("OS", "GNU/Linux");
13175 @end group
13176
13177 @group
13178    package Compiler is
13179      case OS is
13180        when "GNU/Linux" | "Unix" =>
13181          for ^Default_Switches^Default_Switches^ ("Ada")
13182              use ("^-gnath^-gnath^");
13183        when "NT" =>
13184          for ^Default_Switches^Default_Switches^ ("Ada")
13185              use ("^-gnatP^-gnatP^");
13186        when others =>
13187      end case;
13188    end Compiler;
13189 end MyProj;
13190 @end group
13191 @end smallexample
13192
13193 @noindent
13194 The syntax of a @code{case} construction is based on the Ada case statement
13195 (although there is no @code{null} construction for empty alternatives).
13196
13197 The case expression must be a typed string variable.
13198 Each alternative comprises the reserved word @code{when}, either a list of
13199 literal strings separated by the @code{"|"} character or the reserved word
13200 @code{others},  and the @code{"=>"} token.
13201 Each literal string must belong to the string type that is the type of the
13202 case variable.
13203 An @code{others} alternative, if present, must occur last.
13204
13205 After each @code{=>}, there are zero or more constructions.  The only
13206 constructions allowed in a case construction are other case constructions,
13207 attribute declarations and variable declarations. String type declarations and
13208 package declarations are not allowed. Variable declarations are restricted to
13209 variables that have already been declared before the case construction.
13210
13211 The value of the case variable is often given by an external reference
13212 (@pxref{External References in Project Files}).
13213
13214 @c ****************************************
13215 @c * Objects and Sources in Project Files *
13216 @c ****************************************
13217
13218 @node Objects and Sources in Project Files
13219 @section Objects and Sources in Project Files
13220
13221 @menu
13222 * Object Directory::
13223 * Exec Directory::
13224 * Source Directories::
13225 * Source File Names::
13226 @end menu
13227
13228 @noindent
13229 Each project has exactly one object directory and one or more source
13230 directories. The source directories must contain at least one source file,
13231 unless  the project file explicitly specifies that no source files are present
13232 (@pxref{Source File Names}).
13233
13234 @node Object Directory
13235 @subsection Object Directory
13236
13237 @noindent
13238 The object directory for a project is the directory containing the compiler's
13239 output (such as @file{ALI} files and object files) for the project's immediate
13240 sources.
13241
13242 The object directory is given by the value of the attribute @code{Object_Dir}
13243 in the project file.
13244
13245 @smallexample @c projectfile
13246    for Object_Dir use "objects";
13247 @end smallexample
13248
13249 @noindent
13250 The attribute @code{Object_Dir} has a string value, the path name of the object
13251 directory. The path name may be absolute or relative to the directory of the
13252 project file. This directory must already exist, and be readable and writable.
13253
13254 By default, when the attribute @code{Object_Dir} is not given an explicit value
13255 or when its value is the empty string, the object directory is the same as the
13256 directory containing the project file.
13257
13258 @node Exec Directory
13259 @subsection Exec Directory
13260
13261 @noindent
13262 The exec directory for a project is the directory containing the executables
13263 for the project's main subprograms.
13264
13265 The exec directory is given by the value of the attribute @code{Exec_Dir}
13266 in the project file.
13267
13268 @smallexample @c projectfile
13269    for Exec_Dir use "executables";
13270 @end smallexample
13271
13272 @noindent
13273 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13274 directory. The path name may be absolute or relative to the directory of the
13275 project file. This directory must already exist, and be writable.
13276
13277 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13278 or when its value is the empty string, the exec directory is the same as the
13279 object directory of the project file.
13280
13281 @node Source Directories
13282 @subsection Source Directories
13283
13284 @noindent
13285 The source directories of a project are specified by the project file
13286 attribute @code{Source_Dirs}.
13287
13288 This attribute's value is a string list. If the attribute is not given an
13289 explicit value, then there is only one source directory, the one where the
13290 project file resides.
13291
13292 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13293 as in
13294
13295 @smallexample @c projectfile
13296     for Source_Dirs use ();
13297 @end smallexample
13298
13299 @noindent
13300 indicates that the project contains no source files.
13301
13302 Otherwise, each string in the string list designates one or more
13303 source directories.
13304
13305 @smallexample @c projectfile
13306    for Source_Dirs use ("sources", "test/drivers");
13307 @end smallexample
13308
13309 @noindent
13310 If a string in the list ends with @code{"/**"},  then the directory whose path
13311 name precedes the two asterisks, as well as all its subdirectories
13312 (recursively), are source directories.
13313
13314 @smallexample @c projectfile
13315    for Source_Dirs use ("/system/sources/**");
13316 @end smallexample
13317
13318 @noindent
13319 Here the directory @code{/system/sources} and all of its subdirectories
13320 (recursively) are source directories.
13321
13322 To specify that the source directories are the directory of the project file
13323 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13324 @smallexample @c projectfile
13325    for Source_Dirs use ("./**");
13326 @end smallexample
13327
13328 @noindent
13329 Each of the source directories must exist and be readable.
13330
13331 @node Source File Names
13332 @subsection Source File Names
13333
13334 @noindent
13335 In a project that contains source files, their names may be specified by the
13336 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13337 (a string). Source file names never include any directory information.
13338
13339 If the attribute @code{Source_Files} is given an explicit value, then each
13340 element of the list is a source file name.
13341
13342 @smallexample @c projectfile
13343    for Source_Files use ("main.adb");
13344    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13345 @end smallexample
13346
13347 @noindent
13348 If the attribute @code{Source_Files} is not given an explicit value,
13349 but the attribute @code{Source_List_File} is given a string value,
13350 then the source file names are contained in the text file whose path name
13351 (absolute or relative to the directory of the project file) is the
13352 value of the attribute @code{Source_List_File}.
13353
13354 Each line in the file that is not empty or is not a comment
13355 contains a source file name.
13356
13357 @smallexample @c projectfile
13358    for Source_List_File use "source_list.txt";
13359 @end smallexample
13360
13361 @noindent
13362 By default, if neither the attribute @code{Source_Files} nor the attribute
13363 @code{Source_List_File} is given an explicit value, then each file in the
13364 source directories that conforms to the project's naming scheme
13365 (@pxref{Naming Schemes}) is an immediate source of the project.
13366
13367 A warning is issued if both attributes @code{Source_Files} and
13368 @code{Source_List_File} are given explicit values. In this case, the attribute
13369 @code{Source_Files} prevails.
13370
13371 Each source file name must be the name of one existing source file
13372 in one of the source directories.
13373
13374 A @code{Source_Files} attribute whose value is an empty list
13375 indicates that there are no source files in the project.
13376
13377 If the order of the source directories is known statically, that is if
13378 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13379 be several files with the same source file name. In this case, only the file
13380 in the first directory is considered as an immediate source of the project
13381 file. If the order of the source directories is not known statically, it is
13382 an error to have several files with the same source file name.
13383
13384 Projects can be specified to have no Ada source
13385 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13386 list, or the @code{"Ada"} may be absent from @code{Languages}:
13387
13388 @smallexample @c projectfile
13389    for Source_Dirs use ();
13390    for Source_Files use ();
13391    for Languages use ("C", "C++");
13392 @end smallexample
13393
13394 @noindent
13395 Otherwise, a project must contain at least one immediate source.
13396
13397 Projects with no source files are useful as template packages
13398 (@pxref{Packages in Project Files}) for other projects; in particular to
13399 define a package @code{Naming} (@pxref{Naming Schemes}).
13400
13401 @c ****************************
13402 @c * Importing Projects *
13403 @c ****************************
13404
13405 @node  Importing Projects
13406 @section Importing Projects
13407 @cindex @code{ADA_PROJECT_PATH}
13408 @cindex @code{GPR_PROJECT_PATH}
13409
13410 @noindent
13411 An immediate source of a project P may depend on source files that
13412 are neither immediate sources of P nor in the predefined library.
13413 To get this effect, P must @emph{import} the projects that contain the needed
13414 source files.
13415
13416 @smallexample @c projectfile
13417 @group
13418   with "project1", "utilities.gpr";
13419   with "/namings/apex.gpr";
13420   project Main is
13421     @dots{}
13422 @end group
13423 @end smallexample
13424
13425 @noindent
13426 As can be seen in this example, the syntax for importing projects is similar
13427 to the syntax for importing compilation units in Ada. However, project files
13428 use literal strings instead of names, and the @code{with} clause identifies
13429 project files rather than packages.
13430
13431 Each literal string is the file name or path name (absolute or relative) of a
13432 project file. If a string corresponds to a file name, with no path or a
13433 relative path, then its location is determined by the @emph{project path}. The
13434 latter can be queried using @code{gnatls -v}. It contains:
13435
13436 @itemize @bullet
13437 @item
13438 In first position, the directory containing the current project file.
13439 @item
13440 In last position, the default project directory. This default project directory
13441 is part of the GNAT installation and is the standard place to install project
13442 files giving access to standard support libraries.
13443 @ifclear vms
13444 @ref{Installing a library}
13445 @end ifclear
13446
13447 @item
13448 In between, all the directories referenced in the
13449 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13450 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13451 @end itemize
13452
13453 @noindent
13454 If a relative pathname is used, as in
13455
13456 @smallexample @c projectfile
13457   with "tests/proj";
13458 @end smallexample
13459
13460 @noindent
13461 then the full path for the project is constructed by concatenating this
13462 relative path to those in the project path, in order, until a matching file is
13463 found. Any symbolic link will be fully resolved in the directory of the
13464 importing project file before the imported project file is examined.
13465
13466 If the @code{with}'ed project file name does not have an extension,
13467 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13468 then the file name as specified in the @code{with} clause (no extension) will
13469 be used. In the above example, if a file @code{project1.gpr} is found, then it
13470 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13471 then it will be used; if neither file exists, this is an error.
13472
13473 A warning is issued if the name of the project file does not match the
13474 name of the project; this check is case insensitive.
13475
13476 Any source file that is an immediate source of the imported project can be
13477 used by the immediate sources of the importing project, transitively. Thus
13478 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13479 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13480 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13481 because if and when @code{B} ceases to import @code{C}, some sources in
13482 @code{A} will no longer compile.
13483
13484 A side effect of this capability is that normally cyclic dependencies are not
13485 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13486 is not allowed to import @code{A}. However, there are cases when cyclic
13487 dependencies would be beneficial. For these cases, another form of import
13488 between projects exists, the @code{limited with}: a project @code{A} that
13489 imports a project @code{B} with a straight @code{with} may also be imported,
13490 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13491 to @code{A} include at least one @code{limited with}.
13492
13493 @smallexample @c 0projectfile
13494 with "../b/b.gpr";
13495 with "../c/c.gpr";
13496 project A is
13497 end A;
13498
13499 limited with "../a/a.gpr";
13500 project B is
13501 end B;
13502
13503 with "../d/d.gpr";
13504 project C is
13505 end C;
13506
13507 limited with "../a/a.gpr";
13508 project D is
13509 end D;
13510 @end smallexample
13511
13512 @noindent
13513 In the above legal example, there are two project cycles:
13514 @itemize @bullet
13515 @item A-> B-> A
13516 @item A -> C -> D -> A
13517 @end itemize
13518
13519 @noindent
13520 In each of these cycle there is one @code{limited with}: import of @code{A}
13521 from @code{B} and import of @code{A} from @code{D}.
13522
13523 The difference between straight @code{with} and @code{limited with} is that
13524 the name of a project imported with a @code{limited with} cannot be used in the
13525 project that imports it. In particular, its packages cannot be renamed and
13526 its variables cannot be referred to.
13527
13528 An exception to the above rules for @code{limited with} is that for the main
13529 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13530 @code{limited with} is equivalent to a straight @code{with}. For example,
13531 in the example above, projects @code{B} and @code{D} could not be main
13532 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13533 each have a @code{limited with} that is the only one in a cycle of importing
13534 projects.
13535
13536 @c *********************
13537 @c * Project Extension *
13538 @c *********************
13539
13540 @node Project Extension
13541 @section Project Extension
13542
13543 @noindent
13544 During development of a large system, it is sometimes necessary to use
13545 modified versions of some of the source files, without changing the original
13546 sources. This can be achieved through the @emph{project extension} facility.
13547
13548 @smallexample @c projectfile
13549    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13550 @end smallexample
13551
13552 @noindent
13553 A project extension declaration introduces an extending project
13554 (the @emph{child}) and a project being extended (the @emph{parent}).
13555
13556 By default, a child project inherits all the sources of its parent.
13557 However, inherited sources can be overridden: a unit in a parent is hidden
13558 by a unit of the same name in the child.
13559
13560 Inherited sources are considered to be sources (but not immediate sources)
13561 of the child project; see @ref{Project File Syntax}.
13562
13563 An inherited source file retains any switches specified in the parent project.
13564
13565 For example if the project @code{Utilities} contains the spec and the
13566 body of an Ada package @code{Util_IO}, then the project
13567 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13568 The original body of @code{Util_IO} will not be considered in program builds.
13569 However, the package spec will still be found in the project
13570 @code{Utilities}.
13571
13572 A child project can have only one parent, except when it is qualified as
13573 abstract. But it may import any number of other projects.
13574
13575 A project is not allowed to import directly or indirectly at the same time a
13576 child project and any of its ancestors.
13577
13578 @c *******************************
13579 @c * Project Hierarchy Extension *
13580 @c *******************************
13581
13582 @node Project Hierarchy Extension
13583 @section Project Hierarchy Extension
13584
13585 @noindent
13586 When extending a large system spanning multiple projects, it is often
13587 inconvenient to extend every project in the hierarchy that is impacted by a
13588 small change introduced. In such cases, it is possible to create a virtual
13589 extension of entire hierarchy using @code{extends all} relationship.
13590
13591 When the project is extended using @code{extends all} inheritance, all projects
13592 that are imported by it, both directly and indirectly, are considered virtually
13593 extended. That is, the Project Manager creates "virtual projects"
13594 that extend every project in the hierarchy; all these virtual projects have
13595 no sources of their own and have as object directory the object directory of
13596 the root of "extending all" project.
13597
13598 It is possible to explicitly extend one or more projects in the hierarchy
13599 in order to modify the sources. These extending projects must be imported by
13600 the "extending all" project, which will replace the corresponding virtual
13601 projects with the explicit ones.
13602
13603 When building such a project hierarchy extension, the Project Manager will
13604 ensure that both modified sources and sources in virtual extending projects
13605 that depend on them, are recompiled.
13606
13607 By means of example, consider the following hierarchy of projects.
13608
13609 @enumerate
13610 @item
13611 project A, containing package P1
13612 @item
13613 project B importing A and containing package P2 which depends on P1
13614 @item
13615 project C importing B and containing package P3 which depends on P2
13616 @end enumerate
13617
13618 @noindent
13619 We want to modify packages P1 and P3.
13620
13621 This project hierarchy will need to be extended as follows:
13622
13623 @enumerate
13624 @item
13625 Create project A1 that extends A, placing modified P1 there:
13626
13627 @smallexample @c 0projectfile
13628 project A1 extends "(@dots{})/A" is
13629 end A1;
13630 @end smallexample
13631
13632 @item
13633 Create project C1 that "extends all" C and imports A1, placing modified
13634 P3 there:
13635
13636 @smallexample @c 0projectfile
13637 with "(@dots{})/A1";
13638 project C1 extends all "(@dots{})/C" is
13639 end C1;
13640 @end smallexample
13641 @end enumerate
13642
13643 When you build project C1, your entire modified project space will be
13644 recompiled, including the virtual project B1 that has been impacted by the
13645 "extending all" inheritance of project C.
13646
13647 Note that if a Library Project in the hierarchy is virtually extended,
13648 the virtual project that extends the Library Project is not a Library Project.
13649
13650 @c ****************************************
13651 @c * External References in Project Files *
13652 @c ****************************************
13653
13654 @node  External References in Project Files
13655 @section External References in Project Files
13656
13657 @noindent
13658 A project file may contain references to external variables; such references
13659 are called @emph{external references}.
13660
13661 An external variable is either defined as part of the environment (an
13662 environment variable in Unix, for example) or else specified on the command
13663 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13664 If both, then the command line value is used.
13665
13666 The value of an external reference is obtained by means of the built-in
13667 function @code{external}, which returns a string value.
13668 This function has two forms:
13669 @itemize @bullet
13670 @item @code{external (external_variable_name)}
13671 @item @code{external (external_variable_name, default_value)}
13672 @end itemize
13673
13674 @noindent
13675 Each parameter must be a string literal.  For example:
13676
13677 @smallexample @c projectfile
13678    external ("USER")
13679    external ("OS", "GNU/Linux")
13680 @end smallexample
13681
13682 @noindent
13683 In the form with one parameter, the function returns the value of
13684 the external variable given as parameter. If this name is not present in the
13685 environment, the function returns an empty string.
13686
13687 In the form with two string parameters, the second argument is
13688 the value returned when the variable given as the first argument is not
13689 present in the environment. In the example above, if @code{"OS"} is not
13690 the name of ^an environment variable^a logical name^ and is not passed on
13691 the command line, then the returned value is @code{"GNU/Linux"}.
13692
13693 An external reference may be part of a string expression or of a string
13694 list expression, and can therefore appear in a variable declaration or
13695 an attribute declaration.
13696
13697 @smallexample @c projectfile
13698 @group
13699    type Mode_Type is ("Debug", "Release");
13700    Mode : Mode_Type := external ("MODE");
13701    case Mode is
13702      when "Debug" =>
13703         @dots{}
13704 @end group
13705 @end smallexample
13706
13707 @c *****************************
13708 @c * Packages in Project Files *
13709 @c *****************************
13710
13711 @node  Packages in Project Files
13712 @section Packages in Project Files
13713
13714 @noindent
13715 A @emph{package} defines the settings for project-aware tools within a
13716 project.
13717 For each such tool one can declare a package; the names for these
13718 packages are preset (@pxref{Packages}).
13719 A package may contain variable declarations, attribute declarations, and case
13720 constructions.
13721
13722 @smallexample @c projectfile
13723 @group
13724    project Proj is
13725       package Builder is  -- used by gnatmake
13726          for ^Default_Switches^Default_Switches^ ("Ada")
13727              use ("^-v^-v^",
13728                   "^-g^-g^");
13729       end Builder;
13730    end Proj;
13731 @end group
13732 @end smallexample
13733
13734 @noindent
13735 The syntax of package declarations mimics that of package in Ada.
13736
13737 Most of the packages have an attribute
13738 @code{^Default_Switches^Default_Switches^}.
13739 This attribute is an associative array, and its value is a string list.
13740 The index of the associative array is the name of a programming language (case
13741 insensitive). This attribute indicates the ^switch^switch^
13742 or ^switches^switches^ to be used
13743 with the corresponding tool.
13744
13745 Some packages also have another attribute, @code{^Switches^Switches^},
13746 an associative array whose value is a string list.
13747 The index is the name of a source file.
13748 This attribute indicates the ^switch^switch^
13749 or ^switches^switches^ to be used by the corresponding
13750 tool when dealing with this specific file.
13751
13752 Further information on these ^switch^switch^-related attributes is found in
13753 @ref{^Switches^Switches^ and Project Files}.
13754
13755 A package may be declared as a @emph{renaming} of another package; e.g., from
13756 the project file for an imported project.
13757
13758 @smallexample @c projectfile
13759 @group
13760   with "/global/apex.gpr";
13761   project Example is
13762     package Naming renames Apex.Naming;
13763     @dots{}
13764   end Example;
13765 @end group
13766 @end smallexample
13767
13768 @noindent
13769 Packages that are renamed in other project files often come from project files
13770 that have no sources: they are just used as templates. Any modification in the
13771 template will be reflected automatically in all the project files that rename
13772 a package from the template.
13773
13774 In addition to the tool-oriented packages, you can also declare a package
13775 named @code{Naming} to establish specialized source file naming conventions
13776 (@pxref{Naming Schemes}).
13777
13778 @c ************************************
13779 @c * Variables from Imported Projects *
13780 @c ************************************
13781
13782 @node Variables from Imported Projects
13783 @section Variables from Imported Projects
13784
13785 @noindent
13786 An attribute or variable defined in an imported or parent project can
13787 be used in expressions in the importing / extending project.
13788 Such an attribute or variable is denoted by an expanded name whose prefix
13789 is either the name of the project or the expanded name of a package within
13790 a project.
13791
13792 @smallexample @c projectfile
13793 @group
13794   with "imported";
13795   project Main extends "base" is
13796      Var1 := Imported.Var;
13797      Var2 := Base.Var & ".new";
13798 @end group
13799
13800 @group
13801      package Builder is
13802         for ^Default_Switches^Default_Switches^ ("Ada")
13803             use Imported.Builder'Ada_^Switches^Switches^ &
13804                 "^-gnatg^-gnatg^" &
13805                 "^-v^-v^";
13806      end Builder;
13807 @end group
13808
13809 @group
13810      package Compiler is
13811         for ^Default_Switches^Default_Switches^ ("Ada")
13812             use Base.Compiler'Ada_^Switches^Switches^;
13813      end Compiler;
13814   end Main;
13815 @end group
13816 @end smallexample
13817
13818 @noindent
13819 In this example:
13820
13821 @itemize @bullet
13822 @item
13823 The value of @code{Var1} is a copy of the variable @code{Var} defined
13824 in the project file @file{"imported.gpr"}
13825 @item
13826 the value of @code{Var2} is a copy of the value of variable @code{Var}
13827 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13828 @item
13829 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13830 @code{Builder} is a string list that includes in its value a copy of the value
13831 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13832 in project file @file{imported.gpr} plus two new elements:
13833 @option{"^-gnatg^-gnatg^"}
13834 and @option{"^-v^-v^"};
13835 @item
13836 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13837 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13838 defined in the @code{Compiler} package in project file @file{base.gpr},
13839 the project being extended.
13840 @end itemize
13841
13842 @c ******************
13843 @c * Naming Schemes *
13844 @c ******************
13845
13846 @node  Naming Schemes
13847 @section Naming Schemes
13848
13849 @noindent
13850 Sometimes an Ada software system is ported from a foreign compilation
13851 environment to GNAT, and the file names do not use the default GNAT
13852 conventions. Instead of changing all the file names (which for a variety
13853 of reasons might not be possible), you can define the relevant file
13854 naming scheme in the @code{Naming} package in your project file.
13855
13856 @noindent
13857 Note that the use of pragmas described in
13858 @ref{Alternative File Naming Schemes} by mean of a configuration
13859 pragmas file is not supported when using project files. You must use
13860 the features described in this paragraph. You can however use specify
13861 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13862
13863 @ifclear vms
13864 For example, the following
13865 package models the Apex file naming rules:
13866
13867 @smallexample @c projectfile
13868 @group
13869   package Naming is
13870     for Casing               use "lowercase";
13871     for Dot_Replacement      use ".";
13872     for Spec_Suffix ("Ada")  use ".1.ada";
13873     for Body_Suffix ("Ada")  use ".2.ada";
13874   end Naming;
13875 @end group
13876 @end smallexample
13877 @end ifclear
13878
13879 @ifset vms
13880 For example, the following package models the HP Ada file naming rules:
13881
13882 @smallexample @c projectfile
13883 @group
13884   package Naming is
13885     for Casing               use "lowercase";
13886     for Dot_Replacement      use "__";
13887     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13888     for Body_Suffix ("Ada")  use ".^ada^ada^";
13889   end Naming;
13890 @end group
13891 @end smallexample
13892
13893 @noindent
13894 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13895 names in lower case)
13896 @end ifset
13897
13898 @noindent
13899 You can define the following attributes in package @code{Naming}:
13900
13901 @table @code
13902
13903 @item @code{Casing}
13904 This must be a string with one of the three values @code{"lowercase"},
13905 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13906
13907 @noindent
13908 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13909
13910 @item @code{Dot_Replacement}
13911 This must be a string whose value satisfies the following conditions:
13912
13913 @itemize @bullet
13914 @item It must not be empty
13915 @item It cannot start or end with an alphanumeric character
13916 @item It cannot be a single underscore
13917 @item It cannot start with an underscore followed by an alphanumeric
13918 @item It cannot contain a dot @code{'.'} except if the entire string
13919 is @code{"."}
13920 @end itemize
13921
13922 @noindent
13923 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13924
13925 @item @code{Spec_Suffix}
13926 This is an associative array (indexed by the programming language name, case
13927 insensitive) whose value is a string that must satisfy the following
13928 conditions:
13929
13930 @itemize @bullet
13931 @item It must not be empty
13932 @item It must include at least one dot
13933 @end itemize
13934 @noindent
13935 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13936 @code{"^.ads^.ADS^"}.
13937
13938 @item @code{Body_Suffix}
13939 This is an associative array (indexed by the programming language name, case
13940 insensitive) whose value is a string that must satisfy the following
13941 conditions:
13942
13943 @itemize @bullet
13944 @item It must not be empty
13945 @item It must include at least one dot
13946 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13947 @end itemize
13948 @noindent
13949 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13950 same string, then a file name that ends with the longest of these two suffixes
13951 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13952 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13953
13954 If the suffix does not start with a '.', a file with a name exactly equal
13955 to the suffix will also be part of the project (for instance if you define
13956 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13957 of the project. This is not interesting in general when using projects to
13958 compile. However, it might become useful when a project is also used to
13959 find the list of source files in an editor, like the GNAT Programming System
13960 (GPS).
13961
13962 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13963 @code{"^.adb^.ADB^"}.
13964
13965 @item @code{Separate_Suffix}
13966 This must be a string whose value satisfies the same conditions as
13967 @code{Body_Suffix}. The same "longest suffix" rules apply.
13968
13969 @noindent
13970 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13971 value as @code{Body_Suffix ("Ada")}.
13972
13973 @item @code{Spec}
13974 @noindent
13975 You can use the associative array attribute @code{Spec}  to define
13976 the source file name for an individual Ada compilation unit's spec. The array
13977 index must be a string literal that identifies the Ada unit (case insensitive).
13978 The value of this attribute must be a string that identifies the file that
13979 contains this unit's spec (case sensitive or insensitive depending on the
13980 operating system).
13981
13982 @smallexample @c projectfile
13983    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13984 @end smallexample
13985
13986 When the source file contains several units, you can indicate at what
13987 position the unit occurs in the file, with the following. The first unit
13988 in the file has index 1
13989
13990 @smallexample @c projectfile
13991   for Body ("top") use "foo.a" at 1;
13992   for Body ("foo") use "foo.a" at 2;
13993 @end smallexample
13994
13995 @item @code{Body}
13996
13997 You can use the associative array attribute @code{Body} to
13998 define the source file name for an individual Ada compilation unit's body
13999 (possibly a subunit).  The array index must be a string literal that identifies
14000 the Ada unit (case insensitive).  The value of this attribute must be a string
14001 that identifies the file that contains this unit's body or subunit (case
14002 sensitive or insensitive depending on the operating system).
14003
14004 @smallexample @c projectfile
14005    for Body ("MyPack.MyChild") use "mypack.mychild.body";
14006 @end smallexample
14007 @end table
14008
14009 @c ********************
14010 @c * Library Projects *
14011 @c ********************
14012
14013 @node Library Projects
14014 @section Library Projects
14015
14016 @noindent
14017 @emph{Library projects} are projects whose object code is placed in a library.
14018 (Note that this facility is not yet supported on all platforms).
14019
14020 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14021 single archive, which might either be a shared or a static library. This
14022 library can later on be linked with multiple executables, potentially
14023 reducing their sizes.
14024
14025 If your project file specifies languages other than Ada, but you are still
14026 using @code{gnatmake} to compile and link, the latter will not try to
14027 compile your sources other than Ada (you should use @code{gprbuild} if that
14028 is your intent). However, @code{gnatmake} will automatically link all object
14029 files found in the object directory, whether or not they were compiled from
14030 an Ada source file. This specific behavior only applies when multiple
14031 languages are specified.
14032
14033 To create a library project, you need to define in its project file
14034 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14035 Additionally, you may define other library-related attributes such as
14036 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14037 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14038
14039 The @code{Library_Name} attribute has a string value. There is no restriction
14040 on the name of a library. It is the responsibility of the developer to
14041 choose a name that will be accepted by the platform. It is recommended to
14042 choose names that could be Ada identifiers; such names are almost guaranteed
14043 to be acceptable on all platforms.
14044
14045 The @code{Library_Dir} attribute has a string value that designates the path
14046 (absolute or relative) of the directory where the library will reside.
14047 It must designate an existing directory, and this directory must be writable,
14048 different from the project's object directory and from any source directory
14049 in the project tree.
14050
14051 If both @code{Library_Name} and @code{Library_Dir} are specified and
14052 are legal, then the project file defines a library project.  The optional
14053 library-related attributes are checked only for such project files.
14054
14055 The @code{Library_Kind} attribute has a string value that must be one of the
14056 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14057 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14058 attribute is not specified, the library is a static library, that is
14059 an archive of object files that can be potentially linked into a
14060 static executable. Otherwise, the library may be dynamic or
14061 relocatable, that is a library that is loaded only at the start of execution.
14062
14063 If you need to build both a static and a dynamic library, you should use two
14064 different object directories, since in some cases some extra code needs to
14065 be generated for the latter. For such cases, it is recommended to either use
14066 two different project files, or a single one which uses external variables
14067 to indicate what kind of library should be build.
14068
14069 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14070 directory where the ALI files of the library will be copied. When it is
14071 not specified, the ALI files are copied to the directory specified in
14072 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14073 must be writable and different from the project's object directory and from
14074 any source directory in the project tree.
14075
14076 The @code{Library_Version} attribute has a string value whose interpretation
14077 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14078 used only for dynamic/relocatable libraries as the internal name of the
14079 library (the @code{"soname"}). If the library file name (built from the
14080 @code{Library_Name}) is different from the @code{Library_Version}, then the
14081 library file will be a symbolic link to the actual file whose name will be
14082 @code{Library_Version}.
14083
14084 Example (on Unix):
14085
14086 @smallexample @c projectfile
14087 @group
14088 project Plib is
14089
14090    Version := "1";
14091
14092    for Library_Dir use "lib_dir";
14093    for Library_Name use "dummy";
14094    for Library_Kind use "relocatable";
14095    for Library_Version use "libdummy.so." & Version;
14096
14097 end Plib;
14098 @end group
14099 @end smallexample
14100
14101 @noindent
14102 Directory @file{lib_dir} will contain the internal library file whose name
14103 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14104 @file{libdummy.so.1}.
14105
14106 When @command{gnatmake} detects that a project file
14107 is a library project file, it will check all immediate sources of the project
14108 and rebuild the library if any of the sources have been recompiled.
14109
14110 Standard project files can import library project files. In such cases,
14111 the libraries will only be rebuilt if some of its sources are recompiled
14112 because they are in the closure of some other source in an importing project.
14113 Sources of the library project files that are not in such a closure will
14114 not be checked, unless the full library is checked, because one of its sources
14115 needs to be recompiled.
14116
14117 For instance, assume the project file @code{A} imports the library project file
14118 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14119 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14120 @file{l2.ads}, @file{l2.adb}.
14121
14122 If @file{l1.adb} has been modified, then the library associated with @code{L}
14123 will be rebuilt when compiling all the immediate sources of @code{A} only
14124 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14125 @code{"with L1;"}.
14126
14127 To be sure that all the sources in the library associated with @code{L} are
14128 up to date, and that all the sources of project @code{A} are also up to date,
14129 the following two commands needs to be used:
14130
14131 @smallexample
14132 gnatmake -Pl.gpr
14133 gnatmake -Pa.gpr
14134 @end smallexample
14135
14136 When a library is built or rebuilt, an attempt is made first to delete all
14137 files in the library directory.
14138 All @file{ALI} files will also be copied from the object directory to the
14139 library directory. To build executables, @command{gnatmake} will use the
14140 library rather than the individual object files.
14141
14142 @ifclear vms
14143 It is also possible to create library project files for third-party libraries
14144 that are precompiled and cannot be compiled locally thanks to the
14145 @code{externally_built} attribute. (See @ref{Installing a library}).
14146 @end ifclear
14147
14148 @c *******************************
14149 @c * Stand-alone Library Projects *
14150 @c *******************************
14151
14152 @node Stand-alone Library Projects
14153 @section Stand-alone Library Projects
14154
14155 @noindent
14156 A Stand-alone Library is a library that contains the necessary code to
14157 elaborate the Ada units that are included in the library. A Stand-alone
14158 Library is suitable to be used in an executable when the main is not
14159 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14160 subprogram.
14161
14162 A Stand-alone Library Project is a Library Project where the library is
14163 a Stand-alone Library.
14164
14165 To be a Stand-alone Library Project, in addition to the two attributes
14166 that make a project a Library Project (@code{Library_Name} and
14167 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14168 @code{Library_Interface} must be defined.
14169
14170 @smallexample @c projectfile
14171 @group
14172    for Library_Dir use "lib_dir";
14173    for Library_Name use "dummy";
14174    for Library_Interface use ("int1", "int1.child");
14175 @end group
14176 @end smallexample
14177
14178 Attribute @code{Library_Interface} has a nonempty string list value,
14179 each string in the list designating a unit contained in an immediate source
14180 of the project file.
14181
14182 When a Stand-alone Library is built, first the binder is invoked to build
14183 a package whose name depends on the library name
14184 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14185 This binder-generated package includes initialization and
14186 finalization procedures whose
14187 names depend on the library name (dummyinit and dummyfinal in the example
14188 above). The object corresponding to this package is included in the library.
14189
14190 A dynamic or relocatable Stand-alone Library is automatically initialized
14191 if automatic initialization of Stand-alone Libraries is supported on the
14192 platform and if attribute @code{Library_Auto_Init} is not specified or
14193 is specified with the value "true". A static Stand-alone Library is never
14194 automatically initialized.
14195
14196 Single string attribute @code{Library_Auto_Init} may be specified with only
14197 two possible values: "false" or "true" (case-insensitive). Specifying
14198 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14199 initialization of dynamic or relocatable libraries.
14200
14201 When a non-automatically initialized Stand-alone Library is used
14202 in an executable, its initialization procedure must be called before
14203 any service of the library is used.
14204 When the main subprogram is in Ada, it may mean that the initialization
14205 procedure has to be called during elaboration of another package.
14206
14207 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14208 (those that are listed in attribute @code{Library_Interface}) are copied to
14209 the Library Directory. As a consequence, only the Interface Units may be
14210 imported from Ada units outside of the library. If other units are imported,
14211 the binding phase will fail.
14212
14213 When a Stand-Alone Library is bound, the switches that are specified in
14214 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14215 used in the call to @command{gnatbind}.
14216
14217 The string list attribute @code{Library_Options} may be used to specified
14218 additional switches to the call to @command{gcc} to link the library.
14219
14220 The attribute @code{Library_Src_Dir}, may be specified for a
14221 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14222 single string value. Its value must be the path (absolute or relative to the
14223 project directory) of an existing directory. This directory cannot be the
14224 object directory or one of the source directories, but it can be the same as
14225 the library directory. The sources of the Interface
14226 Units of the library, necessary to an Ada client of the library, will be
14227 copied to the designated directory, called Interface Copy directory.
14228 These sources includes the specs of the Interface Units, but they may also
14229 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14230 are used, or when there is a generic units in the spec. Before the sources
14231 are copied to the Interface Copy directory, an attempt is made to delete all
14232 files in the Interface Copy directory.
14233
14234 @c *************************************
14235 @c * Switches Related to Project Files *
14236 @c *************************************
14237 @node Switches Related to Project Files
14238 @section Switches Related to Project Files
14239
14240 @noindent
14241 The following switches are used by GNAT tools that support project files:
14242
14243 @table @option
14244
14245 @item ^-P^/PROJECT_FILE=^@var{project}
14246 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14247 Indicates the name of a project file. This project file will be parsed with
14248 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14249 if any, and using the external references indicated
14250 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14251 @ifclear vms
14252 There may zero, one or more spaces between @option{-P} and @var{project}.
14253 @end ifclear
14254
14255 @noindent
14256 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14257
14258 @noindent
14259 Since the Project Manager parses the project file only after all the switches
14260 on the command line are checked, the order of the switches
14261 @option{^-P^/PROJECT_FILE^},
14262 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14263 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14264
14265 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14266 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14267 Indicates that external variable @var{name} has the value @var{value}.
14268 The Project Manager will use this value for occurrences of
14269 @code{external(name)} when parsing the project file.
14270
14271 @ifclear vms
14272 @noindent
14273 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14274 put between quotes.
14275 @smallexample
14276   -XOS=NT
14277   -X"user=John Doe"
14278 @end smallexample
14279 @end ifclear
14280
14281 @noindent
14282 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14283 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14284 @var{name}, only the last one is used.
14285
14286 @noindent
14287 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14288 takes precedence over the value of the same name in the environment.
14289
14290 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14291 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14292 Indicates the verbosity of the parsing of GNAT project files.
14293
14294 @ifclear vms
14295 @option{-vP0} means Default;
14296 @option{-vP1} means Medium;
14297 @option{-vP2} means High.
14298 @end ifclear
14299
14300 @ifset vms
14301 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14302 HIGH.
14303 @end ifset
14304
14305 @noindent
14306 The default is ^Default^DEFAULT^: no output for syntactically correct
14307 project files.
14308 @noindent
14309 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14310 only the last one is used.
14311
14312 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14313 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14314 Add directory <dir> at the beginning of the project search path, in order,
14315 after the current working directory.
14316
14317 @ifclear vms
14318 @item -eL
14319 @cindex @option{-eL} (any project-aware tool)
14320 Follow all symbolic links when processing project files.
14321 @end ifclear
14322
14323 @item ^--subdirs^/SUBDIRS^=<subdir>
14324 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14325 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14326 directories (except the source directories) are the subdirectories <subdir>
14327 of the directories specified in the project files. This applies in particular
14328 to object directories, library directories and exec directories. If the
14329 subdirectories do not exist, they are created automatically.
14330
14331 @end table
14332
14333 @c **********************************
14334 @c * Tools Supporting Project Files *
14335 @c **********************************
14336
14337 @node  Tools Supporting Project Files
14338 @section Tools Supporting Project Files
14339
14340 @menu
14341 * gnatmake and Project Files::
14342 * The GNAT Driver and Project Files::
14343 @end menu
14344
14345 @node gnatmake and Project Files
14346 @subsection gnatmake and Project Files
14347
14348 @noindent
14349 This section covers several topics related to @command{gnatmake} and
14350 project files: defining ^switches^switches^ for @command{gnatmake}
14351 and for the tools that it invokes; specifying configuration pragmas;
14352 the use of the @code{Main} attribute; building and rebuilding library project
14353 files.
14354
14355 @menu
14356 * ^Switches^Switches^ and Project Files::
14357 * Specifying Configuration Pragmas::
14358 * Project Files and Main Subprograms::
14359 * Library Project Files::
14360 @end menu
14361
14362 @node ^Switches^Switches^ and Project Files
14363 @subsubsection ^Switches^Switches^ and Project Files
14364
14365 @ifset vms
14366 It is not currently possible to specify VMS style qualifiers in the project
14367 files; only Unix style ^switches^switches^ may be specified.
14368 @end ifset
14369
14370 @noindent
14371 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14372 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14373 attribute, a @code{^Switches^Switches^} attribute, or both;
14374 as their names imply, these ^switch^switch^-related
14375 attributes affect the ^switches^switches^ that are used for each of these GNAT
14376 components when
14377 @command{gnatmake} is invoked.  As will be explained below, these
14378 component-specific ^switches^switches^ precede
14379 the ^switches^switches^ provided on the @command{gnatmake} command line.
14380
14381 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14382 array indexed by language name (case insensitive) whose value is a string list.
14383 For example:
14384
14385 @smallexample @c projectfile
14386 @group
14387 package Compiler is
14388   for ^Default_Switches^Default_Switches^ ("Ada")
14389       use ("^-gnaty^-gnaty^",
14390            "^-v^-v^");
14391 end Compiler;
14392 @end group
14393 @end smallexample
14394
14395 @noindent
14396 The @code{^Switches^Switches^} attribute is also an associative array,
14397 indexed by a file name (which may or may not be case sensitive, depending
14398 on the operating system) whose value is a string list.  For example:
14399
14400 @smallexample @c projectfile
14401 @group
14402 package Builder is
14403    for ^Switches^Switches^ ("main1.adb")
14404        use ("^-O2^-O2^");
14405    for ^Switches^Switches^ ("main2.adb")
14406        use ("^-g^-g^");
14407 end Builder;
14408 @end group
14409 @end smallexample
14410
14411 @noindent
14412 For the @code{Builder} package, the file names must designate source files
14413 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14414 file names must designate @file{ALI} or source files for main subprograms.
14415 In each case just the file name without an explicit extension is acceptable.
14416
14417 For each tool used in a program build (@command{gnatmake}, the compiler, the
14418 binder, and the linker), the corresponding package @dfn{contributes} a set of
14419 ^switches^switches^ for each file on which the tool is invoked, based on the
14420 ^switch^switch^-related attributes defined in the package.
14421 In particular, the ^switches^switches^
14422 that each of these packages contributes for a given file @var{f} comprise:
14423
14424 @itemize @bullet
14425 @item
14426 the value of attribute @code{^Switches^Switches^ (@var{f})},
14427 if it is specified in the package for the given file,
14428 @item
14429 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14430 if it is specified in the package.
14431 @end itemize
14432
14433 @noindent
14434 If neither of these attributes is defined in the package, then the package does
14435 not contribute any ^switches^switches^ for the given file.
14436
14437 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14438 two sets, in the following order: those contributed for the file
14439 by the @code{Builder} package;
14440 and the switches passed on the command line.
14441
14442 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14443 the ^switches^switches^ passed to the tool comprise three sets,
14444 in the following order:
14445
14446 @enumerate
14447 @item
14448 the applicable ^switches^switches^ contributed for the file
14449 by the @code{Builder} package in the project file supplied on the command line;
14450
14451 @item
14452 those contributed for the file by the package (in the relevant project file --
14453 see below) corresponding to the tool; and
14454
14455 @item
14456 the applicable switches passed on the command line.
14457 @end enumerate
14458
14459 @noindent
14460 The term @emph{applicable ^switches^switches^} reflects the fact that
14461 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14462 tools, depending on the individual ^switch^switch^.
14463
14464 @command{gnatmake} may invoke the compiler on source files from different
14465 projects. The Project Manager will use the appropriate project file to
14466 determine the @code{Compiler} package for each source file being compiled.
14467 Likewise for the @code{Binder} and @code{Linker} packages.
14468
14469 As an example, consider the following package in a project file:
14470
14471 @smallexample @c projectfile
14472 @group
14473 project Proj1 is
14474    package Compiler is
14475       for ^Default_Switches^Default_Switches^ ("Ada")
14476           use ("^-g^-g^");
14477       for ^Switches^Switches^ ("a.adb")
14478           use ("^-O1^-O1^");
14479       for ^Switches^Switches^ ("b.adb")
14480           use ("^-O2^-O2^",
14481                "^-gnaty^-gnaty^");
14482    end Compiler;
14483 end Proj1;
14484 @end group
14485 @end smallexample
14486
14487 @noindent
14488 If @command{gnatmake} is invoked with this project file, and it needs to
14489 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14490 @file{a.adb} will be compiled with the ^switch^switch^
14491 @option{^-O1^-O1^},
14492 @file{b.adb} with ^switches^switches^
14493 @option{^-O2^-O2^}
14494 and @option{^-gnaty^-gnaty^},
14495 and @file{c.adb} with @option{^-g^-g^}.
14496
14497 The following example illustrates the ordering of the ^switches^switches^
14498 contributed by different packages:
14499
14500 @smallexample @c projectfile
14501 @group
14502 project Proj2 is
14503    package Builder is
14504       for ^Switches^Switches^ ("main.adb")
14505           use ("^-g^-g^",
14506                "^-O1^-)1^",
14507                "^-f^-f^");
14508    end Builder;
14509 @end group
14510
14511 @group
14512    package Compiler is
14513       for ^Switches^Switches^ ("main.adb")
14514           use ("^-O2^-O2^");
14515    end Compiler;
14516 end Proj2;
14517 @end group
14518 @end smallexample
14519
14520 @noindent
14521 If you issue the command:
14522
14523 @smallexample
14524     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14525 @end smallexample
14526
14527 @noindent
14528 then the compiler will be invoked on @file{main.adb} with the following
14529 sequence of ^switches^switches^
14530
14531 @smallexample
14532    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14533 @end smallexample
14534
14535 with the last @option{^-O^-O^}
14536 ^switch^switch^ having precedence over the earlier ones;
14537 several other ^switches^switches^
14538 (such as @option{^-c^-c^}) are added implicitly.
14539
14540 The ^switches^switches^
14541 @option{^-g^-g^}
14542 and @option{^-O1^-O1^} are contributed by package
14543 @code{Builder},  @option{^-O2^-O2^} is contributed
14544 by the package @code{Compiler}
14545 and @option{^-O0^-O0^} comes from the command line.
14546
14547 The @option{^-g^-g^}
14548 ^switch^switch^ will also be passed in the invocation of
14549 @command{Gnatlink.}
14550
14551 A final example illustrates switch contributions from packages in different
14552 project files:
14553
14554 @smallexample @c projectfile
14555 @group
14556 project Proj3 is
14557    for Source_Files use ("pack.ads", "pack.adb");
14558    package Compiler is
14559       for ^Default_Switches^Default_Switches^ ("Ada")
14560           use ("^-gnata^-gnata^");
14561    end Compiler;
14562 end Proj3;
14563 @end group
14564
14565 @group
14566 with "Proj3";
14567 project Proj4 is
14568    for Source_Files use ("foo_main.adb", "bar_main.adb");
14569    package Builder is
14570       for ^Switches^Switches^ ("foo_main.adb")
14571           use ("^-s^-s^",
14572                "^-g^-g^");
14573    end Builder;
14574 end Proj4;
14575 @end group
14576
14577 @group
14578 -- Ada source file:
14579 with Pack;
14580 procedure Foo_Main is
14581    @dots{}
14582 end Foo_Main;
14583 @end group
14584 @end smallexample
14585
14586 If the command is
14587 @smallexample
14588 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14589 @end smallexample
14590
14591 @noindent
14592 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14593 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14594 @option{^-gnato^-gnato^} (passed on the command line).
14595 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14596 are @option{^-g^-g^} from @code{Proj4.Builder},
14597 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14598 and @option{^-gnato^-gnato^} from the command line.
14599
14600 @noindent
14601 When using @command{gnatmake} with project files, some ^switches^switches^ or
14602 arguments may be expressed as relative paths. As the working directory where
14603 compilation occurs may change, these relative paths are converted to absolute
14604 paths. For the ^switches^switches^ found in a project file, the relative paths
14605 are relative to the project file directory, for the switches on the command
14606 line, they are relative to the directory where @command{gnatmake} is invoked.
14607 The ^switches^switches^ for which this occurs are:
14608 ^-I^-I^,
14609 ^-A^-A^,
14610 ^-L^-L^,
14611 ^-aO^-aO^,
14612 ^-aL^-aL^,
14613 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14614 ^switch^switch^
14615 ^-o^-o^, object files specified in package @code{Linker} or after
14616 -largs on the command line). The exception to this rule is the ^switch^switch^
14617 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14618
14619 @node Specifying Configuration Pragmas
14620 @subsubsection Specifying Configuration Pragmas
14621
14622 When using @command{gnatmake} with project files, if there exists a file
14623 @file{gnat.adc} that contains configuration pragmas, this file will be
14624 ignored.
14625
14626 Configuration pragmas can be defined by means of the following attributes in
14627 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14628 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14629
14630 Both these attributes are single string attributes. Their values is the path
14631 name of a file containing configuration pragmas. If a path name is relative,
14632 then it is relative to the project directory of the project file where the
14633 attribute is defined.
14634
14635 When compiling a source, the configuration pragmas used are, in order,
14636 those listed in the file designated by attribute
14637 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14638 project file, if it is specified, and those listed in the file designated by
14639 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14640 the project file of the source, if it exists.
14641
14642 @node Project Files and Main Subprograms
14643 @subsubsection Project Files and Main Subprograms
14644
14645 @noindent
14646 When using a project file, you can invoke @command{gnatmake}
14647 with one or several main subprograms, by specifying their source files on the
14648 command line.
14649
14650 @smallexample
14651     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14652 @end smallexample
14653
14654 @noindent
14655 Each of these needs to be a source file of the same project, except
14656 when the switch ^-u^/UNIQUE^ is used.
14657
14658 @noindent
14659 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14660 same project, one of the project in the tree rooted at the project specified
14661 on the command line. The package @code{Builder} of this common project, the
14662 "main project" is the one that is considered by @command{gnatmake}.
14663
14664 @noindent
14665 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14666 imported directly or indirectly by the project specified on the command line.
14667 Note that if such a source file is not part of the project specified on the
14668 command line, the ^switches^switches^ found in package @code{Builder} of the
14669 project specified on the command line, if any, that are transmitted
14670 to the compiler will still be used, not those found in the project file of
14671 the source file.
14672
14673 @noindent
14674 When using a project file, you can also invoke @command{gnatmake} without
14675 explicitly specifying any main, and the effect depends on whether you have
14676 defined the @code{Main} attribute.  This attribute has a string list value,
14677 where each element in the list is the name of a source file (the file
14678 extension is optional) that contains a unit that can be a main subprogram.
14679
14680 If the @code{Main} attribute is defined in a project file as a non-empty
14681 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14682 line, then invoking @command{gnatmake} with this project file but without any
14683 main on the command line is equivalent to invoking @command{gnatmake} with all
14684 the file names in the @code{Main} attribute on the command line.
14685
14686 Example:
14687 @smallexample @c projectfile
14688 @group
14689    project Prj is
14690       for Main use ("main1", "main2", "main3");
14691    end Prj;
14692 @end group
14693 @end smallexample
14694
14695 @noindent
14696 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14697 is equivalent to
14698 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14699
14700 When the project attribute @code{Main} is not specified, or is specified
14701 as an empty string list, or when the switch @option{-u} is used on the command
14702 line, then invoking @command{gnatmake} with no main on the command line will
14703 result in all immediate sources of the project file being checked, and
14704 potentially recompiled. Depending on the presence of the switch @option{-u},
14705 sources from other project files on which the immediate sources of the main
14706 project file depend are also checked and potentially recompiled. In other
14707 words, the @option{-u} switch is applied to all of the immediate sources of the
14708 main project file.
14709
14710 When no main is specified on the command line and attribute @code{Main} exists
14711 and includes several mains, or when several mains are specified on the
14712 command line, the default ^switches^switches^ in package @code{Builder} will
14713 be used for all mains, even if there are specific ^switches^switches^
14714 specified for one or several mains.
14715
14716 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14717 the specific ^switches^switches^ for each main, if they are specified.
14718
14719 @node Library Project Files
14720 @subsubsection Library Project Files
14721
14722 @noindent
14723 When @command{gnatmake} is invoked with a main project file that is a library
14724 project file, it is not allowed to specify one or more mains on the command
14725 line.
14726
14727 @noindent
14728 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14729 ^-l^/ACTION=LINK^ have special meanings.
14730
14731 @itemize @bullet
14732 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14733 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14734 library.
14735
14736 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14737 to @command{gnatmake} that the binder generated file should be compiled
14738 (in the case of a stand-alone library) and that the library should be built.
14739
14740 @end itemize
14741
14742 @node The GNAT Driver and Project Files
14743 @subsection The GNAT Driver and Project Files
14744
14745 @noindent
14746 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14747 can benefit from project files:
14748 (@command{^gnatbind^gnatbind^},
14749 @command{^gnatcheck^gnatcheck^},
14750 @command{^gnatclean^gnatclean^},
14751 @command{^gnatelim^gnatelim^},
14752 @command{^gnatfind^gnatfind^},
14753 @command{^gnatlink^gnatlink^},
14754 @command{^gnatls^gnatls^},
14755 @command{^gnatmetric^gnatmetric^},
14756 @command{^gnatpp^gnatpp^},
14757 @command{^gnatstub^gnatstub^},
14758 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
14759 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14760 They must be invoked through the @command{gnat} driver.
14761
14762 The @command{gnat} driver is a wrapper that accepts a number of commands and
14763 calls the corresponding tool. It was designed initially for VMS platforms (to
14764 convert VMS qualifiers to Unix-style switches), but it is now available on all
14765 GNAT platforms.
14766
14767 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14768 (case insensitive):
14769
14770 @itemize @bullet
14771 @item
14772 BIND to invoke @command{^gnatbind^gnatbind^}
14773 @item
14774 CHOP to invoke @command{^gnatchop^gnatchop^}
14775 @item
14776 CLEAN to invoke @command{^gnatclean^gnatclean^}
14777 @item
14778 COMP or COMPILE to invoke the compiler
14779 @item
14780 ELIM to invoke @command{^gnatelim^gnatelim^}
14781 @item
14782 FIND to invoke @command{^gnatfind^gnatfind^}
14783 @item
14784 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14785 @item
14786 LINK to invoke @command{^gnatlink^gnatlink^}
14787 @item
14788 LS or LIST to invoke @command{^gnatls^gnatls^}
14789 @item
14790 MAKE to invoke @command{^gnatmake^gnatmake^}
14791 @item
14792 NAME to invoke @command{^gnatname^gnatname^}
14793 @item
14794 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14795 @item
14796 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14797 @item
14798 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14799 @item
14800 STUB to invoke @command{^gnatstub^gnatstub^}
14801 @item
14802 XREF to invoke @command{^gnatxref^gnatxref^}
14803 @end itemize
14804
14805 @noindent
14806 (note that the compiler is invoked using the command
14807 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14808
14809 @noindent
14810 On non-VMS platforms, between @command{gnat} and the command, two
14811 special switches may be used:
14812
14813 @itemize @bullet
14814 @item
14815 @command{-v} to display the invocation of the tool.
14816 @item
14817 @command{-dn} to prevent the @command{gnat} driver from removing
14818 the temporary files it has created. These temporary files are
14819 configuration files and temporary file list files.
14820 @end itemize
14821
14822 @noindent
14823 The command may be followed by switches and arguments for the invoked
14824 tool.
14825
14826 @smallexample
14827   gnat bind -C main.ali
14828   gnat ls -a main
14829   gnat chop foo.txt
14830 @end smallexample
14831
14832 @noindent
14833 Switches may also be put in text files, one switch per line, and the text
14834 files may be specified with their path name preceded by '@@'.
14835
14836 @smallexample
14837    gnat bind @@args.txt main.ali
14838 @end smallexample
14839
14840 @noindent
14841 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14842 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14843 (@option{^-P^/PROJECT_FILE^},
14844 @option{^-X^/EXTERNAL_REFERENCE^} and
14845 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14846 the switches of the invoking tool.
14847
14848 @noindent
14849 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14850 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14851 the immediate sources of the specified project file.
14852
14853 @noindent
14854 When GNAT METRIC is used with a project file, but with no source
14855 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14856 with all the immediate sources of the specified project file and with
14857 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14858 of the project.
14859
14860 @noindent
14861 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14862 a project file, no source is specified on the command line and
14863 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14864 the underlying tool (^gnatpp^gnatpp^ or
14865 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14866 not only for the immediate sources of the main project.
14867 @ifclear vms
14868 (-U stands for Universal or Union of the project files of the project tree)
14869 @end ifclear
14870
14871 @noindent
14872 For each of the following commands, there is optionally a corresponding
14873 package in the main project.
14874
14875 @itemize @bullet
14876 @item
14877 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14878
14879 @item
14880 package @code{Check} for command CHECK (invoking
14881 @code{^gnatcheck^gnatcheck^})
14882
14883 @item
14884 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14885
14886 @item
14887 package @code{Cross_Reference} for command XREF (invoking
14888 @code{^gnatxref^gnatxref^})
14889
14890 @item
14891 package @code{Eliminate} for command ELIM (invoking
14892 @code{^gnatelim^gnatelim^})
14893
14894 @item
14895 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14896
14897 @item
14898 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14899
14900 @item
14901 package @code{Gnatstub} for command STUB
14902 (invoking @code{^gnatstub^gnatstub^})
14903
14904 @item
14905 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14906
14907 @item
14908 package @code{Check} for command CHECK
14909 (invoking @code{^gnatcheck^gnatcheck^})
14910
14911 @item
14912 package @code{Metrics} for command METRIC
14913 (invoking @code{^gnatmetric^gnatmetric^})
14914
14915 @item
14916 package @code{Pretty_Printer} for command PP or PRETTY
14917 (invoking @code{^gnatpp^gnatpp^})
14918
14919 @end itemize
14920
14921 @noindent
14922 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14923 a simple variable with a string list value. It contains ^switches^switches^
14924 for the invocation of @code{^gnatls^gnatls^}.
14925
14926 @smallexample @c projectfile
14927 @group
14928 project Proj1 is
14929    package gnatls is
14930       for ^Switches^Switches^
14931           use ("^-a^-a^",
14932                "^-v^-v^");
14933    end gnatls;
14934 end Proj1;
14935 @end group
14936 @end smallexample
14937
14938 @noindent
14939 All other packages have two attribute @code{^Switches^Switches^} and
14940 @code{^Default_Switches^Default_Switches^}.
14941
14942 @noindent
14943 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14944 source file name, that has a string list value: the ^switches^switches^ to be
14945 used when the tool corresponding to the package is invoked for the specific
14946 source file.
14947
14948 @noindent
14949 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14950 indexed by  the programming language that has a string list value.
14951 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14952 ^switches^switches^ for the invocation of the tool corresponding
14953 to the package, except if a specific @code{^Switches^Switches^} attribute
14954 is specified for the source file.
14955
14956 @smallexample @c projectfile
14957 @group
14958 project Proj is
14959
14960    for Source_Dirs use ("./**");
14961
14962    package gnatls is
14963       for ^Switches^Switches^ use
14964           ("^-a^-a^",
14965            "^-v^-v^");
14966    end gnatls;
14967 @end group
14968 @group
14969
14970    package Compiler is
14971       for ^Default_Switches^Default_Switches^ ("Ada")
14972           use ("^-gnatv^-gnatv^",
14973                "^-gnatwa^-gnatwa^");
14974    end Binder;
14975 @end group
14976 @group
14977
14978    package Binder is
14979       for ^Default_Switches^Default_Switches^ ("Ada")
14980           use ("^-C^-C^",
14981                "^-e^-e^");
14982    end Binder;
14983 @end group
14984 @group
14985
14986    package Linker is
14987       for ^Default_Switches^Default_Switches^ ("Ada")
14988           use ("^-C^-C^");
14989       for ^Switches^Switches^ ("main.adb")
14990           use ("^-C^-C^",
14991                "^-v^-v^",
14992                "^-v^-v^");
14993    end Linker;
14994 @end group
14995 @group
14996
14997    package Finder is
14998       for ^Default_Switches^Default_Switches^ ("Ada")
14999            use ("^-a^-a^",
15000                 "^-f^-f^");
15001    end Finder;
15002 @end group
15003 @group
15004
15005    package Cross_Reference is
15006       for ^Default_Switches^Default_Switches^ ("Ada")
15007           use ("^-a^-a^",
15008                "^-f^-f^",
15009                "^-d^-d^",
15010                "^-u^-u^");
15011    end Cross_Reference;
15012 end Proj;
15013 @end group
15014 @end smallexample
15015
15016 @noindent
15017 With the above project file, commands such as
15018
15019 @smallexample
15020    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15021    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15022    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15023    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15024    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15025 @end smallexample
15026
15027 @noindent
15028 will set up the environment properly and invoke the tool with the switches
15029 found in the package corresponding to the tool:
15030 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15031 except @code{^Switches^Switches^ ("main.adb")}
15032 for @code{^gnatlink^gnatlink^}.
15033 It is also possible to invoke some of the tools,
15034 (@code{^gnatcheck^gnatcheck^},
15035 @code{^gnatmetric^gnatmetric^},
15036 and @code{^gnatpp^gnatpp^})
15037 on a set of project units thanks to the combination of the switches
15038 @option{-P}, @option{-U} and possibly the main unit when one is interested
15039 in its closure. For instance,
15040 @smallexample
15041 gnat metric -Pproj
15042 @end smallexample
15043 will compute the metrics for all the immediate units of project
15044 @code{proj}.
15045 @smallexample
15046 gnat metric -Pproj -U
15047 @end smallexample
15048 will compute the metrics for all the units of the closure of projects
15049 rooted at @code{proj}.
15050 @smallexample
15051 gnat metric -Pproj -U main_unit
15052 @end smallexample
15053 will compute the metrics for the closure of units rooted at
15054 @code{main_unit}. This last possibility relies implicitly
15055 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
15056 tool invoked by the the @command{gnat} driver are explicitly  specified
15057 either directly or through the tool @option{-files} option, then the tool
15058 is called only for these explicitly specified files.
15059
15060 @c **********************
15061 @node An Extended Example
15062 @section An Extended Example
15063
15064 @noindent
15065 Suppose that we have two programs, @var{prog1} and @var{prog2},
15066 whose sources are in corresponding directories. We would like
15067 to build them with a single @command{gnatmake} command, and we want to place
15068 their object files into @file{build} subdirectories of the source directories.
15069 Furthermore, we want to have to have two separate subdirectories
15070 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15071 the object files compiled with different set of compilation flags.
15072
15073 In other words, we have the following structure:
15074
15075 @smallexample
15076 @group
15077    main
15078      |- prog1
15079      |    |- build
15080      |         | debug
15081      |         | release
15082      |- prog2
15083           |- build
15084                | debug
15085                | release
15086 @end group
15087 @end smallexample
15088
15089 @noindent
15090 Here are the project files that we must place in a directory @file{main}
15091 to maintain this structure:
15092
15093 @enumerate
15094
15095 @item We create a @code{Common} project with a package @code{Compiler} that
15096 specifies the compilation ^switches^switches^:
15097
15098 @smallexample
15099 File "common.gpr":
15100 @group
15101 @b{project} Common @b{is}
15102
15103    @b{for} Source_Dirs @b{use} (); -- No source files
15104 @end group
15105
15106 @group
15107    @b{type} Build_Type @b{is} ("release", "debug");
15108    Build : Build_Type := External ("BUILD", "debug");
15109 @end group
15110 @group
15111    @b{package} Compiler @b{is}
15112       @b{case} Build @b{is}
15113          @b{when} "release" =>
15114            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15115                    @b{use} ("^-O2^-O2^");
15116          @b{when} "debug"   =>
15117            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15118                    @b{use} ("^-g^-g^");
15119       @b{end case};
15120    @b{end} Compiler;
15121
15122 @b{end} Common;
15123 @end group
15124 @end smallexample
15125
15126 @item We create separate projects for the two programs:
15127
15128 @smallexample
15129 @group
15130 File "prog1.gpr":
15131
15132 @b{with} "common";
15133 @b{project} Prog1 @b{is}
15134
15135     @b{for} Source_Dirs @b{use} ("prog1");
15136     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15137
15138     @b{package} Compiler @b{renames} Common.Compiler;
15139
15140 @b{end} Prog1;
15141 @end group
15142 @end smallexample
15143
15144 @smallexample
15145 @group
15146 File "prog2.gpr":
15147
15148 @b{with} "common";
15149 @b{project} Prog2 @b{is}
15150
15151     @b{for} Source_Dirs @b{use} ("prog2");
15152     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15153
15154     @b{package} Compiler @b{renames} Common.Compiler;
15155
15156 @end group
15157 @b{end} Prog2;
15158 @end smallexample
15159
15160 @item We create a wrapping project @code{Main}:
15161
15162 @smallexample
15163 @group
15164 File "main.gpr":
15165
15166 @b{with} "common";
15167 @b{with} "prog1";
15168 @b{with} "prog2";
15169 @b{project} Main @b{is}
15170
15171    @b{package} Compiler @b{renames} Common.Compiler;
15172
15173 @b{end} Main;
15174 @end group
15175 @end smallexample
15176
15177 @item Finally we need to create a dummy procedure that @code{with}s (either
15178 explicitly or implicitly) all the sources of our two programs.
15179
15180 @end enumerate
15181
15182 @noindent
15183 Now we can build the programs using the command
15184
15185 @smallexample
15186    gnatmake ^-P^/PROJECT_FILE=^main dummy
15187 @end smallexample
15188
15189 @noindent
15190 for the Debug mode, or
15191
15192 @ifclear vms
15193 @smallexample
15194    gnatmake -Pmain -XBUILD=release
15195 @end smallexample
15196 @end ifclear
15197
15198 @ifset vms
15199 @smallexample
15200    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15201 @end smallexample
15202 @end ifset
15203
15204 @noindent
15205 for the Release mode.
15206
15207 @c ********************************
15208 @c * Project File Complete Syntax *
15209 @c ********************************
15210
15211 @node Project File Complete Syntax
15212 @section Project File Complete Syntax
15213
15214 @smallexample
15215 project ::=
15216   context_clause project_declaration
15217
15218 context_clause ::=
15219   @{with_clause@}
15220
15221 with_clause ::=
15222   @b{with} path_name @{ , path_name @} ;
15223
15224 path_name ::=
15225    string_literal
15226
15227 project_declaration ::=
15228   simple_project_declaration | project_extension
15229
15230 simple_project_declaration ::=
15231   @b{project} <project_>simple_name @b{is}
15232     @{declarative_item@}
15233   @b{end} <project_>simple_name;
15234
15235 project_extension ::=
15236   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15237     @{declarative_item@}
15238   @b{end} <project_>simple_name;
15239
15240 declarative_item ::=
15241   package_declaration |
15242   typed_string_declaration |
15243   other_declarative_item
15244
15245 package_declaration ::=
15246   package_spec | package_renaming
15247
15248 package_spec ::=
15249   @b{package} package_identifier @b{is}
15250     @{simple_declarative_item@}
15251   @b{end} package_identifier ;
15252
15253 package_identifier ::=
15254   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15255   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15256   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15257
15258 package_renaming ::==
15259   @b{package} package_identifier @b{renames}
15260        <project_>simple_name.package_identifier ;
15261
15262 typed_string_declaration ::=
15263   @b{type} <typed_string_>_simple_name @b{is}
15264    ( string_literal @{, string_literal@} );
15265
15266 other_declarative_item ::=
15267   attribute_declaration |
15268   typed_variable_declaration |
15269   variable_declaration |
15270   case_construction
15271
15272 attribute_declaration ::=
15273   full_associative_array_declaration |
15274   @b{for} attribute_designator @b{use} expression ;
15275
15276 full_associative_array_declaration ::=
15277   @b{for} <associative_array_attribute_>simple_name @b{use}
15278   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15279
15280 attribute_designator ::=
15281   <simple_attribute_>simple_name |
15282   <associative_array_attribute_>simple_name ( string_literal )
15283
15284 typed_variable_declaration ::=
15285   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15286
15287 variable_declaration ::=
15288   <variable_>simple_name := expression;
15289
15290 expression ::=
15291   term @{& term@}
15292
15293 term ::=
15294   literal_string |
15295   string_list |
15296   <variable_>name |
15297   external_value |
15298   attribute_reference
15299
15300 string_literal ::=
15301   (same as Ada)
15302
15303 string_list ::=
15304   ( <string_>expression @{ , <string_>expression @} )
15305
15306 external_value ::=
15307   @b{external} ( string_literal [, string_literal] )
15308
15309 attribute_reference ::=
15310   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15311
15312 attribute_prefix ::=
15313   @b{project} |
15314   <project_>simple_name | package_identifier |
15315   <project_>simple_name . package_identifier
15316
15317 case_construction ::=
15318   @b{case} <typed_variable_>name @b{is}
15319     @{case_item@}
15320   @b{end case} ;
15321
15322 case_item ::=
15323   @b{when} discrete_choice_list =>
15324       @{case_construction | attribute_declaration@}
15325
15326 discrete_choice_list ::=
15327   string_literal @{| string_literal@} |
15328   @b{others}
15329
15330 name ::=
15331   simple_name @{. simple_name@}
15332
15333 simple_name ::=
15334   identifier (same as Ada)
15335
15336 @end smallexample
15337
15338 @node The Cross-Referencing Tools gnatxref and gnatfind
15339 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15340 @findex gnatxref
15341 @findex gnatfind
15342
15343 @noindent
15344 The compiler generates cross-referencing information (unless
15345 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15346 This information indicates where in the source each entity is declared and
15347 referenced. Note that entities in package Standard are not included, but
15348 entities in all other predefined units are included in the output.
15349
15350 Before using any of these two tools, you need to compile successfully your
15351 application, so that GNAT gets a chance to generate the cross-referencing
15352 information.
15353
15354 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15355 information to provide the user with the capability to easily locate the
15356 declaration and references to an entity. These tools are quite similar,
15357 the difference being that @code{gnatfind} is intended for locating
15358 definitions and/or references to a specified entity or entities, whereas
15359 @code{gnatxref} is oriented to generating a full report of all
15360 cross-references.
15361
15362 To use these tools, you must not compile your application using the
15363 @option{-gnatx} switch on the @command{gnatmake} command line
15364 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15365 information will not be generated.
15366
15367 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15368 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15369
15370 @menu
15371 * Switches for gnatxref::
15372 * Switches for gnatfind::
15373 * Project Files for gnatxref and gnatfind::
15374 * Regular Expressions in gnatfind and gnatxref::
15375 * Examples of gnatxref Usage::
15376 * Examples of gnatfind Usage::
15377 @end menu
15378
15379 @node Switches for gnatxref
15380 @section @code{gnatxref} Switches
15381
15382 @noindent
15383 The command invocation for @code{gnatxref} is:
15384 @smallexample
15385 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15386 @c Expanding @ovar macro inline (explanation in macro def comments)
15387 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15388 @end smallexample
15389
15390 @noindent
15391 where
15392
15393 @table @var
15394 @item sourcefile1
15395 @itemx sourcefile2
15396 identifies the source files for which a report is to be generated. The
15397 ``with''ed units will be processed too. You must provide at least one file.
15398
15399 These file names are considered to be regular expressions, so for instance
15400 specifying @file{source*.adb} is the same as giving every file in the current
15401 directory whose name starts with @file{source} and whose extension is
15402 @file{adb}.
15403
15404 You shouldn't specify any directory name, just base names. @command{gnatxref}
15405 and @command{gnatfind} will be able to locate these files by themselves using
15406 the source path. If you specify directories, no result is produced.
15407
15408 @end table
15409
15410 @noindent
15411 The switches can be:
15412 @table @option
15413 @c !sort!
15414 @item --version
15415 @cindex @option{--version} @command{gnatxref}
15416 Display Copyright and version, then exit disregarding all other options.
15417
15418 @item --help
15419 @cindex @option{--help} @command{gnatxref}
15420 If @option{--version} was not used, display usage, then exit disregarding
15421 all other options.
15422
15423 @item ^-a^/ALL_FILES^
15424 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15425 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15426 the read-only files found in the library search path. Otherwise, these files
15427 will be ignored. This option can be used to protect Gnat sources or your own
15428 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15429 much faster, and their output much smaller. Read-only here refers to access
15430 or permissions status in the file system for the current user.
15431
15432 @item -aIDIR
15433 @cindex @option{-aIDIR} (@command{gnatxref})
15434 When looking for source files also look in directory DIR. The order in which
15435 source file search is undertaken is the same as for @command{gnatmake}.
15436
15437 @item -aODIR
15438 @cindex @option{-aODIR} (@command{gnatxref})
15439 When searching for library and object files, look in directory
15440 DIR. The order in which library files are searched is the same as for
15441 @command{gnatmake}.
15442
15443 @item -nostdinc
15444 @cindex @option{-nostdinc} (@command{gnatxref})
15445 Do not look for sources in the system default directory.
15446
15447 @item -nostdlib
15448 @cindex @option{-nostdlib} (@command{gnatxref})
15449 Do not look for library files in the system default directory.
15450
15451 @item --RTS=@var{rts-path}
15452 @cindex @option{--RTS} (@command{gnatxref})
15453 Specifies the default location of the runtime library. Same meaning as the
15454 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15455
15456 @item ^-d^/DERIVED_TYPES^
15457 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15458 If this switch is set @code{gnatxref} will output the parent type
15459 reference for each matching derived types.
15460
15461 @item ^-f^/FULL_PATHNAME^
15462 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15463 If this switch is set, the output file names will be preceded by their
15464 directory (if the file was found in the search path). If this switch is
15465 not set, the directory will not be printed.
15466
15467 @item ^-g^/IGNORE_LOCALS^
15468 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15469 If this switch is set, information is output only for library-level
15470 entities, ignoring local entities. The use of this switch may accelerate
15471 @code{gnatfind} and @code{gnatxref}.
15472
15473 @item -IDIR
15474 @cindex @option{-IDIR} (@command{gnatxref})
15475 Equivalent to @samp{-aODIR -aIDIR}.
15476
15477 @item -pFILE
15478 @cindex @option{-pFILE} (@command{gnatxref})
15479 Specify a project file to use @xref{Project Files}.
15480 If you need to use the @file{.gpr}
15481 project files, you should use gnatxref through the GNAT driver
15482 (@command{gnat xref -Pproject}).
15483
15484 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15485 project file in the current directory.
15486
15487 If a project file is either specified or found by the tools, then the content
15488 of the source directory and object directory lines are added as if they
15489 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15490 and @samp{^-aO^OBJECT_SEARCH^}.
15491 @item ^-u^/UNUSED^
15492 Output only unused symbols. This may be really useful if you give your
15493 main compilation unit on the command line, as @code{gnatxref} will then
15494 display every unused entity and 'with'ed package.
15495
15496 @ifclear vms
15497 @item -v
15498 Instead of producing the default output, @code{gnatxref} will generate a
15499 @file{tags} file that can be used by vi. For examples how to use this
15500 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15501 to the standard output, thus you will have to redirect it to a file.
15502 @end ifclear
15503
15504 @end table
15505
15506 @noindent
15507 All these switches may be in any order on the command line, and may even
15508 appear after the file names. They need not be separated by spaces, thus
15509 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15510 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15511
15512 @node Switches for gnatfind
15513 @section @code{gnatfind} Switches
15514
15515 @noindent
15516 The command line for @code{gnatfind} is:
15517
15518 @smallexample
15519 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15520 @c       @r{[}@var{file1} @var{file2} @dots{}]
15521 @c Expanding @ovar macro inline (explanation in macro def comments)
15522 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15523       @r{[}@var{file1} @var{file2} @dots{}@r{]}
15524 @end smallexample
15525
15526 @noindent
15527 where
15528
15529 @table @var
15530 @item pattern
15531 An entity will be output only if it matches the regular expression found
15532 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15533
15534 Omitting the pattern is equivalent to specifying @samp{*}, which
15535 will match any entity. Note that if you do not provide a pattern, you
15536 have to provide both a sourcefile and a line.
15537
15538 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15539 for matching purposes. At the current time there is no support for
15540 8-bit codes other than Latin-1, or for wide characters in identifiers.
15541
15542 @item sourcefile
15543 @code{gnatfind} will look for references, bodies or declarations
15544 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15545 and column @var{column}. See @ref{Examples of gnatfind Usage}
15546 for syntax examples.
15547
15548 @item line
15549 is a decimal integer identifying the line number containing
15550 the reference to the entity (or entities) to be located.
15551
15552 @item column
15553 is a decimal integer identifying the exact location on the
15554 line of the first character of the identifier for the
15555 entity reference. Columns are numbered from 1.
15556
15557 @item file1 file2 @dots{}
15558 The search will be restricted to these source files. If none are given, then
15559 the search will be done for every library file in the search path.
15560 These file must appear only after the pattern or sourcefile.
15561
15562 These file names are considered to be regular expressions, so for instance
15563 specifying @file{source*.adb} is the same as giving every file in the current
15564 directory whose name starts with @file{source} and whose extension is
15565 @file{adb}.
15566
15567 The location of the spec of the entity will always be displayed, even if it
15568 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15569 occurrences of the entity in the separate units of the ones given on the
15570 command line will also be displayed.
15571
15572 Note that if you specify at least one file in this part, @code{gnatfind} may
15573 sometimes not be able to find the body of the subprograms.
15574
15575 @end table
15576
15577 @noindent
15578 At least one of 'sourcefile' or 'pattern' has to be present on
15579 the command line.
15580
15581 The following switches are available:
15582 @table @option
15583 @c !sort!
15584
15585 @cindex @option{--version} @command{gnatfind}
15586 Display Copyright and version, then exit disregarding all other options.
15587
15588 @item --help
15589 @cindex @option{--help} @command{gnatfind}
15590 If @option{--version} was not used, display usage, then exit disregarding
15591 all other options.
15592
15593 @item ^-a^/ALL_FILES^
15594 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15595 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15596 the read-only files found in the library search path. Otherwise, these files
15597 will be ignored. This option can be used to protect Gnat sources or your own
15598 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15599 much faster, and their output much smaller. Read-only here refers to access
15600 or permission status in the file system for the current user.
15601
15602 @item -aIDIR
15603 @cindex @option{-aIDIR} (@command{gnatfind})
15604 When looking for source files also look in directory DIR. The order in which
15605 source file search is undertaken is the same as for @command{gnatmake}.
15606
15607 @item -aODIR
15608 @cindex @option{-aODIR} (@command{gnatfind})
15609 When searching for library and object files, look in directory
15610 DIR. The order in which library files are searched is the same as for
15611 @command{gnatmake}.
15612
15613 @item -nostdinc
15614 @cindex @option{-nostdinc} (@command{gnatfind})
15615 Do not look for sources in the system default directory.
15616
15617 @item -nostdlib
15618 @cindex @option{-nostdlib} (@command{gnatfind})
15619 Do not look for library files in the system default directory.
15620
15621 @item --ext=@var{extension}
15622 @cindex @option{--ext} (@command{gnatfind})
15623 Specify an alternate ali file extension. The default is @code{ali} and other
15624 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15625 switch. Note that if this switch overrides the default, which means that only
15626 the new extension will be considered.
15627
15628 @item --RTS=@var{rts-path}
15629 @cindex @option{--RTS} (@command{gnatfind})
15630 Specifies the default location of the runtime library. Same meaning as the
15631 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15632
15633 @item ^-d^/DERIVED_TYPE_INFORMATION^
15634 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15635 If this switch is set, then @code{gnatfind} will output the parent type
15636 reference for each matching derived types.
15637
15638 @item ^-e^/EXPRESSIONS^
15639 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15640 By default, @code{gnatfind} accept the simple regular expression set for
15641 @samp{pattern}. If this switch is set, then the pattern will be
15642 considered as full Unix-style regular expression.
15643
15644 @item ^-f^/FULL_PATHNAME^
15645 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15646 If this switch is set, the output file names will be preceded by their
15647 directory (if the file was found in the search path). If this switch is
15648 not set, the directory will not be printed.
15649
15650 @item ^-g^/IGNORE_LOCALS^
15651 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15652 If this switch is set, information is output only for library-level
15653 entities, ignoring local entities. The use of this switch may accelerate
15654 @code{gnatfind} and @code{gnatxref}.
15655
15656 @item -IDIR
15657 @cindex @option{-IDIR} (@command{gnatfind})
15658 Equivalent to @samp{-aODIR -aIDIR}.
15659
15660 @item -pFILE
15661 @cindex @option{-pFILE} (@command{gnatfind})
15662 Specify a project file (@pxref{Project Files}) to use.
15663 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15664 project file in the current directory.
15665
15666 If a project file is either specified or found by the tools, then the content
15667 of the source directory and object directory lines are added as if they
15668 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15669 @samp{^-aO^/OBJECT_SEARCH^}.
15670
15671 @item ^-r^/REFERENCES^
15672 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15673 By default, @code{gnatfind} will output only the information about the
15674 declaration, body or type completion of the entities. If this switch is
15675 set, the @code{gnatfind} will locate every reference to the entities in
15676 the files specified on the command line (or in every file in the search
15677 path if no file is given on the command line).
15678
15679 @item ^-s^/PRINT_LINES^
15680 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15681 If this switch is set, then @code{gnatfind} will output the content
15682 of the Ada source file lines were the entity was found.
15683
15684 @item ^-t^/TYPE_HIERARCHY^
15685 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15686 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15687 the specified type. It act like -d option but recursively from parent
15688 type to parent type. When this switch is set it is not possible to
15689 specify more than one file.
15690
15691 @end table
15692
15693 @noindent
15694 All these switches may be in any order on the command line, and may even
15695 appear after the file names. They need not be separated by spaces, thus
15696 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15697 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15698
15699 As stated previously, gnatfind will search in every directory in the
15700 search path. You can force it to look only in the current directory if
15701 you specify @code{*} at the end of the command line.
15702
15703 @node Project Files for gnatxref and gnatfind
15704 @section Project Files for @command{gnatxref} and @command{gnatfind}
15705
15706 @noindent
15707 Project files allow a programmer to specify how to compile its
15708 application, where to find sources, etc.  These files are used
15709 @ifclear vms
15710 primarily by GPS, but they can also be used
15711 @end ifclear
15712 by the two tools
15713 @code{gnatxref} and @code{gnatfind}.
15714
15715 A project file name must end with @file{.gpr}. If a single one is
15716 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15717 extract the information from it. If multiple project files are found, none of
15718 them is read, and you have to use the @samp{-p} switch to specify the one
15719 you want to use.
15720
15721 The following lines can be included, even though most of them have default
15722 values which can be used in most cases.
15723 The lines can be entered in any order in the file.
15724 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15725 each line. If you have multiple instances, only the last one is taken into
15726 account.
15727
15728 @table @code
15729 @item src_dir=DIR
15730 [default: @code{"^./^[]^"}]
15731 specifies a directory where to look for source files. Multiple @code{src_dir}
15732 lines can be specified and they will be searched in the order they
15733 are specified.
15734
15735 @item obj_dir=DIR
15736 [default: @code{"^./^[]^"}]
15737 specifies a directory where to look for object and library files. Multiple
15738 @code{obj_dir} lines can be specified, and they will be searched in the order
15739 they are specified
15740
15741 @item comp_opt=SWITCHES
15742 [default: @code{""}]
15743 creates a variable which can be referred to subsequently by using
15744 the @code{$@{comp_opt@}} notation. This is intended to store the default
15745 switches given to @command{gnatmake} and @command{gcc}.
15746
15747 @item bind_opt=SWITCHES
15748 [default: @code{""}]
15749 creates a variable which can be referred to subsequently by using
15750 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15751 switches given to @command{gnatbind}.
15752
15753 @item link_opt=SWITCHES
15754 [default: @code{""}]
15755 creates a variable which can be referred to subsequently by using
15756 the @samp{$@{link_opt@}} notation. This is intended to store the default
15757 switches given to @command{gnatlink}.
15758
15759 @item main=EXECUTABLE
15760 [default: @code{""}]
15761 specifies the name of the executable for the application. This variable can
15762 be referred to in the following lines by using the @samp{$@{main@}} notation.
15763
15764 @ifset vms
15765 @item comp_cmd=COMMAND
15766 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15767 @end ifset
15768 @ifclear vms
15769 @item comp_cmd=COMMAND
15770 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15771 @end ifclear
15772 specifies the command used to compile a single file in the application.
15773
15774 @ifset vms
15775 @item make_cmd=COMMAND
15776 [default: @code{"GNAT MAKE $@{main@}
15777 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15778 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15779 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15780 @end ifset
15781 @ifclear vms
15782 @item make_cmd=COMMAND
15783 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15784 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15785 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15786 @end ifclear
15787 specifies the command used to recompile the whole application.
15788
15789 @item run_cmd=COMMAND
15790 [default: @code{"$@{main@}"}]
15791 specifies the command used to run the application.
15792
15793 @item debug_cmd=COMMAND
15794 [default: @code{"gdb $@{main@}"}]
15795 specifies the command used to debug the application
15796
15797 @end table
15798
15799 @noindent
15800 @command{gnatxref} and @command{gnatfind} only take into account the
15801 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15802
15803 @node Regular Expressions in gnatfind and gnatxref
15804 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15805
15806 @noindent
15807 As specified in the section about @command{gnatfind}, the pattern can be a
15808 regular expression. Actually, there are to set of regular expressions
15809 which are recognized by the program:
15810
15811 @table @code
15812 @item globbing patterns
15813 These are the most usual regular expression. They are the same that you
15814 generally used in a Unix shell command line, or in a DOS session.
15815
15816 Here is a more formal grammar:
15817 @smallexample
15818 @group
15819 @iftex
15820 @leftskip=.5cm
15821 @end iftex
15822 regexp ::= term
15823 term   ::= elmt            -- matches elmt
15824 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15825 term   ::= *               -- any string of 0 or more characters
15826 term   ::= ?               -- matches any character
15827 term   ::= [char @{char@}]   -- matches any character listed
15828 term   ::= [char - char]   -- matches any character in range
15829 @end group
15830 @end smallexample
15831
15832 @item full regular expression
15833 The second set of regular expressions is much more powerful. This is the
15834 type of regular expressions recognized by utilities such a @file{grep}.
15835
15836 The following is the form of a regular expression, expressed in Ada
15837 reference manual style BNF is as follows
15838
15839 @smallexample
15840 @iftex
15841 @leftskip=.5cm
15842 @end iftex
15843 @group
15844 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15845
15846 term ::= item @{item@}       -- concatenation (item then item)
15847
15848 item ::= elmt              -- match elmt
15849 item ::= elmt *            -- zero or more elmt's
15850 item ::= elmt +            -- one or more elmt's
15851 item ::= elmt ?            -- matches elmt or nothing
15852 @end group
15853 @group
15854 elmt ::= nschar            -- matches given character
15855 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15856 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15857 elmt ::= [char - char]     -- matches chars in given range
15858 elmt ::= \ char            -- matches given character
15859 elmt ::= .                 -- matches any single character
15860 elmt ::= ( regexp )        -- parens used for grouping
15861
15862 char ::= any character, including special characters
15863 nschar ::= any character except ()[].*+?^^^
15864 @end group
15865 @end smallexample
15866
15867 Following are a few examples:
15868
15869 @table @samp
15870 @item abcde|fghi
15871 will match any of the two strings @samp{abcde} and @samp{fghi},
15872
15873 @item abc*d
15874 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15875 @samp{abcccd}, and so on,
15876
15877 @item [a-z]+
15878 will match any string which has only lowercase characters in it (and at
15879 least one character.
15880
15881 @end table
15882 @end table
15883
15884 @node Examples of gnatxref Usage
15885 @section Examples of @code{gnatxref} Usage
15886
15887 @subsection General Usage
15888
15889 @noindent
15890 For the following examples, we will consider the following units:
15891
15892 @smallexample @c ada
15893 @group
15894 @cartouche
15895 main.ads:
15896 1: with Bar;
15897 2: package Main is
15898 3:     procedure Foo (B : in Integer);
15899 4:     C : Integer;
15900 5: private
15901 6:     D : Integer;
15902 7: end Main;
15903
15904 main.adb:
15905 1: package body Main is
15906 2:     procedure Foo (B : in Integer) is
15907 3:     begin
15908 4:        C := B;
15909 5:        D := B;
15910 6:        Bar.Print (B);
15911 7:        Bar.Print (C);
15912 8:     end Foo;
15913 9: end Main;
15914
15915 bar.ads:
15916 1: package Bar is
15917 2:     procedure Print (B : Integer);
15918 3: end bar;
15919 @end cartouche
15920 @end group
15921 @end smallexample
15922
15923 @table @code
15924
15925 @noindent
15926 The first thing to do is to recompile your application (for instance, in
15927 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15928 the cross-referencing information.
15929 You can then issue any of the following commands:
15930
15931 @item gnatxref main.adb
15932 @code{gnatxref} generates cross-reference information for main.adb
15933 and every unit 'with'ed by main.adb.
15934
15935 The output would be:
15936 @smallexample
15937 @iftex
15938 @leftskip=0cm
15939 @end iftex
15940 B                                                      Type: Integer
15941   Decl: bar.ads           2:22
15942 B                                                      Type: Integer
15943   Decl: main.ads          3:20
15944   Body: main.adb          2:20
15945   Ref:  main.adb          4:13     5:13     6:19
15946 Bar                                                    Type: Unit
15947   Decl: bar.ads           1:9
15948   Ref:  main.adb          6:8      7:8
15949        main.ads           1:6
15950 C                                                      Type: Integer
15951   Decl: main.ads          4:5
15952   Modi: main.adb          4:8
15953   Ref:  main.adb          7:19
15954 D                                                      Type: Integer
15955   Decl: main.ads          6:5
15956   Modi: main.adb          5:8
15957 Foo                                                    Type: Unit
15958   Decl: main.ads          3:15
15959   Body: main.adb          2:15
15960 Main                                                    Type: Unit
15961   Decl: main.ads          2:9
15962   Body: main.adb          1:14
15963 Print                                                   Type: Unit
15964   Decl: bar.ads           2:15
15965   Ref:  main.adb          6:12     7:12
15966 @end smallexample
15967
15968 @noindent
15969 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15970 its body is in main.adb, line 1, column 14 and is not referenced any where.
15971
15972 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15973 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15974
15975 @item gnatxref package1.adb package2.ads
15976 @code{gnatxref} will generates cross-reference information for
15977 package1.adb, package2.ads and any other package 'with'ed by any
15978 of these.
15979
15980 @end table
15981
15982 @ifclear vms
15983 @subsection Using gnatxref with vi
15984
15985 @code{gnatxref} can generate a tags file output, which can be used
15986 directly from @command{vi}. Note that the standard version of @command{vi}
15987 will not work properly with overloaded symbols. Consider using another
15988 free implementation of @command{vi}, such as @command{vim}.
15989
15990 @smallexample
15991 $ gnatxref -v gnatfind.adb > tags
15992 @end smallexample
15993
15994 @noindent
15995 will generate the tags file for @code{gnatfind} itself (if the sources
15996 are in the search path!).
15997
15998 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15999 (replacing @var{entity} by whatever you are looking for), and vi will
16000 display a new file with the corresponding declaration of entity.
16001 @end ifclear
16002
16003 @node Examples of gnatfind Usage
16004 @section Examples of @code{gnatfind} Usage
16005
16006 @table @code
16007
16008 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
16009 Find declarations for all entities xyz referenced at least once in
16010 main.adb. The references are search in every library file in the search
16011 path.
16012
16013 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
16014 switch is set)
16015
16016 The output will look like:
16017 @smallexample
16018 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16019 ^directory/^[directory]^main.adb:24:10: xyz <= body
16020 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16021 @end smallexample
16022
16023 @noindent
16024 that is to say, one of the entities xyz found in main.adb is declared at
16025 line 12 of main.ads (and its body is in main.adb), and another one is
16026 declared at line 45 of foo.ads
16027
16028 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16029 This is the same command as the previous one, instead @code{gnatfind} will
16030 display the content of the Ada source file lines.
16031
16032 The output will look like:
16033
16034 @smallexample
16035 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16036    procedure xyz;
16037 ^directory/^[directory]^main.adb:24:10: xyz <= body
16038    procedure xyz is
16039 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16040    xyz : Integer;
16041 @end smallexample
16042
16043 @noindent
16044 This can make it easier to find exactly the location your are looking
16045 for.
16046
16047 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16048 Find references to all entities containing an x that are
16049 referenced on line 123 of main.ads.
16050 The references will be searched only in main.ads and foo.adb.
16051
16052 @item gnatfind main.ads:123
16053 Find declarations and bodies for all entities that are referenced on
16054 line 123 of main.ads.
16055
16056 This is the same as @code{gnatfind "*":main.adb:123}.
16057
16058 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16059 Find the declaration for the entity referenced at column 45 in
16060 line 123 of file main.adb in directory mydir. Note that it
16061 is usual to omit the identifier name when the column is given,
16062 since the column position identifies a unique reference.
16063
16064 The column has to be the beginning of the identifier, and should not
16065 point to any character in the middle of the identifier.
16066
16067 @end table
16068
16069 @c *********************************
16070 @node The GNAT Pretty-Printer gnatpp
16071 @chapter The GNAT Pretty-Printer @command{gnatpp}
16072 @findex gnatpp
16073 @cindex Pretty-Printer
16074
16075 @noindent
16076 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16077 for source reformatting / pretty-printing.
16078 It takes an Ada source file as input and generates a reformatted
16079 version as output.
16080 You can specify various style directives via switches; e.g.,
16081 identifier case conventions, rules of indentation, and comment layout.
16082
16083 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16084 tree for the input source and thus requires the input to be syntactically and
16085 semantically legal.
16086 If this condition is not met, @command{gnatpp} will terminate with an
16087 error message; no output file will be generated.
16088
16089 If the source files presented to @command{gnatpp} contain
16090 preprocessing directives, then the output file will
16091 correspond to the generated source after all
16092 preprocessing is carried out. There is no way
16093 using @command{gnatpp} to obtain pretty printed files that
16094 include the preprocessing directives.
16095
16096 If the compilation unit
16097 contained in the input source depends semantically upon units located
16098 outside the current directory, you have to provide the source search path
16099 when invoking @command{gnatpp}, if these units are contained in files with
16100 names that do not follow the GNAT file naming rules, you have to provide
16101 the configuration file describing the corresponding naming scheme;
16102 see the description of the @command{gnatpp}
16103 switches below. Another possibility is to use a project file and to
16104 call @command{gnatpp} through the @command{gnat} driver
16105
16106 The @command{gnatpp} command has the form
16107
16108 @smallexample
16109 @c $ gnatpp @ovar{switches} @var{filename}
16110 @c Expanding @ovar macro inline (explanation in macro def comments)
16111 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
16112 @end smallexample
16113
16114 @noindent
16115 where
16116 @itemize @bullet
16117 @item
16118 @var{switches} is an optional sequence of switches defining such properties as
16119 the formatting rules, the source search path, and the destination for the
16120 output source file
16121
16122 @item
16123 @var{filename} is the name (including the extension) of the source file to
16124 reformat; ``wildcards'' or several file names on the same gnatpp command are
16125 allowed.  The file name may contain path information; it does not have to
16126 follow the GNAT file naming rules
16127
16128 @item
16129 @samp{@var{gcc_switches}} is a list of switches for
16130 @command{gcc}. They will be passed on to all compiler invocations made by
16131 @command{gnatelim} to generate the ASIS trees. Here you can provide
16132 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16133 use the @option{-gnatec} switch to set the configuration file etc.
16134 @end itemize
16135
16136 @menu
16137 * Switches for gnatpp::
16138 * Formatting Rules::
16139 @end menu
16140
16141 @node Switches for gnatpp
16142 @section Switches for @command{gnatpp}
16143
16144 @noindent
16145 The following subsections describe the various switches accepted by
16146 @command{gnatpp}, organized by category.
16147
16148 @ifclear vms
16149 You specify a switch by supplying a name and generally also a value.
16150 In many cases the values for a switch with a given name are incompatible with
16151 each other
16152 (for example the switch that controls the casing of a reserved word may have
16153 exactly one value: upper case, lower case, or
16154 mixed case) and thus exactly one such switch can be in effect for an
16155 invocation of @command{gnatpp}.
16156 If more than one is supplied, the last one is used.
16157 However, some values for the same switch are mutually compatible.
16158 You may supply several such switches to @command{gnatpp}, but then
16159 each must be specified in full, with both the name and the value.
16160 Abbreviated forms (the name appearing once, followed by each value) are
16161 not permitted.
16162 For example, to set
16163 the alignment of the assignment delimiter both in declarations and in
16164 assignment statements, you must write @option{-A2A3}
16165 (or @option{-A2 -A3}), but not @option{-A23}.
16166 @end ifclear
16167
16168 @ifset vms
16169 In many cases the set of options for a given qualifier are incompatible with
16170 each other (for example the qualifier that controls the casing of a reserved
16171 word may have exactly one option, which specifies either upper case, lower
16172 case, or mixed case), and thus exactly one such option can be in effect for
16173 an invocation of @command{gnatpp}.
16174 If more than one is supplied, the last one is used.
16175 However, some qualifiers have options that are mutually compatible,
16176 and then you may then supply several such options when invoking
16177 @command{gnatpp}.
16178 @end ifset
16179
16180 In most cases, it is obvious whether or not the
16181 ^values for a switch with a given name^options for a given qualifier^
16182 are compatible with each other.
16183 When the semantics might not be evident, the summaries below explicitly
16184 indicate the effect.
16185
16186 @menu
16187 * Alignment Control::
16188 * Casing Control::
16189 * Construct Layout Control::
16190 * General Text Layout Control::
16191 * Other Formatting Options::
16192 * Setting the Source Search Path::
16193 * Output File Control::
16194 * Other gnatpp Switches::
16195 @end menu
16196
16197 @node Alignment Control
16198 @subsection Alignment Control
16199 @cindex Alignment control in @command{gnatpp}
16200
16201 @noindent
16202 Programs can be easier to read if certain constructs are vertically aligned.
16203 By default all alignments are set ON.
16204 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16205 OFF, and then use one or more of the other
16206 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16207 to activate alignment for specific constructs.
16208
16209 @table @option
16210 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16211
16212 @ifset vms
16213 @item /ALIGN=ON
16214 Set all alignments to ON
16215 @end ifset
16216
16217 @item ^-A0^/ALIGN=OFF^
16218 Set all alignments to OFF
16219
16220 @item ^-A1^/ALIGN=COLONS^
16221 Align @code{:} in declarations
16222
16223 @item ^-A2^/ALIGN=DECLARATIONS^
16224 Align @code{:=} in initializations in declarations
16225
16226 @item ^-A3^/ALIGN=STATEMENTS^
16227 Align @code{:=} in assignment statements
16228
16229 @item ^-A4^/ALIGN=ARROWS^
16230 Align @code{=>} in associations
16231
16232 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16233 Align @code{at} keywords in the component clauses in record
16234 representation clauses
16235 @end table
16236
16237 @noindent
16238 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16239 is allowed.
16240
16241 @node Casing Control
16242 @subsection Casing Control
16243 @cindex Casing control in @command{gnatpp}
16244
16245 @noindent
16246 @command{gnatpp} allows you to specify the casing for reserved words,
16247 pragma names, attribute designators and identifiers.
16248 For identifiers you may define a
16249 general rule for name casing but also override this rule
16250 via a set of dictionary files.
16251
16252 Three types of casing are supported: lower case, upper case, and mixed case.
16253 Lower and upper case are self-explanatory (but since some letters in
16254 Latin1 and other GNAT-supported character sets
16255 exist only in lower-case form, an upper case conversion will have no
16256 effect on them.)
16257 ``Mixed case'' means that the first letter, and also each letter immediately
16258 following an underscore, are converted to their uppercase forms;
16259 all the other letters are converted to their lowercase forms.
16260
16261 @table @option
16262 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16263 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16264 Attribute designators are lower case
16265
16266 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16267 Attribute designators are upper case
16268
16269 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16270 Attribute designators are mixed case (this is the default)
16271
16272 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16273 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16274 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16275 lower case (this is the default)
16276
16277 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16278 Keywords are upper case
16279
16280 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16281 @item ^-nD^/NAME_CASING=AS_DECLARED^
16282 Name casing for defining occurrences are as they appear in the source file
16283 (this is the default)
16284
16285 @item ^-nU^/NAME_CASING=UPPER_CASE^
16286 Names are in upper case
16287
16288 @item ^-nL^/NAME_CASING=LOWER_CASE^
16289 Names are in lower case
16290
16291 @item ^-nM^/NAME_CASING=MIXED_CASE^
16292 Names are in mixed case
16293
16294 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16295 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16296 Pragma names are lower case
16297
16298 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16299 Pragma names are upper case
16300
16301 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16302 Pragma names are mixed case (this is the default)
16303
16304 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16305 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16306 Use @var{file} as a @emph{dictionary file} that defines
16307 the casing for a set of specified names,
16308 thereby overriding the effect on these names by
16309 any explicit or implicit
16310 ^-n^/NAME_CASING^ switch.
16311 To supply more than one dictionary file,
16312 use ^several @option{-D} switches^a list of files as options^.
16313
16314 @noindent
16315 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16316 to define the casing for the Ada predefined names and
16317 the names declared in the GNAT libraries.
16318
16319 @item ^-D-^/SPECIFIC_CASING^
16320 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16321 Do not use the default dictionary file;
16322 instead, use the casing
16323 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16324 dictionary file(s)
16325 @end table
16326
16327 @noindent
16328 The structure of a dictionary file, and details on the conventions
16329 used in the default dictionary file, are defined in @ref{Name Casing}.
16330
16331 The @option{^-D-^/SPECIFIC_CASING^} and
16332 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16333 compatible.
16334
16335 @node Construct Layout Control
16336 @subsection Construct Layout Control
16337 @cindex Layout control in @command{gnatpp}
16338
16339 @noindent
16340 This group of @command{gnatpp} switches controls the layout of comments and
16341 complex syntactic constructs.  See @ref{Formatting Comments} for details
16342 on their effect.
16343
16344 @table @option
16345 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16346 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16347 All the comments remain unchanged
16348
16349 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16350 GNAT-style comment line indentation (this is the default).
16351
16352 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16353 Reference-manual comment line indentation.
16354
16355 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16356 GNAT-style comment beginning
16357
16358 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16359 Reformat comment blocks
16360
16361 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16362 Keep unchanged special form comments
16363
16364 Reformat comment blocks
16365
16366 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16367 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16368 GNAT-style layout (this is the default)
16369
16370 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16371 Compact layout
16372
16373 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16374 Uncompact layout
16375
16376 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16377 @item ^-N^/NOTABS^
16378 All the VT characters are removed from the comment text. All the HT characters
16379 are expanded with the sequences of space characters to get to the next tab
16380 stops.
16381
16382 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16383 @item ^--no-separate-is^/NO_SEPARATE_IS^
16384 Do not place the keyword @code{is} on a separate line in a subprogram body in
16385 case if the spec occupies more then one line.
16386
16387 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16388 @item ^--separate-label^/SEPARATE_LABEL^
16389 Place statement label(s) on a separate line, with the following statement
16390 on the next line.
16391
16392 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16393 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16394 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16395 keyword @code{then} in IF statements on a separate line.
16396
16397 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16398 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16399 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16400 keyword @code{then} in IF statements on a separate line. This option is
16401 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16402
16403 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16404 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16405 Start each USE clause in a context clause from a separate line.
16406
16407 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16408 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16409 Use a separate line for a loop or block statement name, but do not use an extra
16410 indentation level for the statement itself.
16411
16412 @end table
16413
16414 @ifclear vms
16415 @noindent
16416 The @option{-c1} and @option{-c2} switches are incompatible.
16417 The @option{-c3} and @option{-c4} switches are compatible with each other and
16418 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16419 the other comment formatting switches.
16420
16421 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16422 @end ifclear
16423
16424 @ifset vms
16425 @noindent
16426 For the @option{/COMMENTS_LAYOUT} qualifier:
16427 @itemize @bullet
16428 @item
16429 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16430 @item
16431 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16432 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16433 @end itemize
16434
16435 @noindent
16436 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16437 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16438 @end ifset
16439
16440 @node General Text Layout Control
16441 @subsection General Text Layout Control
16442
16443 @noindent
16444 These switches allow control over line length and indentation.
16445
16446 @table @option
16447 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16448 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16449 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16450
16451 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16452 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16453 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16454
16455 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16456 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16457 Indentation level for continuation lines (relative to the line being
16458 continued), @var{nnn} from 1@dots{}9.
16459 The default
16460 value is one less then the (normal) indentation level, unless the
16461 indentation is set to 1 (in which case the default value for continuation
16462 line indentation is also 1)
16463 @end table
16464
16465 @node Other Formatting Options
16466 @subsection Other Formatting Options
16467
16468 @noindent
16469 These switches control the inclusion of missing end/exit labels, and
16470 the indentation level in @b{case} statements.
16471
16472 @table @option
16473 @item ^-e^/NO_MISSED_LABELS^
16474 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16475 Do not insert missing end/exit labels. An end label is the name of
16476 a construct that may optionally be repeated at the end of the
16477 construct's declaration;
16478 e.g., the names of packages, subprograms, and tasks.
16479 An exit label is the name of a loop that may appear as target
16480 of an exit statement within the loop.
16481 By default, @command{gnatpp} inserts these end/exit labels when
16482 they are absent from the original source. This option suppresses such
16483 insertion, so that the formatted source reflects the original.
16484
16485 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16486 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16487 Insert a Form Feed character after a pragma Page.
16488
16489 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16490 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16491 Do not use an additional indentation level for @b{case} alternatives
16492 and variants if there are @var{nnn} or more (the default
16493 value is 10).
16494 If @var{nnn} is 0, an additional indentation level is
16495 used for @b{case} alternatives and variants regardless of their number.
16496 @end table
16497
16498 @node Setting the Source Search Path
16499 @subsection Setting the Source Search Path
16500
16501 @noindent
16502 To define the search path for the input source file, @command{gnatpp}
16503 uses the same switches as the GNAT compiler, with the same effects.
16504
16505 @table @option
16506 @item ^-I^/SEARCH=^@var{dir}
16507 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16508 The same as the corresponding gcc switch
16509
16510 @item ^-I-^/NOCURRENT_DIRECTORY^
16511 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16512 The same as the corresponding gcc switch
16513
16514 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16515 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16516 The same as the corresponding gcc switch
16517
16518 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16519 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16520 The same as the corresponding gcc switch
16521
16522 @end table
16523
16524 @node Output File Control
16525 @subsection Output File Control
16526
16527 @noindent
16528 By default the output is sent to the file whose name is obtained by appending
16529 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16530 (if the file with this name already exists, it is unconditionally overwritten).
16531 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16532 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16533 as output file.
16534 The output may be redirected by the following switches:
16535
16536 @table @option
16537 @item ^-pipe^/STANDARD_OUTPUT^
16538 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16539 Send the output to @code{Standard_Output}
16540
16541 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16542 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16543 Write the output into @var{output_file}.
16544 If @var{output_file} already exists, @command{gnatpp} terminates without
16545 reading or processing the input file.
16546
16547 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16548 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16549 Write the output into @var{output_file}, overwriting the existing file
16550 (if one is present).
16551
16552 @item ^-r^/REPLACE^
16553 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16554 Replace the input source file with the reformatted output, and copy the
16555 original input source into the file whose name is obtained by appending the
16556 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16557 If a file with this name already exists, @command{gnatpp} terminates without
16558 reading or processing the input file.
16559
16560 @item ^-rf^/OVERRIDING_REPLACE^
16561 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16562 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16563 already exists, it is overwritten.
16564
16565 @item ^-rnb^/REPLACE_NO_BACKUP^
16566 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16567 Replace the input source file with the reformatted output without
16568 creating any backup copy of the input source.
16569
16570 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16571 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16572 Specifies the format of the reformatted output file. The @var{xxx}
16573 ^string specified with the switch^option^ may be either
16574 @itemize @bullet
16575 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16576 @item ``@option{^crlf^CRLF^}''
16577 the same as @option{^crlf^CRLF^}
16578 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16579 @item ``@option{^lf^LF^}''
16580 the same as @option{^unix^UNIX^}
16581 @end itemize
16582
16583 @item ^-W^/RESULT_ENCODING=^@var{e}
16584 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16585 Specify the wide character encoding method used to write the code in the
16586 result file
16587 @var{e} is one of the following:
16588
16589 @itemize @bullet
16590
16591 @item ^h^HEX^
16592 Hex encoding
16593
16594 @item ^u^UPPER^
16595 Upper half encoding
16596
16597 @item ^s^SHIFT_JIS^
16598 Shift/JIS encoding
16599
16600 @item ^e^EUC^
16601 EUC encoding
16602
16603 @item ^8^UTF8^
16604 UTF-8 encoding
16605
16606 @item ^b^BRACKETS^
16607 Brackets encoding (default value)
16608 @end itemize
16609
16610 @end table
16611
16612 @noindent
16613 Options @option{^-pipe^/STANDARD_OUTPUT^},
16614 @option{^-o^/OUTPUT^} and
16615 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16616 contains only one file to reformat.
16617 Option
16618 @option{^--eol^/END_OF_LINE^}
16619 and
16620 @option{^-W^/RESULT_ENCODING^}
16621 cannot be used together
16622 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16623
16624 @node Other gnatpp Switches
16625 @subsection Other @code{gnatpp} Switches
16626
16627 @noindent
16628 The additional @command{gnatpp} switches are defined in this subsection.
16629
16630 @table @option
16631 @item ^-files @var{filename}^/FILES=@var{filename}^
16632 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16633 Take the argument source files from the specified file. This file should be an
16634 ordinary text file containing file names separated by spaces or
16635 line breaks. You can use this switch more than once in the same call to
16636 @command{gnatpp}. You also can combine this switch with an explicit list of
16637 files.
16638
16639 @item ^-v^/VERBOSE^
16640 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16641 Verbose mode;
16642 @command{gnatpp} generates version information and then
16643 a trace of the actions it takes to produce or obtain the ASIS tree.
16644
16645 @item ^-w^/WARNINGS^
16646 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16647 Warning mode;
16648 @command{gnatpp} generates a warning whenever it cannot provide
16649 a required layout in the result source.
16650 @end table
16651
16652 @node Formatting Rules
16653 @section Formatting Rules
16654
16655 @noindent
16656 The following subsections show how @command{gnatpp} treats ``white space'',
16657 comments, program layout, and name casing.
16658 They provide the detailed descriptions of the switches shown above.
16659
16660 @menu
16661 * White Space and Empty Lines::
16662 * Formatting Comments::
16663 * Construct Layout::
16664 * Name Casing::
16665 @end menu
16666
16667 @node White Space and Empty Lines
16668 @subsection White Space and Empty Lines
16669
16670 @noindent
16671 @command{gnatpp} does not have an option to control space characters.
16672 It will add or remove spaces according to the style illustrated by the
16673 examples in the @cite{Ada Reference Manual}.
16674
16675 The only format effectors
16676 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16677 that will appear in the output file are platform-specific line breaks,
16678 and also format effectors within (but not at the end of) comments.
16679 In particular, each horizontal tab character that is not inside
16680 a comment will be treated as a space and thus will appear in the
16681 output file as zero or more spaces depending on
16682 the reformatting of the line in which it appears.
16683 The only exception is a Form Feed character, which is inserted after a
16684 pragma @code{Page} when @option{-ff} is set.
16685
16686 The output file will contain no lines with trailing ``white space'' (spaces,
16687 format effectors).
16688
16689 Empty lines in the original source are preserved
16690 only if they separate declarations or statements.
16691 In such contexts, a
16692 sequence of two or more empty lines is replaced by exactly one empty line.
16693 Note that a blank line will be removed if it separates two ``comment blocks''
16694 (a comment block is a sequence of whole-line comments).
16695 In order to preserve a visual separation between comment blocks, use an
16696 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16697 Likewise, if for some reason you wish to have a sequence of empty lines,
16698 use a sequence of empty comments instead.
16699
16700 @node Formatting Comments
16701 @subsection Formatting Comments
16702
16703 @noindent
16704 Comments in Ada code are of two kinds:
16705 @itemize @bullet
16706 @item
16707 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16708 ``white space'') on a line
16709
16710 @item
16711 an @emph{end-of-line comment}, which follows some other Ada lexical element
16712 on the same line.
16713 @end itemize
16714
16715 @noindent
16716 The indentation of a whole-line comment is that of either
16717 the preceding or following line in
16718 the formatted source, depending on switch settings as will be described below.
16719
16720 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16721 between the end of the preceding Ada lexical element and the beginning
16722 of the comment as appear in the original source,
16723 unless either the comment has to be split to
16724 satisfy the line length limitation, or else the next line contains a
16725 whole line comment that is considered a continuation of this end-of-line
16726 comment (because it starts at the same position).
16727 In the latter two
16728 cases, the start of the end-of-line comment is moved right to the nearest
16729 multiple of the indentation level.
16730 This may result in a ``line overflow'' (the right-shifted comment extending
16731 beyond the maximum line length), in which case the comment is split as
16732 described below.
16733
16734 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16735 (GNAT-style comment line indentation)
16736 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16737 (reference-manual comment line indentation).
16738 With reference-manual style, a whole-line comment is indented as if it
16739 were a declaration or statement at the same place
16740 (i.e., according to the indentation of the preceding line(s)).
16741 With GNAT style, a whole-line comment that is immediately followed by an
16742 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16743 word @b{begin}, is indented based on the construct that follows it.
16744
16745 For example:
16746 @smallexample @c ada
16747 @cartouche
16748 if A then
16749     null;
16750        -- some comment
16751 else
16752    null;
16753 end if;
16754 @end cartouche
16755 @end smallexample
16756
16757 @noindent
16758 Reference-manual indentation produces:
16759
16760 @smallexample @c ada
16761 @cartouche
16762 if A then
16763    null;
16764    --  some comment
16765 else
16766    null;
16767 end if;
16768 @end cartouche
16769 @end smallexample
16770
16771 @noindent
16772 while GNAT-style indentation produces:
16773
16774 @smallexample @c ada
16775 @cartouche
16776 if A then
16777    null;
16778 --  some comment
16779 else
16780    null;
16781 end if;
16782 @end cartouche
16783 @end smallexample
16784
16785 @noindent
16786 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16787 (GNAT style comment beginning) has the following
16788 effect:
16789
16790 @itemize @bullet
16791 @item
16792 For each whole-line comment that does not end with two hyphens,
16793 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16794 to ensure that there are at least two spaces between these hyphens and the
16795 first non-blank character of the comment.
16796 @end itemize
16797
16798 @noindent
16799 For an end-of-line comment, if in the original source the next line is a
16800 whole-line comment that starts at the same position
16801 as the end-of-line comment,
16802 then the whole-line comment (and all whole-line comments
16803 that follow it and that start at the same position)
16804 will start at this position in the output file.
16805
16806 @noindent
16807 That is, if in the original source we have:
16808
16809 @smallexample @c ada
16810 @cartouche
16811 begin
16812 A := B + C;            --  B must be in the range Low1..High1
16813                        --  C must be in the range Low2..High2
16814              --B+C will be in the range Low1+Low2..High1+High2
16815 X := X + 1;
16816 @end cartouche
16817 @end smallexample
16818
16819 @noindent
16820 Then in the formatted source we get
16821
16822 @smallexample @c ada
16823 @cartouche
16824 begin
16825    A := B + C;            --  B must be in the range Low1..High1
16826                           --  C must be in the range Low2..High2
16827    --  B+C will be in the range Low1+Low2..High1+High2
16828    X := X + 1;
16829 @end cartouche
16830 @end smallexample
16831
16832 @noindent
16833 A comment that exceeds the line length limit will be split.
16834 Unless switch
16835 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16836 the line belongs to a reformattable block, splitting the line generates a
16837 @command{gnatpp} warning.
16838 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16839 comments may be reformatted in typical
16840 word processor style (that is, moving words between lines and putting as
16841 many words in a line as possible).
16842
16843 @noindent
16844 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16845 that has a special format (that is, a character that is neither a letter nor digit
16846 not white space nor line break immediately following the leading @code{--} of
16847 the comment) should be without any change moved from the argument source
16848 into reformatted source. This switch allows to preserve comments that are used
16849 as a special marks in the code (e.g.@: SPARK annotation).
16850
16851 @node Construct Layout
16852 @subsection Construct Layout
16853
16854 @noindent
16855 In several cases the suggested layout in the Ada Reference Manual includes
16856 an extra level of indentation that many programmers prefer to avoid. The
16857 affected cases include:
16858
16859 @itemize @bullet
16860
16861 @item Record type declaration (RM 3.8)
16862
16863 @item Record representation clause (RM 13.5.1)
16864
16865 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16866
16867 @item Block statement in case if a block has a statement identifier (RM 5.6)
16868 @end itemize
16869
16870 @noindent
16871 In compact mode (when GNAT style layout or compact layout is set),
16872 the pretty printer uses one level of indentation instead
16873 of two. This is achieved in the record definition and record representation
16874 clause cases by putting the @code{record} keyword on the same line as the
16875 start of the declaration or representation clause, and in the block and loop
16876 case by putting the block or loop header on the same line as the statement
16877 identifier.
16878
16879 @noindent
16880 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16881 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16882 layout on the one hand, and uncompact layout
16883 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16884 can be illustrated by the following examples:
16885
16886 @iftex
16887 @cartouche
16888 @multitable @columnfractions .5 .5
16889 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16890
16891 @item
16892 @smallexample @c ada
16893 type q is record
16894    a : integer;
16895    b : integer;
16896 end record;
16897 @end smallexample
16898 @tab
16899 @smallexample @c ada
16900 type q is
16901    record
16902       a : integer;
16903       b : integer;
16904    end record;
16905 @end smallexample
16906
16907 @item
16908 @smallexample @c ada
16909 for q use record
16910    a at 0 range  0 .. 31;
16911    b at 4 range  0 .. 31;
16912 end record;
16913 @end smallexample
16914 @tab
16915 @smallexample @c ada
16916 for q use
16917    record
16918       a at 0 range  0 .. 31;
16919       b at 4 range  0 .. 31;
16920    end record;
16921 @end smallexample
16922
16923 @item
16924 @smallexample @c ada
16925 Block : declare
16926    A : Integer := 3;
16927 begin
16928    Proc (A, A);
16929 end Block;
16930 @end smallexample
16931 @tab
16932 @smallexample @c ada
16933 Block :
16934    declare
16935       A : Integer := 3;
16936    begin
16937       Proc (A, A);
16938    end Block;
16939 @end smallexample
16940
16941 @item
16942 @smallexample @c ada
16943 Clear : for J in 1 .. 10 loop
16944    A (J) := 0;
16945 end loop Clear;
16946 @end smallexample
16947 @tab
16948 @smallexample @c ada
16949 Clear :
16950    for J in 1 .. 10 loop
16951       A (J) := 0;
16952    end loop Clear;
16953 @end smallexample
16954 @end multitable
16955 @end cartouche
16956 @end iftex
16957
16958 @ifnottex
16959 @smallexample
16960 @cartouche
16961 GNAT style, compact layout              Uncompact layout
16962
16963 type q is record                        type q is
16964    a : integer;                            record
16965    b : integer;                               a : integer;
16966 end record;                                   b : integer;
16967                                            end record;
16968
16969 for q use record                        for q use
16970    a at 0 range  0 .. 31;                  record
16971    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16972 end record;                                   b at 4 range  0 .. 31;
16973                                            end record;
16974
16975 Block : declare                         Block :
16976    A : Integer := 3;                       declare
16977 begin                                         A : Integer := 3;
16978    Proc (A, A);                            begin
16979 end Block;                                    Proc (A, A);
16980                                            end Block;
16981
16982 Clear : for J in 1 .. 10 loop           Clear :
16983    A (J) := 0;                             for J in 1 .. 10 loop
16984 end loop Clear;                               A (J) := 0;
16985                                            end loop Clear;
16986 @end cartouche
16987 @end smallexample
16988 @end ifnottex
16989
16990 @noindent
16991 A further difference between GNAT style layout and compact layout is that
16992 GNAT style layout inserts empty lines as separation for
16993 compound statements, return statements and bodies.
16994
16995 Note that the layout specified by
16996 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16997 for named block and loop statements overrides the layout defined by these
16998 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16999 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
17000 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
17001
17002 @node Name Casing
17003 @subsection Name Casing
17004
17005 @noindent
17006 @command{gnatpp} always converts the usage occurrence of a (simple) name to
17007 the same casing as the corresponding defining identifier.
17008
17009 You control the casing for defining occurrences via the
17010 @option{^-n^/NAME_CASING^} switch.
17011 @ifclear vms
17012 With @option{-nD} (``as declared'', which is the default),
17013 @end ifclear
17014 @ifset vms
17015 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
17016 @end ifset
17017 defining occurrences appear exactly as in the source file
17018 where they are declared.
17019 The other ^values for this switch^options for this qualifier^ ---
17020 @option{^-nU^UPPER_CASE^},
17021 @option{^-nL^LOWER_CASE^},
17022 @option{^-nM^MIXED_CASE^} ---
17023 result in
17024 ^upper, lower, or mixed case, respectively^the corresponding casing^.
17025 If @command{gnatpp} changes the casing of a defining
17026 occurrence, it analogously changes the casing of all the
17027 usage occurrences of this name.
17028
17029 If the defining occurrence of a name is not in the source compilation unit
17030 currently being processed by @command{gnatpp}, the casing of each reference to
17031 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
17032 switch (subject to the dictionary file mechanism described below).
17033 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17034 had affected the
17035 casing for the defining occurrence of the name.
17036
17037 Some names may need to be spelled with casing conventions that are not
17038 covered by the upper-, lower-, and mixed-case transformations.
17039 You can arrange correct casing by placing such names in a
17040 @emph{dictionary file},
17041 and then supplying a @option{^-D^/DICTIONARY^} switch.
17042 The casing of names from dictionary files overrides
17043 any @option{^-n^/NAME_CASING^} switch.
17044
17045 To handle the casing of Ada predefined names and the names from GNAT libraries,
17046 @command{gnatpp} assumes a default dictionary file.
17047 The name of each predefined entity is spelled with the same casing as is used
17048 for the entity in the @cite{Ada Reference Manual}.
17049 The name of each entity in the GNAT libraries is spelled with the same casing
17050 as is used in the declaration of that entity.
17051
17052 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17053 default dictionary file.
17054 Instead, the casing for predefined and GNAT-defined names will be established
17055 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17056 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17057 will appear as just shown,
17058 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17059 To ensure that even such names are rendered in uppercase,
17060 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17061 (or else, less conveniently, place these names in upper case in a dictionary
17062 file).
17063
17064 A dictionary file is
17065 a plain text file; each line in this file can be either a blank line
17066 (containing only space characters and ASCII.HT characters), an Ada comment
17067 line, or the specification of exactly one @emph{casing schema}.
17068
17069 A casing schema is a string that has the following syntax:
17070
17071 @smallexample
17072 @cartouche
17073   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17074
17075   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17076 @end cartouche
17077 @end smallexample
17078
17079 @noindent
17080 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17081 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17082
17083 The casing schema string can be followed by white space and/or an Ada-style
17084 comment; any amount of white space is allowed before the string.
17085
17086 If a dictionary file is passed as
17087 @ifclear vms
17088 the value of a @option{-D@var{file}} switch
17089 @end ifclear
17090 @ifset vms
17091 an option to the @option{/DICTIONARY} qualifier
17092 @end ifset
17093 then for every
17094 simple name and every identifier, @command{gnatpp} checks if the dictionary
17095 defines the casing for the name or for some of its parts (the term ``subword''
17096 is used below to denote the part of a name which is delimited by ``_'' or by
17097 the beginning or end of the word and which does not contain any ``_'' inside):
17098
17099 @itemize @bullet
17100 @item
17101 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17102 the casing defined by the dictionary; no subwords are checked for this word
17103
17104 @item
17105 for every subword @command{gnatpp} checks if the dictionary contains the
17106 corresponding string of the form @code{*@var{simple_identifier}*},
17107 and if it does, the casing of this @var{simple_identifier} is used
17108 for this subword
17109
17110 @item
17111 if the whole name does not contain any ``_'' inside, and if for this name
17112 the dictionary contains two entries - one of the form @var{identifier},
17113 and another - of the form *@var{simple_identifier}*, then the first one
17114 is applied to define the casing of this name
17115
17116 @item
17117 if more than one dictionary file is passed as @command{gnatpp} switches, each
17118 dictionary adds new casing exceptions and overrides all the existing casing
17119 exceptions set by the previous dictionaries
17120
17121 @item
17122 when @command{gnatpp} checks if the word or subword is in the dictionary,
17123 this check is not case sensitive
17124 @end itemize
17125
17126 @noindent
17127 For example, suppose we have the following source to reformat:
17128
17129 @smallexample @c ada
17130 @cartouche
17131 procedure test is
17132    name1 : integer := 1;
17133    name4_name3_name2 : integer := 2;
17134    name2_name3_name4 : Boolean;
17135    name1_var : Float;
17136 begin
17137    name2_name3_name4 := name4_name3_name2 > name1;
17138 end;
17139 @end cartouche
17140 @end smallexample
17141
17142 @noindent
17143 And suppose we have two dictionaries:
17144
17145 @smallexample
17146 @cartouche
17147 @i{dict1:}
17148    NAME1
17149    *NaMe3*
17150    *Name1*
17151 @end cartouche
17152
17153 @cartouche
17154 @i{dict2:}
17155   *NAME3*
17156 @end cartouche
17157 @end smallexample
17158
17159 @noindent
17160 If @command{gnatpp} is called with the following switches:
17161
17162 @smallexample
17163 @ifclear vms
17164 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17165 @end ifclear
17166 @ifset vms
17167 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17168 @end ifset
17169 @end smallexample
17170
17171 @noindent
17172 then we will get the following name casing in the @command{gnatpp} output:
17173
17174 @smallexample @c ada
17175 @cartouche
17176 procedure Test is
17177    NAME1             : Integer := 1;
17178    Name4_NAME3_Name2 : Integer := 2;
17179    Name2_NAME3_Name4 : Boolean;
17180    Name1_Var         : Float;
17181 begin
17182    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17183 end Test;
17184 @end cartouche
17185 @end smallexample
17186
17187 @c *********************************
17188 @node The GNAT Metric Tool gnatmetric
17189 @chapter The GNAT Metric Tool @command{gnatmetric}
17190 @findex gnatmetric
17191 @cindex Metric tool
17192
17193 @noindent
17194 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17195 for computing various program metrics.
17196 It takes an Ada source file as input and generates a file containing the
17197 metrics data as output. Various switches control which
17198 metrics are computed and output.
17199
17200 @command{gnatmetric} generates and uses the ASIS
17201 tree for the input source and thus requires the input to be syntactically and
17202 semantically legal.
17203 If this condition is not met, @command{gnatmetric} will generate
17204 an error message; no metric information for this file will be
17205 computed and reported.
17206
17207 If the compilation unit contained in the input source depends semantically
17208 upon units in files located outside the current directory, you have to provide
17209 the source search path when invoking @command{gnatmetric}.
17210 If it depends semantically upon units that are contained
17211 in files with names that do not follow the GNAT file naming rules, you have to
17212 provide the configuration file describing the corresponding naming scheme (see
17213 the description of the @command{gnatmetric} switches below.)
17214 Alternatively, you may use a project file and invoke @command{gnatmetric}
17215 through the @command{gnat} driver.
17216
17217 The @command{gnatmetric} command has the form
17218
17219 @smallexample
17220 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17221 @c Expanding @ovar macro inline (explanation in macro def comments)
17222 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17223 @end smallexample
17224
17225 @noindent
17226 where
17227 @itemize @bullet
17228 @item
17229 @var{switches} specify the metrics to compute and define the destination for
17230 the output
17231
17232 @item
17233 Each @var{filename} is the name (including the extension) of a source
17234 file to process. ``Wildcards'' are allowed, and
17235 the file name may contain path information.
17236 If no @var{filename} is supplied, then the @var{switches} list must contain
17237 at least one
17238 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17239 Including both a @option{-files} switch and one or more
17240 @var{filename} arguments is permitted.
17241
17242 @item
17243 @samp{@var{gcc_switches}} is a list of switches for
17244 @command{gcc}. They will be passed on to all compiler invocations made by
17245 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17246 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17247 and use the @option{-gnatec} switch to set the configuration file.
17248 @end itemize
17249
17250 @menu
17251 * Switches for gnatmetric::
17252 @end menu
17253
17254 @node Switches for gnatmetric
17255 @section Switches for @command{gnatmetric}
17256
17257 @noindent
17258 The following subsections describe the various switches accepted by
17259 @command{gnatmetric}, organized by category.
17260
17261 @menu
17262 * Output Files Control::
17263 * Disable Metrics For Local Units::
17264 * Specifying a set of metrics to compute::
17265 * Other gnatmetric Switches::
17266 * Generate project-wide metrics::
17267 @end menu
17268
17269 @node Output Files Control
17270 @subsection Output File Control
17271 @cindex Output file control in @command{gnatmetric}
17272
17273 @noindent
17274 @command{gnatmetric} has two output formats. It can generate a
17275 textual (human-readable) form, and also XML. By default only textual
17276 output is generated.
17277
17278 When generating the output in textual form, @command{gnatmetric} creates
17279 for each Ada source file a corresponding text file
17280 containing the computed metrics, except for the case when the set of metrics
17281 specified by gnatmetric parameters consists only of metrics that are computed
17282 for the whole set of analyzed sources, but not for each Ada source.
17283 By default, this file is placed in the same directory as where the source
17284 file is located, and its name is obtained
17285 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17286 input file.
17287
17288 All the output information generated in XML format is placed in a single
17289 file. By default this file is placed in the current directory and has the
17290 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17291
17292 Some of the computed metrics are summed over the units passed to
17293 @command{gnatmetric}; for example, the total number of lines of code.
17294 By default this information is sent to @file{stdout}, but a file
17295 can be specified with the @option{-og} switch.
17296
17297 The following switches control the @command{gnatmetric} output:
17298
17299 @table @option
17300 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17301 @item ^-x^/XML^
17302 Generate the XML output
17303
17304 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17305 @item ^-xs^/XSD^
17306 Generate the XML output and the XML schema file that describes the structure
17307 of the XML metric report, this schema is assigned to the XML file. The schema
17308 file has the same name as the XML output file with @file{.xml} suffix replaced
17309 with @file{.xsd}
17310
17311 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17312 @item ^-nt^/NO_TEXT^
17313 Do not generate the output in text form (implies @option{^-x^/XML^})
17314
17315 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17316 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17317 Put text files with detailed metrics into @var{output_dir}
17318
17319 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17320 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17321 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17322 in the name of the output file.
17323
17324 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17325 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17326 Put global metrics into @var{file_name}
17327
17328 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17329 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17330 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17331
17332 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17333 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17334 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17335 output includes the name(s) of the Ada source file(s) from which the metrics
17336 are computed.  By default each name includes the absolute path. The
17337 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17338 to exclude all directory information from the file names that are output.)
17339
17340 @end table
17341
17342 @node Disable Metrics For Local Units
17343 @subsection Disable Metrics For Local Units
17344 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17345
17346 @noindent
17347 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17348 one compilation
17349 unit per one source file. It computes line metrics for the whole source
17350 file, and it also computes syntax
17351 and complexity metrics for the file's outermost unit.
17352
17353 By default, @command{gnatmetric} will also compute all metrics for certain
17354 kinds of locally declared program units:
17355
17356 @itemize @bullet
17357 @item
17358 subprogram (and generic subprogram) bodies;
17359
17360 @item
17361 package (and generic package) specs and bodies;
17362
17363 @item
17364 task object and type specifications and bodies;
17365
17366 @item
17367 protected object and type specifications and bodies.
17368 @end itemize
17369
17370 @noindent
17371 These kinds of entities will be referred to as
17372 @emph{eligible local program units}, or simply @emph{eligible local units},
17373 @cindex Eligible local unit (for @command{gnatmetric})
17374 in the discussion below.
17375
17376 Note that a subprogram declaration, generic instantiation,
17377 or renaming declaration only receives metrics
17378 computation when it appear as the outermost entity
17379 in a source file.
17380
17381 Suppression of metrics computation for eligible local units can be
17382 obtained via the following switch:
17383
17384 @table @option
17385 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17386 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17387 Do not compute detailed metrics for eligible local program units
17388
17389 @end table
17390
17391 @node Specifying a set of metrics to compute
17392 @subsection Specifying a set of metrics to compute
17393
17394 @noindent
17395 By default all the metrics are computed and reported. The switches
17396 described in this subsection allow you to control, on an individual
17397 basis, whether metrics are computed and
17398 reported. If at least one positive metric
17399 switch is specified (that is, a switch that defines that a given
17400 metric or set of metrics is to be computed), then only
17401 explicitly specified metrics are reported.
17402
17403 @menu
17404 * Line Metrics Control::
17405 * Syntax Metrics Control::
17406 * Complexity Metrics Control::
17407 * Object-Oriented Metrics Control::
17408 @end menu
17409
17410 @node Line Metrics Control
17411 @subsubsection Line Metrics Control
17412 @cindex Line metrics control in @command{gnatmetric}
17413
17414 @noindent
17415 For any (legal) source file, and for each of its
17416 eligible local program units, @command{gnatmetric} computes the following
17417 metrics:
17418
17419 @itemize @bullet
17420 @item
17421 the total number of lines;
17422
17423 @item
17424 the total number of code lines (i.e., non-blank lines that are not comments)
17425
17426 @item
17427 the number of comment lines
17428
17429 @item
17430 the number of code lines containing end-of-line comments;
17431
17432 @item
17433 the comment percentage: the ratio between the number of lines that contain
17434 comments and the number of all non-blank lines, expressed as a percentage;
17435
17436 @item
17437 the number of empty lines and lines containing only space characters and/or
17438 format effectors (blank lines)
17439
17440 @item
17441 the average number of code lines in subprogram bodies, task bodies, entry
17442 bodies and statement sequences in package bodies (this metric is only computed
17443 across the whole set of the analyzed units)
17444
17445 @end itemize
17446
17447 @noindent
17448 @command{gnatmetric} sums the values of the line metrics for all the
17449 files being processed and then generates the cumulative results. The tool
17450 also computes for all the files being processed the average number of code
17451 lines in bodies.
17452
17453 You can use the following switches to select the specific line metrics
17454 to be computed and reported.
17455
17456 @table @option
17457 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17458
17459 @ifclear vms
17460 @cindex @option{--no-lines@var{x}}
17461 @end ifclear
17462
17463 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17464 Report all the line metrics
17465
17466 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17467 Do not report any of line metrics
17468
17469 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17470 Report the number of all lines
17471
17472 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17473 Do not report the number of all lines
17474
17475 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17476 Report the number of code lines
17477
17478 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17479 Do not report the number of code lines
17480
17481 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17482 Report the number of comment lines
17483
17484 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17485 Do not report the number of comment lines
17486
17487 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17488 Report the number of code lines containing
17489 end-of-line comments
17490
17491 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17492 Do not report the number of code lines containing
17493 end-of-line comments
17494
17495 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17496 Report the comment percentage in the program text
17497
17498 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17499 Do not report the comment percentage in the program text
17500
17501 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17502 Report the number of blank lines
17503
17504 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17505 Do not report the number of blank lines
17506
17507 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17508 Report the average number of code lines in subprogram bodies, task bodies,
17509 entry bodies and statement sequences in package bodies. The metric is computed
17510 and reported for the whole set of processed Ada sources only.
17511
17512 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17513 Do not report the average number of code lines in subprogram bodies,
17514 task bodies, entry bodies and statement sequences in package bodies.
17515
17516 @end table
17517
17518 @node Syntax Metrics Control
17519 @subsubsection Syntax Metrics Control
17520 @cindex Syntax metrics control in @command{gnatmetric}
17521
17522 @noindent
17523 @command{gnatmetric} computes various syntactic metrics for the
17524 outermost unit and for each eligible local unit:
17525
17526 @table @emph
17527 @item LSLOC (``Logical Source Lines Of Code'')
17528 The total number of declarations and the total number of statements
17529
17530 @item Maximal static nesting level of inner program units
17531 According to
17532 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17533 package, a task unit, a protected unit, a
17534 protected entry, a generic unit, or an explicitly declared subprogram other
17535 than an enumeration literal.''
17536
17537 @item Maximal nesting level of composite syntactic constructs
17538 This corresponds to the notion of the
17539 maximum nesting level in the GNAT built-in style checks
17540 (@pxref{Style Checking})
17541 @end table
17542
17543 @noindent
17544 For the outermost unit in the file, @command{gnatmetric} additionally computes
17545 the following metrics:
17546
17547 @table @emph
17548 @item Public subprograms
17549 This metric is computed for package specs. It is the
17550 number of subprograms and generic subprograms declared in the visible
17551 part (including the visible part of nested packages, protected objects, and
17552 protected types).
17553
17554 @item All subprograms
17555 This metric is computed for bodies and subunits. The
17556 metric is equal to a total number of subprogram bodies in the compilation
17557 unit.
17558 Neither generic instantiations nor renamings-as-a-body nor body stubs
17559 are counted. Any subprogram body is counted, independently of its nesting
17560 level and enclosing constructs. Generic bodies and bodies of protected
17561 subprograms are counted in the same way as ``usual'' subprogram bodies.
17562
17563 @item Public types
17564 This metric is computed for package specs and
17565 generic package declarations. It is the total number of types
17566 that can be referenced from outside this compilation unit, plus the
17567 number of types from all the visible parts of all the visible generic
17568 packages. Generic formal types are not counted.  Only types, not subtypes,
17569 are included.
17570
17571 @noindent
17572 Along with the total number of public types, the following
17573 types are counted and reported separately:
17574
17575 @itemize @bullet
17576 @item
17577 Abstract types
17578
17579 @item
17580 Root tagged types (abstract, non-abstract, private, non-private). Type
17581 extensions are @emph{not} counted
17582
17583 @item
17584 Private types (including private extensions)
17585
17586 @item
17587 Task types
17588
17589 @item
17590 Protected types
17591
17592 @end itemize
17593
17594 @item All types
17595 This metric is computed for any compilation unit. It is equal to the total
17596 number of the declarations of different types given in the compilation unit.
17597 The private and the corresponding full type declaration are counted as one
17598 type declaration. Incomplete type declarations and generic formal types
17599 are not counted.
17600 No distinction is made among different kinds of types (abstract,
17601 private etc.); the total number of types is computed and reported.
17602
17603 @end table
17604
17605 @noindent
17606 By default, all the syntax metrics are computed and reported. You can use the
17607 following switches to select specific syntax metrics.
17608
17609 @table @option
17610
17611 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17612
17613 @ifclear vms
17614 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17615 @end ifclear
17616
17617 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17618 Report all the syntax metrics
17619
17620 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17621 Do not report any of syntax metrics
17622
17623 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17624 Report the total number of declarations
17625
17626 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17627 Do not report the total number of declarations
17628
17629 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17630 Report the total number of statements
17631
17632 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17633 Do not report the total number of statements
17634
17635 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17636 Report the number of public subprograms in a compilation unit
17637
17638 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17639 Do not report the number of public subprograms in a compilation unit
17640
17641 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17642 Report the number of all the subprograms in a compilation unit
17643
17644 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17645 Do not report the number of all the subprograms in a compilation unit
17646
17647 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17648 Report the number of public types in a compilation unit
17649
17650 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17651 Do not report the number of public types in a compilation unit
17652
17653 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17654 Report the number of all the types in a compilation unit
17655
17656 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17657 Do not report the number of all the types in a compilation unit
17658
17659 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17660 Report the maximal program unit nesting level
17661
17662 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17663 Do not report the maximal program unit nesting level
17664
17665 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17666 Report the maximal construct nesting level
17667
17668 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17669 Do not report the maximal construct nesting level
17670
17671 @end table
17672
17673 @node Complexity Metrics Control
17674 @subsubsection Complexity Metrics Control
17675 @cindex Complexity metrics control in @command{gnatmetric}
17676
17677 @noindent
17678 For a program unit that is an executable body (a subprogram body (including
17679 generic bodies), task body, entry body or a package body containing
17680 its own statement sequence) @command{gnatmetric} computes the following
17681 complexity metrics:
17682
17683 @itemize @bullet
17684 @item
17685 McCabe cyclomatic complexity;
17686
17687 @item
17688 McCabe essential complexity;
17689
17690 @item
17691 maximal loop nesting level
17692
17693 @end itemize
17694
17695 @noindent
17696 The McCabe complexity metrics are defined
17697 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17698
17699 According to McCabe, both control statements and short-circuit control forms
17700 should be taken into account when computing cyclomatic complexity. For each
17701 body, we compute three metric values:
17702
17703 @itemize @bullet
17704 @item
17705 the complexity introduced by control
17706 statements only, without taking into account short-circuit forms,
17707
17708 @item
17709 the complexity introduced by short-circuit control forms only, and
17710
17711 @item
17712 the total
17713 cyclomatic complexity, which is the sum of these two values.
17714 @end itemize
17715
17716 @noindent
17717 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17718 the code in the exception handlers and in all the nested program units.
17719
17720 By default, all the complexity metrics are computed and reported.
17721 For more fine-grained control you can use
17722 the following switches:
17723
17724 @table @option
17725 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17726
17727 @ifclear vms
17728 @cindex @option{--no-complexity@var{x}}
17729 @end ifclear
17730
17731 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17732 Report all the complexity metrics
17733
17734 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17735 Do not report any of complexity metrics
17736
17737 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17738 Report the McCabe Cyclomatic Complexity
17739
17740 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17741 Do not report the McCabe Cyclomatic Complexity
17742
17743 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17744 Report the Essential Complexity
17745
17746 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17747 Do not report the Essential Complexity
17748
17749 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17750 Report maximal loop nesting level
17751
17752 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17753 Do not report maximal loop nesting level
17754
17755 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17756 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17757 task bodies, entry bodies and statement sequences in package bodies.
17758 The metric is computed and reported for whole set of processed Ada sources
17759 only.
17760
17761 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17762 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17763 bodies, task bodies, entry bodies and statement sequences in package bodies
17764
17765 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17766 @item ^-ne^/NO_EXITS_AS_GOTOS^
17767 Do not consider @code{exit} statements as @code{goto}s when
17768 computing Essential Complexity
17769
17770 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17771 Report the extra exit points for subprogram bodies. As an exit point, this
17772 metric counts @code{return} statements and raise statements in case when the
17773 raised exception is not handled in the same body. In case of a function this
17774 metric subtracts 1 from the number of exit points, because a function body
17775 must contain at least one @code{return} statement.
17776
17777 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17778 Do not report the extra exit points for subprogram bodies
17779 @end table
17780
17781
17782 @node Object-Oriented Metrics Control
17783 @subsubsection Object-Oriented Metrics Control
17784 @cindex Object-Oriented metrics control in @command{gnatmetric}
17785
17786 @noindent
17787 @cindex Coupling metrics (in in @command{gnatmetric})
17788 Coupling metrics are object-oriented metrics that measure the
17789 dependencies between a given class (or a group of classes) and the
17790 ``external world'' (that is, the other classes in the program). In this
17791 subsection the term ``class'' is used in its
17792 traditional object-oriented programming sense
17793 (an instantiable module that contains data and/or method members).
17794 A @emph{category} (of classes)
17795 is a group of closely related classes that are reused and/or
17796 modified together.
17797
17798 A class @code{K}'s @emph{efferent coupling} is the number of classes
17799 that @code{K} depends upon.
17800 A category's efferent coupling is the number of classes outside the
17801 category that the classes inside the category depend upon.
17802
17803 A class @code{K}'s @emph{afferent coupling} is the number of classes
17804 that depend upon @code{K}.
17805 A category's afferent coupling is the number of classes outside the
17806 category that depend on classes belonging to the category.
17807
17808 Ada's implementation of the object-oriented paradigm does not use the
17809 traditional class notion, so the definition of the coupling
17810 metrics for Ada maps the class and class category notions
17811 onto Ada constructs.
17812
17813 For the coupling metrics, several kinds of modules -- a library package,
17814 a library generic package, and a library generic package instantiation --
17815 that define a tagged type or an interface type are
17816 considered to be a class. A category consists of a library package (or
17817 a library generic package) that defines a tagged or an interface type,
17818 together with all its descendant (generic) packages that define tagged
17819 or interface types. For any package counted as a class,
17820 its body and subunits (if any) are considered
17821 together with its spec when counting the dependencies, and coupling
17822 metrics are reported for spec units only. For dependencies
17823 between classes, the Ada semantic dependencies are considered.
17824 For coupling metrics, only dependencies on units that are considered as
17825 classes, are considered.
17826
17827 When computing coupling metrics, @command{gnatmetric} counts only
17828 dependencies between units that are arguments of the gnatmetric call.
17829 Coupling metrics are program-wide (or project-wide) metrics, so to
17830 get a valid result, you should call @command{gnatmetric} for
17831 the whole set of sources that make up your program. It can be done
17832 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17833 option (see See @ref{The GNAT Driver and Project Files} for details.
17834
17835 By default, all the coupling metrics are disabled. You can use the following
17836 switches to specify the coupling metrics to be computed and reported:
17837
17838 @table @option
17839
17840 @ifclear vms
17841 @cindex @option{--package@var{x}} (@command{gnatmetric})
17842 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17843 @cindex @option{--category@var{x}} (@command{gnatmetric})
17844 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17845 @end ifclear
17846
17847 @ifset vms
17848 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17849 @end ifset
17850
17851 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17852 Report all the coupling metrics
17853
17854 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17855 Do not report any of  metrics
17856
17857 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17858 Report package efferent coupling
17859
17860 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17861 Do not report package efferent coupling
17862
17863 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17864 Report package afferent coupling
17865
17866 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17867 Do not report package afferent coupling
17868
17869 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17870 Report category efferent coupling
17871
17872 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17873 Do not report category efferent coupling
17874
17875 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17876 Report category afferent coupling
17877
17878 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17879 Do not report category afferent coupling
17880
17881 @end table
17882
17883 @node Other gnatmetric Switches
17884 @subsection Other @code{gnatmetric} Switches
17885
17886 @noindent
17887 Additional @command{gnatmetric} switches are as follows:
17888
17889 @table @option
17890 @item ^-files @var{filename}^/FILES=@var{filename}^
17891 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17892 Take the argument source files from the specified file. This file should be an
17893 ordinary text file containing file names separated by spaces or
17894 line breaks. You can use this switch more than once in the same call to
17895 @command{gnatmetric}. You also can combine this switch with
17896 an explicit list of files.
17897
17898 @item ^-v^/VERBOSE^
17899 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17900 Verbose mode;
17901 @command{gnatmetric} generates version information and then
17902 a trace of sources being processed.
17903
17904 @item ^-dv^/DEBUG_OUTPUT^
17905 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17906 Debug mode;
17907 @command{gnatmetric} generates various messages useful to understand what
17908 happens during the metrics computation
17909
17910 @item ^-q^/QUIET^
17911 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17912 Quiet mode.
17913 @end table
17914
17915 @node Generate project-wide metrics
17916 @subsection Generate project-wide metrics
17917
17918 In order to compute metrics on all units of a given project, you can use
17919 the @command{gnat} driver along with the @option{-P} option:
17920 @smallexample
17921    gnat metric -Pproj
17922 @end smallexample
17923
17924 @noindent
17925 If the project @code{proj} depends upon other projects, you can compute
17926 the metrics on the project closure using the @option{-U} option:
17927 @smallexample
17928    gnat metric -Pproj -U
17929 @end smallexample
17930
17931 @noindent
17932 Finally, if not all the units are relevant to a particular main
17933 program in the project closure, you can generate metrics for the set
17934 of units needed to create a given main program (unit closure) using
17935 the @option{-U} option followed by the name of the main unit:
17936 @smallexample
17937    gnat metric -Pproj -U main
17938 @end smallexample
17939
17940
17941 @c ***********************************
17942 @node File Name Krunching Using gnatkr
17943 @chapter File Name Krunching Using @code{gnatkr}
17944 @findex gnatkr
17945
17946 @noindent
17947 This chapter discusses the method used by the compiler to shorten
17948 the default file names chosen for Ada units so that they do not
17949 exceed the maximum length permitted. It also describes the
17950 @code{gnatkr} utility that can be used to determine the result of
17951 applying this shortening.
17952 @menu
17953 * About gnatkr::
17954 * Using gnatkr::
17955 * Krunching Method::
17956 * Examples of gnatkr Usage::
17957 @end menu
17958
17959 @node About gnatkr
17960 @section About @code{gnatkr}
17961
17962 @noindent
17963 The default file naming rule in GNAT
17964 is that the file name must be derived from
17965 the unit name. The exact default rule is as follows:
17966 @itemize @bullet
17967 @item
17968 Take the unit name and replace all dots by hyphens.
17969 @item
17970 If such a replacement occurs in the
17971 second character position of a name, and the first character is
17972 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17973 then replace the dot by the character
17974 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17975 instead of a minus.
17976 @end itemize
17977 The reason for this exception is to avoid clashes
17978 with the standard names for children of System, Ada, Interfaces,
17979 and GNAT, which use the prefixes
17980 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17981 respectively.
17982
17983 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17984 switch of the compiler activates a ``krunching''
17985 circuit that limits file names to nn characters (where nn is a decimal
17986 integer). For example, using OpenVMS,
17987 where the maximum file name length is
17988 39, the value of nn is usually set to 39, but if you want to generate
17989 a set of files that would be usable if ported to a system with some
17990 different maximum file length, then a different value can be specified.
17991 The default value of 39 for OpenVMS need not be specified.
17992
17993 The @code{gnatkr} utility can be used to determine the krunched name for
17994 a given file, when krunched to a specified maximum length.
17995
17996 @node Using gnatkr
17997 @section Using @code{gnatkr}
17998
17999 @noindent
18000 The @code{gnatkr} command has the form
18001
18002 @ifclear vms
18003 @smallexample
18004 @c $ gnatkr @var{name} @ovar{length}
18005 @c Expanding @ovar macro inline (explanation in macro def comments)
18006 $ gnatkr @var{name} @r{[}@var{length}@r{]}
18007 @end smallexample
18008 @end ifclear
18009
18010 @ifset vms
18011 @smallexample
18012 $ gnatkr @var{name} /COUNT=nn
18013 @end smallexample
18014 @end ifset
18015
18016 @noindent
18017 @var{name} is the uncrunched file name, derived from the name of the unit
18018 in the standard manner described in the previous section (i.e., in particular
18019 all dots are replaced by hyphens). The file name may or may not have an
18020 extension (defined as a suffix of the form period followed by arbitrary
18021 characters other than period). If an extension is present then it will
18022 be preserved in the output. For example, when krunching @file{hellofile.ads}
18023 to eight characters, the result will be hellofil.ads.
18024
18025 Note: for compatibility with previous versions of @code{gnatkr} dots may
18026 appear in the name instead of hyphens, but the last dot will always be
18027 taken as the start of an extension. So if @code{gnatkr} is given an argument
18028 such as @file{Hello.World.adb} it will be treated exactly as if the first
18029 period had been a hyphen, and for example krunching to eight characters
18030 gives the result @file{hellworl.adb}.
18031
18032 Note that the result is always all lower case (except on OpenVMS where it is
18033 all upper case). Characters of the other case are folded as required.
18034
18035 @var{length} represents the length of the krunched name. The default
18036 when no argument is given is ^8^39^ characters. A length of zero stands for
18037 unlimited, in other words do not chop except for system files where the
18038 implied crunching length is always eight characters.
18039
18040 @noindent
18041 The output is the krunched name. The output has an extension only if the
18042 original argument was a file name with an extension.
18043
18044 @node Krunching Method
18045 @section Krunching Method
18046
18047 @noindent
18048 The initial file name is determined by the name of the unit that the file
18049 contains. The name is formed by taking the full expanded name of the
18050 unit and replacing the separating dots with hyphens and
18051 using ^lowercase^uppercase^
18052 for all letters, except that a hyphen in the second character position is
18053 replaced by a ^tilde^dollar sign^ if the first character is
18054 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18055 The extension is @code{.ads} for a
18056 spec and @code{.adb} for a body.
18057 Krunching does not affect the extension, but the file name is shortened to
18058 the specified length by following these rules:
18059
18060 @itemize @bullet
18061 @item
18062 The name is divided into segments separated by hyphens, tildes or
18063 underscores and all hyphens, tildes, and underscores are
18064 eliminated. If this leaves the name short enough, we are done.
18065
18066 @item
18067 If the name is too long, the longest segment is located (left-most
18068 if there are two of equal length), and shortened by dropping
18069 its last character. This is repeated until the name is short enough.
18070
18071 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18072 to fit the name into 8 characters as required by some operating systems.
18073
18074 @smallexample
18075 our-strings-wide_fixed 22
18076 our strings wide fixed 19
18077 our string  wide fixed 18
18078 our strin   wide fixed 17
18079 our stri    wide fixed 16
18080 our stri    wide fixe  15
18081 our str     wide fixe  14
18082 our str     wid  fixe  13
18083 our str     wid  fix   12
18084 ou  str     wid  fix   11
18085 ou  st      wid  fix   10
18086 ou  st      wi   fix   9
18087 ou  st      wi   fi    8
18088 Final file name: oustwifi.adb
18089 @end smallexample
18090
18091 @item
18092 The file names for all predefined units are always krunched to eight
18093 characters. The krunching of these predefined units uses the following
18094 special prefix replacements:
18095
18096 @table @file
18097 @item ada-
18098 replaced by @file{^a^A^-}
18099
18100 @item gnat-
18101 replaced by @file{^g^G^-}
18102
18103 @item interfaces-
18104 replaced by @file{^i^I^-}
18105
18106 @item system-
18107 replaced by @file{^s^S^-}
18108 @end table
18109
18110 These system files have a hyphen in the second character position. That
18111 is why normal user files replace such a character with a
18112 ^tilde^dollar sign^, to
18113 avoid confusion with system file names.
18114
18115 As an example of this special rule, consider
18116 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18117
18118 @smallexample
18119 ada-strings-wide_fixed 22
18120 a-  strings wide fixed 18
18121 a-  string  wide fixed 17
18122 a-  strin   wide fixed 16
18123 a-  stri    wide fixed 15
18124 a-  stri    wide fixe  14
18125 a-  str     wide fixe  13
18126 a-  str     wid  fixe  12
18127 a-  str     wid  fix   11
18128 a-  st      wid  fix   10
18129 a-  st      wi   fix   9
18130 a-  st      wi   fi    8
18131 Final file name: a-stwifi.adb
18132 @end smallexample
18133 @end itemize
18134
18135 Of course no file shortening algorithm can guarantee uniqueness over all
18136 possible unit names, and if file name krunching is used then it is your
18137 responsibility to ensure that no name clashes occur. The utility
18138 program @code{gnatkr} is supplied for conveniently determining the
18139 krunched name of a file.
18140
18141 @node Examples of gnatkr Usage
18142 @section Examples of @code{gnatkr} Usage
18143
18144 @smallexample
18145 @iftex
18146 @leftskip=0cm
18147 @end iftex
18148 @ifclear vms
18149 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18150 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18151 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18152 $ gnatkr grandparent-parent-child     --> grparchi
18153 @end ifclear
18154 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18155 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18156 @end smallexample
18157
18158 @node Preprocessing Using gnatprep
18159 @chapter Preprocessing Using @code{gnatprep}
18160 @findex gnatprep
18161
18162 @noindent
18163 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18164 preprocessing.
18165 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18166 special GNAT features.
18167 For further discussion of conditional compilation in general, see
18168 @ref{Conditional Compilation}.
18169
18170 @menu
18171 * Preprocessing Symbols::
18172 * Using gnatprep::
18173 * Switches for gnatprep::
18174 * Form of Definitions File::
18175 * Form of Input Text for gnatprep::
18176 @end menu
18177
18178 @node Preprocessing Symbols
18179 @section Preprocessing Symbols
18180
18181 @noindent
18182 Preprocessing symbols are defined in definition files and referred to in
18183 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18184 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18185 all characters need to be in the ASCII set (no accented letters).
18186
18187 @node Using gnatprep
18188 @section Using @code{gnatprep}
18189
18190 @noindent
18191 To call @code{gnatprep} use
18192
18193 @smallexample
18194 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18195 @c Expanding @ovar macro inline (explanation in macro def comments)
18196 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
18197 @end smallexample
18198
18199 @noindent
18200 where
18201 @table @var
18202 @item switches
18203 is an optional sequence of switches as described in the next section.
18204
18205 @item infile
18206 is the full name of the input file, which is an Ada source
18207 file containing preprocessor directives.
18208
18209 @item outfile
18210 is the full name of the output file, which is an Ada source
18211 in standard Ada form. When used with GNAT, this file name will
18212 normally have an ads or adb suffix.
18213
18214 @item deffile
18215 is the full name of a text file containing definitions of
18216 preprocessing symbols to be referenced by the preprocessor. This argument is
18217 optional, and can be replaced by the use of the @option{-D} switch.
18218
18219 @end table
18220
18221 @node Switches for gnatprep
18222 @section Switches for @code{gnatprep}
18223
18224 @table @option
18225 @c !sort!
18226
18227 @item ^-b^/BLANK_LINES^
18228 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18229 Causes both preprocessor lines and the lines deleted by
18230 preprocessing to be replaced by blank lines in the output source file,
18231 preserving line numbers in the output file.
18232
18233 @item ^-c^/COMMENTS^
18234 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18235 Causes both preprocessor lines and the lines deleted
18236 by preprocessing to be retained in the output source as comments marked
18237 with the special string @code{"--! "}. This option will result in line numbers
18238 being preserved in the output file.
18239
18240 @item ^-C^/REPLACE_IN_COMMENTS^
18241 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18242 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18243 If this option is specified, then comments are scanned and any $symbol
18244 substitutions performed as in program text. This is particularly useful
18245 when structured comments are used (e.g., when writing programs in the
18246 SPARK dialect of Ada). Note that this switch is not available when
18247 doing integrated preprocessing (it would be useless in this context
18248 since comments are ignored by the compiler in any case).
18249
18250 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18251 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18252 Defines a new preprocessing symbol, associated with value. If no value is given
18253 on the command line, then symbol is considered to be @code{True}. This switch
18254 can be used in place of a definition file.
18255
18256 @ifset vms
18257 @item /REMOVE
18258 @cindex @option{/REMOVE} (@command{gnatprep})
18259 This is the default setting which causes lines deleted by preprocessing
18260 to be entirely removed from the output file.
18261 @end ifset
18262
18263 @item ^-r^/REFERENCE^
18264 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18265 Causes a @code{Source_Reference} pragma to be generated that
18266 references the original input file, so that error messages will use
18267 the file name of this original file. The use of this switch implies
18268 that preprocessor lines are not to be removed from the file, so its
18269 use will force @option{^-b^/BLANK_LINES^} mode if
18270 @option{^-c^/COMMENTS^}
18271 has not been specified explicitly.
18272
18273 Note that if the file to be preprocessed contains multiple units, then
18274 it will be necessary to @code{gnatchop} the output file from
18275 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18276 in the preprocessed file, it will be respected by
18277 @code{gnatchop ^-r^/REFERENCE^}
18278 so that the final chopped files will correctly refer to the original
18279 input source file for @code{gnatprep}.
18280
18281 @item ^-s^/SYMBOLS^
18282 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18283 Causes a sorted list of symbol names and values to be
18284 listed on the standard output file.
18285
18286 @item ^-u^/UNDEFINED^
18287 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18288 Causes undefined symbols to be treated as having the value FALSE in the context
18289 of a preprocessor test. In the absence of this option, an undefined symbol in
18290 a @code{#if} or @code{#elsif} test will be treated as an error.
18291
18292 @end table
18293
18294 @ifclear vms
18295 @noindent
18296 Note: if neither @option{-b} nor @option{-c} is present,
18297 then preprocessor lines and
18298 deleted lines are completely removed from the output, unless -r is
18299 specified, in which case -b is assumed.
18300 @end ifclear
18301
18302 @node Form of Definitions File
18303 @section Form of Definitions File
18304
18305 @noindent
18306 The definitions file contains lines of the form
18307
18308 @smallexample
18309 symbol := value
18310 @end smallexample
18311
18312 @noindent
18313 where symbol is a preprocessing symbol, and value is one of the following:
18314
18315 @itemize @bullet
18316 @item
18317 Empty, corresponding to a null substitution
18318 @item
18319 A string literal using normal Ada syntax
18320 @item
18321 Any sequence of characters from the set
18322 (letters, digits, period, underline).
18323 @end itemize
18324
18325 @noindent
18326 Comment lines may also appear in the definitions file, starting with
18327 the usual @code{--},
18328 and comments may be added to the definitions lines.
18329
18330 @node Form of Input Text for gnatprep
18331 @section Form of Input Text for @code{gnatprep}
18332
18333 @noindent
18334 The input text may contain preprocessor conditional inclusion lines,
18335 as well as general symbol substitution sequences.
18336
18337 The preprocessor conditional inclusion commands have the form
18338
18339 @smallexample
18340 @group
18341 @cartouche
18342 #if @i{expression} @r{[}then@r{]}
18343    lines
18344 #elsif @i{expression} @r{[}then@r{]}
18345    lines
18346 #elsif @i{expression} @r{[}then@r{]}
18347    lines
18348 @dots{}
18349 #else
18350    lines
18351 #end if;
18352 @end cartouche
18353 @end group
18354 @end smallexample
18355
18356 @noindent
18357 In this example, @i{expression} is defined by the following grammar:
18358 @smallexample
18359 @i{expression} ::=  <symbol>
18360 @i{expression} ::=  <symbol> = "<value>"
18361 @i{expression} ::=  <symbol> = <symbol>
18362 @i{expression} ::=  <symbol> 'Defined
18363 @i{expression} ::=  not @i{expression}
18364 @i{expression} ::=  @i{expression} and @i{expression}
18365 @i{expression} ::=  @i{expression} or @i{expression}
18366 @i{expression} ::=  @i{expression} and then @i{expression}
18367 @i{expression} ::=  @i{expression} or else @i{expression}
18368 @i{expression} ::=  ( @i{expression} )
18369 @end smallexample
18370
18371 The following restriction exists: it is not allowed to have "and" or "or"
18372 following "not" in the same expression without parentheses. For example, this
18373 is not allowed:
18374
18375 @smallexample
18376    not X or Y
18377 @end smallexample
18378
18379 This should be one of the following:
18380
18381 @smallexample
18382    (not X) or Y
18383    not (X or Y)
18384 @end smallexample
18385
18386 @noindent
18387 For the first test (@i{expression} ::= <symbol>) the symbol must have
18388 either the value true or false, that is to say the right-hand of the
18389 symbol definition must be one of the (case-insensitive) literals
18390 @code{True} or @code{False}. If the value is true, then the
18391 corresponding lines are included, and if the value is false, they are
18392 excluded.
18393
18394 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18395 the symbol has been defined in the definition file or by a @option{-D}
18396 switch on the command line. Otherwise, the test is false.
18397
18398 The equality tests are case insensitive, as are all the preprocessor lines.
18399
18400 If the symbol referenced is not defined in the symbol definitions file,
18401 then the effect depends on whether or not switch @option{-u}
18402 is specified. If so, then the symbol is treated as if it had the value
18403 false and the test fails. If this switch is not specified, then
18404 it is an error to reference an undefined symbol. It is also an error to
18405 reference a symbol that is defined with a value other than @code{True}
18406 or @code{False}.
18407
18408 The use of the @code{not} operator inverts the sense of this logical test.
18409 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18410 operators, without parentheses. For example, "if not X or Y then" is not
18411 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18412
18413 The @code{then} keyword is optional as shown
18414
18415 The @code{#} must be the first non-blank character on a line, but
18416 otherwise the format is free form. Spaces or tabs may appear between
18417 the @code{#} and the keyword. The keywords and the symbols are case
18418 insensitive as in normal Ada code. Comments may be used on a
18419 preprocessor line, but other than that, no other tokens may appear on a
18420 preprocessor line. Any number of @code{elsif} clauses can be present,
18421 including none at all. The @code{else} is optional, as in Ada.
18422
18423 The @code{#} marking the start of a preprocessor line must be the first
18424 non-blank character on the line, i.e., it must be preceded only by
18425 spaces or horizontal tabs.
18426
18427 Symbol substitution outside of preprocessor lines is obtained by using
18428 the sequence
18429
18430 @smallexample
18431 $symbol
18432 @end smallexample
18433
18434 @noindent
18435 anywhere within a source line, except in a comment or within a
18436 string literal. The identifier
18437 following the @code{$} must match one of the symbols defined in the symbol
18438 definition file, and the result is to substitute the value of the
18439 symbol in place of @code{$symbol} in the output file.
18440
18441 Note that although the substitution of strings within a string literal
18442 is not possible, it is possible to have a symbol whose defined value is
18443 a string literal. So instead of setting XYZ to @code{hello} and writing:
18444
18445 @smallexample
18446 Header : String := "$XYZ";
18447 @end smallexample
18448
18449 @noindent
18450 you should set XYZ to @code{"hello"} and write:
18451
18452 @smallexample
18453 Header : String := $XYZ;
18454 @end smallexample
18455
18456 @noindent
18457 and then the substitution will occur as desired.
18458
18459 @ifset vms
18460 @node The GNAT Run-Time Library Builder gnatlbr
18461 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18462 @findex gnatlbr
18463 @cindex Library builder
18464
18465 @noindent
18466 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18467 supplied configuration pragmas.
18468
18469 @menu
18470 * Running gnatlbr::
18471 * Switches for gnatlbr::
18472 * Examples of gnatlbr Usage::
18473 @end menu
18474
18475 @node Running gnatlbr
18476 @section Running @code{gnatlbr}
18477
18478 @noindent
18479 The @code{gnatlbr} command has the form
18480
18481 @smallexample
18482 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18483 @end smallexample
18484
18485 @node Switches for gnatlbr
18486 @section Switches for @code{gnatlbr}
18487
18488 @noindent
18489 @code{gnatlbr} recognizes the following switches:
18490
18491 @table @option
18492 @c !sort!
18493 @item /CREATE=directory
18494 @cindex @code{/CREATE} (@code{gnatlbr})
18495 Create the new run-time library in the specified directory.
18496
18497 @item /SET=directory
18498 @cindex @code{/SET} (@code{gnatlbr})
18499 Make the library in the specified directory the current run-time library.
18500
18501 @item /DELETE=directory
18502 @cindex @code{/DELETE} (@code{gnatlbr})
18503 Delete the run-time library in the specified directory.
18504
18505 @item /CONFIG=file
18506 @cindex @code{/CONFIG} (@code{gnatlbr})
18507 With /CREATE: Use the configuration pragmas in the specified file when
18508 building the library.
18509
18510 With /SET: Use the configuration pragmas in the specified file when
18511 compiling.
18512
18513 @end table
18514
18515 @node Examples of gnatlbr Usage
18516 @section Example of @code{gnatlbr} Usage
18517
18518 @smallexample
18519 Contents of VAXFLOAT.ADC:
18520 pragma Float_Representation (VAX_Float);
18521
18522 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18523
18524 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18525
18526 @end smallexample
18527 @end ifset
18528
18529 @node The GNAT Library Browser gnatls
18530 @chapter The GNAT Library Browser @code{gnatls}
18531 @findex gnatls
18532 @cindex Library browser
18533
18534 @noindent
18535 @code{gnatls} is a tool that outputs information about compiled
18536 units. It gives the relationship between objects, unit names and source
18537 files. It can also be used to check the source dependencies of a unit
18538 as well as various characteristics.
18539
18540 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18541 driver (see @ref{The GNAT Driver and Project Files}).
18542
18543 @menu
18544 * Running gnatls::
18545 * Switches for gnatls::
18546 * Examples of gnatls Usage::
18547 @end menu
18548
18549 @node Running gnatls
18550 @section Running @code{gnatls}
18551
18552 @noindent
18553 The @code{gnatls} command has the form
18554
18555 @smallexample
18556 $ gnatls switches @var{object_or_ali_file}
18557 @end smallexample
18558
18559 @noindent
18560 The main argument is the list of object or @file{ali} files
18561 (@pxref{The Ada Library Information Files})
18562 for which information is requested.
18563
18564 In normal mode, without additional option, @code{gnatls} produces a
18565 four-column listing. Each line represents information for a specific
18566 object. The first column gives the full path of the object, the second
18567 column gives the name of the principal unit in this object, the third
18568 column gives the status of the source and the fourth column gives the
18569 full path of the source representing this unit.
18570 Here is a simple example of use:
18571
18572 @smallexample
18573 $ gnatls *.o
18574 ^./^[]^demo1.o            demo1            DIF demo1.adb
18575 ^./^[]^demo2.o            demo2             OK demo2.adb
18576 ^./^[]^hello.o            h1                OK hello.adb
18577 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18578 ^./^[]^instr.o            instr             OK instr.adb
18579 ^./^[]^tef.o              tef              DIF tef.adb
18580 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18581 ^./^[]^tgef.o             tgef             DIF tgef.adb
18582 @end smallexample
18583
18584 @noindent
18585 The first line can be interpreted as follows: the main unit which is
18586 contained in
18587 object file @file{demo1.o} is demo1, whose main source is in
18588 @file{demo1.adb}. Furthermore, the version of the source used for the
18589 compilation of demo1 has been modified (DIF). Each source file has a status
18590 qualifier which can be:
18591
18592 @table @code
18593 @item OK (unchanged)
18594 The version of the source file used for the compilation of the
18595 specified unit corresponds exactly to the actual source file.
18596
18597 @item MOK (slightly modified)
18598 The version of the source file used for the compilation of the
18599 specified unit differs from the actual source file but not enough to
18600 require recompilation. If you use gnatmake with the qualifier
18601 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18602 MOK will not be recompiled.
18603
18604 @item DIF (modified)
18605 No version of the source found on the path corresponds to the source
18606 used to build this object.
18607
18608 @item ??? (file not found)
18609 No source file was found for this unit.
18610
18611 @item HID (hidden,  unchanged version not first on PATH)
18612 The version of the source that corresponds exactly to the source used
18613 for compilation has been found on the path but it is hidden by another
18614 version of the same source that has been modified.
18615
18616 @end table
18617
18618 @node Switches for gnatls
18619 @section Switches for @code{gnatls}
18620
18621 @noindent
18622 @code{gnatls} recognizes the following switches:
18623
18624 @table @option
18625 @c !sort!
18626 @cindex @option{--version} @command{gnatls}
18627 Display Copyright and version, then exit disregarding all other options.
18628
18629 @item --help
18630 @cindex @option{--help} @command{gnatls}
18631 If @option{--version} was not used, display usage, then exit disregarding
18632 all other options.
18633
18634 @item ^-a^/ALL_UNITS^
18635 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18636 Consider all units, including those of the predefined Ada library.
18637 Especially useful with @option{^-d^/DEPENDENCIES^}.
18638
18639 @item ^-d^/DEPENDENCIES^
18640 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18641 List sources from which specified units depend on.
18642
18643 @item ^-h^/OUTPUT=OPTIONS^
18644 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18645 Output the list of options.
18646
18647 @item ^-o^/OUTPUT=OBJECTS^
18648 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18649 Only output information about object files.
18650
18651 @item ^-s^/OUTPUT=SOURCES^
18652 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18653 Only output information about source files.
18654
18655 @item ^-u^/OUTPUT=UNITS^
18656 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18657 Only output information about compilation units.
18658
18659 @item ^-files^/FILES^=@var{file}
18660 @cindex @option{^-files^/FILES^} (@code{gnatls})
18661 Take as arguments the files listed in text file @var{file}.
18662 Text file @var{file} may contain empty lines that are ignored.
18663 Each nonempty line should contain the name of an existing file.
18664 Several such switches may be specified simultaneously.
18665
18666 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18667 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18668 @itemx ^-I^/SEARCH=^@var{dir}
18669 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18670 @itemx -nostdinc
18671 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18672 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18673 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18674 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18675 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18676 flags (@pxref{Switches for gnatmake}).
18677
18678 @item --RTS=@var{rts-path}
18679 @cindex @option{--RTS} (@code{gnatls})
18680 Specifies the default location of the runtime library. Same meaning as the
18681 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18682
18683 @item ^-v^/OUTPUT=VERBOSE^
18684 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18685 Verbose mode. Output the complete source, object and project paths. Do not use
18686 the default column layout but instead use long format giving as much as
18687 information possible on each requested units, including special
18688 characteristics such as:
18689
18690 @table @code
18691 @item  Preelaborable
18692 The unit is preelaborable in the Ada sense.
18693
18694 @item No_Elab_Code
18695 No elaboration code has been produced by the compiler for this unit.
18696
18697 @item Pure
18698 The unit is pure in the Ada sense.
18699
18700 @item Elaborate_Body
18701 The unit contains a pragma Elaborate_Body.
18702
18703 @item Remote_Types
18704 The unit contains a pragma Remote_Types.
18705
18706 @item Shared_Passive
18707 The unit contains a pragma Shared_Passive.
18708
18709 @item Predefined
18710 This unit is part of the predefined environment and cannot be modified
18711 by the user.
18712
18713 @item Remote_Call_Interface
18714 The unit contains a pragma Remote_Call_Interface.
18715
18716 @end table
18717
18718 @end table
18719
18720 @node Examples of gnatls Usage
18721 @section Example of @code{gnatls} Usage
18722 @ifclear vms
18723
18724 @noindent
18725 Example of using the verbose switch. Note how the source and
18726 object paths are affected by the -I switch.
18727
18728 @smallexample
18729 $ gnatls -v -I.. demo1.o
18730
18731 GNATLS 5.03w (20041123-34)
18732 Copyright 1997-2004 Free Software Foundation, Inc.
18733
18734 Source Search Path:
18735    <Current_Directory>
18736    ../
18737    /home/comar/local/adainclude/
18738
18739 Object Search Path:
18740    <Current_Directory>
18741    ../
18742    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18743
18744 Project Search Path:
18745    <Current_Directory>
18746    /home/comar/local/lib/gnat/
18747
18748 ./demo1.o
18749    Unit =>
18750      Name   => demo1
18751      Kind   => subprogram body
18752      Flags  => No_Elab_Code
18753      Source => demo1.adb    modified
18754 @end smallexample
18755
18756 @noindent
18757 The following is an example of use of the dependency list.
18758 Note the use of the -s switch
18759 which gives a straight list of source files. This can be useful for
18760 building specialized scripts.
18761
18762 @smallexample
18763 $ gnatls -d demo2.o
18764 ./demo2.o   demo2        OK demo2.adb
18765                          OK gen_list.ads
18766                          OK gen_list.adb
18767                          OK instr.ads
18768                          OK instr-child.ads
18769
18770 $ gnatls -d -s -a demo1.o
18771 demo1.adb
18772 /home/comar/local/adainclude/ada.ads
18773 /home/comar/local/adainclude/a-finali.ads
18774 /home/comar/local/adainclude/a-filico.ads
18775 /home/comar/local/adainclude/a-stream.ads
18776 /home/comar/local/adainclude/a-tags.ads
18777 gen_list.ads
18778 gen_list.adb
18779 /home/comar/local/adainclude/gnat.ads
18780 /home/comar/local/adainclude/g-io.ads
18781 instr.ads
18782 /home/comar/local/adainclude/system.ads
18783 /home/comar/local/adainclude/s-exctab.ads
18784 /home/comar/local/adainclude/s-finimp.ads
18785 /home/comar/local/adainclude/s-finroo.ads
18786 /home/comar/local/adainclude/s-secsta.ads
18787 /home/comar/local/adainclude/s-stalib.ads
18788 /home/comar/local/adainclude/s-stoele.ads
18789 /home/comar/local/adainclude/s-stratt.ads
18790 /home/comar/local/adainclude/s-tasoli.ads
18791 /home/comar/local/adainclude/s-unstyp.ads
18792 /home/comar/local/adainclude/unchconv.ads
18793 @end smallexample
18794 @end ifclear
18795
18796 @ifset vms
18797 @smallexample
18798 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18799
18800 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18801 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18802 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18803 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18804 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18805 demo1.adb
18806 gen_list.ads
18807 gen_list.adb
18808 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18809 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18810 instr.ads
18811 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18812 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18813 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18814 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18815 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18816 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18817 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18818 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18819 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18820 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18822 @end smallexample
18823 @end ifset
18824
18825 @node Cleaning Up Using gnatclean
18826 @chapter Cleaning Up Using @code{gnatclean}
18827 @findex gnatclean
18828 @cindex Cleaning tool
18829
18830 @noindent
18831 @code{gnatclean} is a tool that allows the deletion of files produced by the
18832 compiler, binder and linker, including ALI files, object files, tree files,
18833 expanded source files, library files, interface copy source files, binder
18834 generated files and executable files.
18835
18836 @menu
18837 * Running gnatclean::
18838 * Switches for gnatclean::
18839 @c * Examples of gnatclean Usage::
18840 @end menu
18841
18842 @node Running gnatclean
18843 @section Running @code{gnatclean}
18844
18845 @noindent
18846 The @code{gnatclean} command has the form:
18847
18848 @smallexample
18849 $ gnatclean switches @var{names}
18850 @end smallexample
18851
18852 @noindent
18853 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18854 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18855 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18856
18857 @noindent
18858 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18859 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18860 the linker. In informative-only mode, specified by switch
18861 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18862 normal mode is listed, but no file is actually deleted.
18863
18864 @node Switches for gnatclean
18865 @section Switches for @code{gnatclean}
18866
18867 @noindent
18868 @code{gnatclean} recognizes the following switches:
18869
18870 @table @option
18871 @c !sort!
18872 @cindex @option{--version} @command{gnatclean}
18873 Display Copyright and version, then exit disregarding all other options.
18874
18875 @item --help
18876 @cindex @option{--help} @command{gnatclean}
18877 If @option{--version} was not used, display usage, then exit disregarding
18878 all other options.
18879
18880 @item ^-c^/COMPILER_FILES_ONLY^
18881 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18882 Only attempt to delete the files produced by the compiler, not those produced
18883 by the binder or the linker. The files that are not to be deleted are library
18884 files, interface copy files, binder generated files and executable files.
18885
18886 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18887 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18888 Indicate that ALI and object files should normally be found in directory
18889 @var{dir}.
18890
18891 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18892 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18893 When using project files, if some errors or warnings are detected during
18894 parsing and verbose mode is not in effect (no use of switch
18895 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18896 file, rather than its simple file name.
18897
18898 @item ^-h^/HELP^
18899 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18900 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18901
18902 @item ^-n^/NODELETE^
18903 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18904 Informative-only mode. Do not delete any files. Output the list of the files
18905 that would have been deleted if this switch was not specified.
18906
18907 @item ^-P^/PROJECT_FILE=^@var{project}
18908 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18909 Use project file @var{project}. Only one such switch can be used.
18910 When cleaning a project file, the files produced by the compilation of the
18911 immediate sources or inherited sources of the project files are to be
18912 deleted. This is not depending on the presence or not of executable names
18913 on the command line.
18914
18915 @item ^-q^/QUIET^
18916 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18917 Quiet output. If there are no errors, do not output anything, except in
18918 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18919 (switch ^-n^/NODELETE^).
18920
18921 @item ^-r^/RECURSIVE^
18922 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18923 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18924 clean all imported and extended project files, recursively. If this switch
18925 is not specified, only the files related to the main project file are to be
18926 deleted. This switch has no effect if no project file is specified.
18927
18928 @item ^-v^/VERBOSE^
18929 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18930 Verbose mode.
18931
18932 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18933 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18934 Indicates the verbosity of the parsing of GNAT project files.
18935 @xref{Switches Related to Project Files}.
18936
18937 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18938 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18939 Indicates that external variable @var{name} has the value @var{value}.
18940 The Project Manager will use this value for occurrences of
18941 @code{external(name)} when parsing the project file.
18942 @xref{Switches Related to Project Files}.
18943
18944 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18945 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18946 When searching for ALI and object files, look in directory
18947 @var{dir}.
18948
18949 @item ^-I^/SEARCH=^@var{dir}
18950 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18951 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18952
18953 @item ^-I-^/NOCURRENT_DIRECTORY^
18954 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18955 @cindex Source files, suppressing search
18956 Do not look for ALI or object files in the directory
18957 where @code{gnatclean} was invoked.
18958
18959 @end table
18960
18961 @c @node Examples of gnatclean Usage
18962 @c @section Examples of @code{gnatclean} Usage
18963
18964 @ifclear vms
18965 @node GNAT and Libraries
18966 @chapter GNAT and Libraries
18967 @cindex Library, building, installing, using
18968
18969 @noindent
18970 This chapter describes how to build and use libraries with GNAT, and also shows
18971 how to recompile the GNAT run-time library. You should be familiar with the
18972 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18973 chapter.
18974
18975 @menu
18976 * Introduction to Libraries in GNAT::
18977 * General Ada Libraries::
18978 * Stand-alone Ada Libraries::
18979 * Rebuilding the GNAT Run-Time Library::
18980 @end menu
18981
18982 @node Introduction to Libraries in GNAT
18983 @section Introduction to Libraries in GNAT
18984
18985 @noindent
18986 A library is, conceptually, a collection of objects which does not have its
18987 own main thread of execution, but rather provides certain services to the
18988 applications that use it. A library can be either statically linked with the
18989 application, in which case its code is directly included in the application,
18990 or, on platforms that support it, be dynamically linked, in which case
18991 its code is shared by all applications making use of this library.
18992
18993 GNAT supports both types of libraries.
18994 In the static case, the compiled code can be provided in different ways. The
18995 simplest approach is to provide directly the set of objects resulting from
18996 compilation of the library source files. Alternatively, you can group the
18997 objects into an archive using whatever commands are provided by the operating
18998 system. For the latter case, the objects are grouped into a shared library.
18999
19000 In the GNAT environment, a library has three types of components:
19001 @itemize @bullet
19002 @item
19003 Source files.
19004 @item
19005 @file{ALI} files.
19006 @xref{The Ada Library Information Files}.
19007 @item
19008 Object files, an archive or a shared library.
19009 @end itemize
19010
19011 @noindent
19012 A GNAT library may expose all its source files, which is useful for
19013 documentation purposes. Alternatively, it may expose only the units needed by
19014 an external user to make use of the library. That is to say, the specs
19015 reflecting the library services along with all the units needed to compile
19016 those specs, which can include generic bodies or any body implementing an
19017 inlined routine. In the case of @emph{stand-alone libraries} those exposed
19018 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
19019
19020 All compilation units comprising an application, including those in a library,
19021 need to be elaborated in an order partially defined by Ada's semantics. GNAT
19022 computes the elaboration order from the @file{ALI} files and this is why they
19023 constitute a mandatory part of GNAT libraries.
19024 @emph{Stand-alone libraries} are the exception to this rule because a specific
19025 library elaboration routine is produced independently of the application(s)
19026 using the library.
19027
19028 @node General Ada Libraries
19029 @section General Ada Libraries
19030
19031 @menu
19032 * Building a library::
19033 * Installing a library::
19034 * Using a library::
19035 @end menu
19036
19037 @node Building a library
19038 @subsection Building a library
19039
19040 @noindent
19041 The easiest way to build a library is to use the Project Manager,
19042 which supports a special type of project called a @emph{Library Project}
19043 (@pxref{Library Projects}).
19044
19045 A project is considered a library project, when two project-level attributes
19046 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19047 control different aspects of library configuration, additional optional
19048 project-level attributes can be specified:
19049 @table @code
19050 @item Library_Kind
19051 This attribute controls whether the library is to be static or dynamic
19052
19053 @item Library_Version
19054 This attribute specifies the library version; this value is used
19055 during dynamic linking of shared libraries to determine if the currently
19056 installed versions of the binaries are compatible.
19057
19058 @item Library_Options
19059 @item Library_GCC
19060 These attributes specify additional low-level options to be used during
19061 library generation, and redefine the actual application used to generate
19062 library.
19063 @end table
19064
19065 @noindent
19066 The GNAT Project Manager takes full care of the library maintenance task,
19067 including recompilation of the source files for which objects do not exist
19068 or are not up to date, assembly of the library archive, and installation of
19069 the library (i.e., copying associated source, object and @file{ALI} files
19070 to the specified location).
19071
19072 Here is a simple library project file:
19073 @smallexample @c ada
19074 project My_Lib is
19075    for Source_Dirs use ("src1", "src2");
19076    for Object_Dir use "obj";
19077    for Library_Name use "mylib";
19078    for Library_Dir use "lib";
19079    for Library_Kind use "dynamic";
19080 end My_lib;
19081 @end smallexample
19082
19083 @noindent
19084 and the compilation command to build and install the library:
19085
19086 @smallexample @c ada
19087   $ gnatmake -Pmy_lib
19088 @end smallexample
19089
19090 @noindent
19091 It is not entirely trivial to perform manually all the steps required to
19092 produce a library. We recommend that you use the GNAT Project Manager
19093 for this task. In special cases where this is not desired, the necessary
19094 steps are discussed below.
19095
19096 There are various possibilities for compiling the units that make up the
19097 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19098 with a conventional script. For simple libraries, it is also possible to create
19099 a dummy main program which depends upon all the packages that comprise the
19100 interface of the library. This dummy main program can then be given to
19101 @command{gnatmake}, which will ensure that all necessary objects are built.
19102
19103 After this task is accomplished, you should follow the standard procedure
19104 of the underlying operating system to produce the static or shared library.
19105
19106 Here is an example of such a dummy program:
19107 @smallexample @c ada
19108 @group
19109 with My_Lib.Service1;
19110 with My_Lib.Service2;
19111 with My_Lib.Service3;
19112 procedure My_Lib_Dummy is
19113 begin
19114    null;
19115 end;
19116 @end group
19117 @end smallexample
19118
19119 @noindent
19120 Here are the generic commands that will build an archive or a shared library.
19121
19122 @smallexample
19123 # compiling the library
19124 $ gnatmake -c my_lib_dummy.adb
19125
19126 # we don't need the dummy object itself
19127 $ rm my_lib_dummy.o my_lib_dummy.ali
19128
19129 # create an archive with the remaining objects
19130 $ ar rc libmy_lib.a *.o
19131 # some systems may require "ranlib" to be run as well
19132
19133 # or create a shared library
19134 $ gcc -shared -o libmy_lib.so *.o
19135 # some systems may require the code to have been compiled with -fPIC
19136
19137 # remove the object files that are now in the library
19138 $ rm *.o
19139
19140 # Make the ALI files read-only so that gnatmake will not try to
19141 # regenerate the objects that are in the library
19142 $ chmod -w *.ali
19143 @end smallexample
19144
19145 @noindent
19146 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19147 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19148 be accessed by the directive @option{-l@var{xxx}} at link time.
19149
19150 @node Installing a library
19151 @subsection Installing a library
19152 @cindex @code{ADA_PROJECT_PATH}
19153 @cindex @code{GPR_PROJECT_PATH}
19154
19155 @noindent
19156 If you use project files, library installation is part of the library build
19157 process. Thus no further action is needed in order to make use of the
19158 libraries that are built as part of the general application build. A usable
19159 version of the library is installed in the directory specified by the
19160 @code{Library_Dir} attribute of the library project file.
19161
19162 You may want to install a library in a context different from where the library
19163 is built. This situation arises with third party suppliers, who may want
19164 to distribute a library in binary form where the user is not expected to be
19165 able to recompile the library. The simplest option in this case is to provide
19166 a project file slightly different from the one used to build the library, by
19167 using the @code{externally_built} attribute. For instance, the project
19168 file used to build the library in the previous section can be changed into the
19169 following one when the library is installed:
19170
19171 @smallexample @c projectfile
19172 project My_Lib is
19173    for Source_Dirs use ("src1", "src2");
19174    for Library_Name use "mylib";
19175    for Library_Dir use "lib";
19176    for Library_Kind use "dynamic";
19177    for Externally_Built use "true";
19178 end My_lib;
19179 @end smallexample
19180
19181 @noindent
19182 This project file assumes that the directories @file{src1},
19183 @file{src2}, and @file{lib} exist in
19184 the directory containing the project file. The @code{externally_built}
19185 attribute makes it clear to the GNAT builder that it should not attempt to
19186 recompile any of the units from this library. It allows the library provider to
19187 restrict the source set to the minimum necessary for clients to make use of the
19188 library as described in the first section of this chapter. It is the
19189 responsibility of the library provider to install the necessary sources, ALI
19190 files and libraries in the directories mentioned in the project file. For
19191 convenience, the user's library project file should be installed in a location
19192 that will be searched automatically by the GNAT
19193 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19194 environment variable (@pxref{Importing Projects}), and also the default GNAT
19195 library location that can be queried with @command{gnatls -v} and is usually of
19196 the form $gnat_install_root/lib/gnat.
19197
19198 When project files are not an option, it is also possible, but not recommended,
19199 to install the library so that the sources needed to use the library are on the
19200 Ada source path and the ALI files & libraries be on the Ada Object path (see
19201 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19202 administrator can place general-purpose libraries in the default compiler
19203 paths, by specifying the libraries' location in the configuration files
19204 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19205 must be located in the GNAT installation tree at the same place as the gcc spec
19206 file. The location of the gcc spec file can be determined as follows:
19207 @smallexample
19208 $ gcc -v
19209 @end smallexample
19210
19211 @noindent
19212 The configuration files mentioned above have a simple format: each line
19213 must contain one unique directory name.
19214 Those names are added to the corresponding path
19215 in their order of appearance in the file. The names can be either absolute
19216 or relative; in the latter case, they are relative to where theses files
19217 are located.
19218
19219 The files @file{ada_source_path} and @file{ada_object_path} might not be
19220 present in a
19221 GNAT installation, in which case, GNAT will look for its run-time library in
19222 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19223 objects and @file{ALI} files). When the files exist, the compiler does not
19224 look in @file{adainclude} and @file{adalib}, and thus the
19225 @file{ada_source_path} file
19226 must contain the location for the GNAT run-time sources (which can simply
19227 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19228 contain the location for the GNAT run-time objects (which can simply
19229 be @file{adalib}).
19230
19231 You can also specify a new default path to the run-time library at compilation
19232 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19233 the run-time library you want your program to be compiled with. This switch is
19234 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19235 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19236
19237 It is possible to install a library before or after the standard GNAT
19238 library, by reordering the lines in the configuration files. In general, a
19239 library must be installed before the GNAT library if it redefines
19240 any part of it.
19241
19242 @node Using a library
19243 @subsection Using a library
19244
19245 @noindent Once again, the project facility greatly simplifies the use of
19246 libraries. In this context, using a library is just a matter of adding a
19247 @code{with} clause in the user project. For instance, to make use of the
19248 library @code{My_Lib} shown in examples in earlier sections, you can
19249 write:
19250
19251 @smallexample @c projectfile
19252 with "my_lib";
19253 project My_Proj is
19254   @dots{}
19255 end My_Proj;
19256 @end smallexample
19257
19258 Even if you have a third-party, non-Ada library, you can still use GNAT's
19259 Project Manager facility to provide a wrapper for it. For example, the
19260 following project, when @code{with}ed by your main project, will link with the
19261 third-party library @file{liba.a}:
19262
19263 @smallexample @c projectfile
19264 @group
19265 project Liba is
19266    for Externally_Built use "true";
19267    for Source_Files use ();
19268    for Library_Dir use "lib";
19269    for Library_Name use "a";
19270    for Library_Kind use "static";
19271 end Liba;
19272 @end group
19273 @end smallexample
19274 This is an alternative to the use of @code{pragma Linker_Options}. It is
19275 especially interesting in the context of systems with several interdependent
19276 static libraries where finding a proper linker order is not easy and best be
19277 left to the tools having visibility over project dependence information.
19278
19279 @noindent
19280 In order to use an Ada library manually, you need to make sure that this
19281 library is on both your source and object path
19282 (see @ref{Search Paths and the Run-Time Library (RTL)}
19283 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19284 in an archive or a shared library, you need to specify the desired
19285 library at link time.
19286
19287 For example, you can use the library @file{mylib} installed in
19288 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19289
19290 @smallexample
19291 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19292   -largs -lmy_lib
19293 @end smallexample
19294
19295 @noindent
19296 This can be expressed more simply:
19297 @smallexample
19298 $ gnatmake my_appl
19299 @end smallexample
19300 @noindent
19301 when the following conditions are met:
19302 @itemize @bullet
19303 @item
19304 @file{/dir/my_lib_src} has been added by the user to the environment
19305 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19306 @file{ada_source_path}
19307 @item
19308 @file{/dir/my_lib_obj} has been added by the user to the environment
19309 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19310 @file{ada_object_path}
19311 @item
19312 a pragma @code{Linker_Options} has been added to one of the sources.
19313 For example:
19314
19315 @smallexample @c ada
19316 pragma Linker_Options ("-lmy_lib");
19317 @end smallexample
19318 @end itemize
19319
19320 @node Stand-alone Ada Libraries
19321 @section Stand-alone Ada Libraries
19322 @cindex Stand-alone library, building, using
19323
19324 @menu
19325 * Introduction to Stand-alone Libraries::
19326 * Building a Stand-alone Library::
19327 * Creating a Stand-alone Library to be used in a non-Ada context::
19328 * Restrictions in Stand-alone Libraries::
19329 @end menu
19330
19331 @node Introduction to Stand-alone Libraries
19332 @subsection Introduction to Stand-alone Libraries
19333
19334 @noindent
19335 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19336 necessary code to
19337 elaborate the Ada units that are included in the library. In contrast with
19338 an ordinary library, which consists of all sources, objects and @file{ALI}
19339 files of the
19340 library, a SAL may specify a restricted subset of compilation units
19341 to serve as a library interface. In this case, the fully
19342 self-sufficient set of files will normally consist of an objects
19343 archive, the sources of interface units' specs, and the @file{ALI}
19344 files of interface units.
19345 If an interface spec contains a generic unit or an inlined subprogram,
19346 the body's
19347 source must also be provided; if the units that must be provided in the source
19348 form depend on other units, the source and @file{ALI} files of those must
19349 also be provided.
19350
19351 The main purpose of a SAL is to minimize the recompilation overhead of client
19352 applications when a new version of the library is installed. Specifically,
19353 if the interface sources have not changed, client applications do not need to
19354 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19355 version, controlled by @code{Library_Version} attribute, is not changed,
19356 then the clients do not need to be relinked.
19357
19358 SALs also allow the library providers to minimize the amount of library source
19359 text exposed to the clients.  Such ``information hiding'' might be useful or
19360 necessary for various reasons.
19361
19362 Stand-alone libraries are also well suited to be used in an executable whose
19363 main routine is not written in Ada.
19364
19365 @node Building a Stand-alone Library
19366 @subsection Building a Stand-alone Library
19367
19368 @noindent
19369 GNAT's Project facility provides a simple way of building and installing
19370 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19371 To be a Stand-alone Library Project, in addition to the two attributes
19372 that make a project a Library Project (@code{Library_Name} and
19373 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19374 @code{Library_Interface} must be defined.  For example:
19375
19376 @smallexample @c projectfile
19377 @group
19378    for Library_Dir use "lib_dir";
19379    for Library_Name use "dummy";
19380    for Library_Interface use ("int1", "int1.child");
19381 @end group
19382 @end smallexample
19383
19384 @noindent
19385 Attribute @code{Library_Interface} has a non-empty string list value,
19386 each string in the list designating a unit contained in an immediate source
19387 of the project file.
19388
19389 When a Stand-alone Library is built, first the binder is invoked to build
19390 a package whose name depends on the library name
19391 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19392 This binder-generated package includes initialization and
19393 finalization procedures whose
19394 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19395 in the example
19396 above). The object corresponding to this package is included in the library.
19397
19398 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19399 calling of these procedures if a static SAL is built, or if a shared SAL
19400 is built
19401 with the project-level attribute @code{Library_Auto_Init} set to
19402 @code{"false"}.
19403
19404 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19405 (those that are listed in attribute @code{Library_Interface}) are copied to
19406 the Library Directory. As a consequence, only the Interface Units may be
19407 imported from Ada units outside of the library. If other units are imported,
19408 the binding phase will fail.
19409
19410 The attribute @code{Library_Src_Dir} may be specified for a
19411 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19412 single string value. Its value must be the path (absolute or relative to the
19413 project directory) of an existing directory. This directory cannot be the
19414 object directory or one of the source directories, but it can be the same as
19415 the library directory. The sources of the Interface
19416 Units of the library that are needed by an Ada client of the library will be
19417 copied to the designated directory, called the Interface Copy directory.
19418 These sources include the specs of the Interface Units, but they may also
19419 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19420 are used, or when there is a generic unit in the spec. Before the sources
19421 are copied to the Interface Copy directory, an attempt is made to delete all
19422 files in the Interface Copy directory.
19423
19424 Building stand-alone libraries by hand is somewhat tedious, but for those
19425 occasions when it is necessary here are the steps that you need to perform:
19426 @itemize @bullet
19427 @item
19428 Compile all library sources.
19429
19430 @item
19431 Invoke the binder with the switch @option{-n} (No Ada main program),
19432 with all the @file{ALI} files of the interfaces, and
19433 with the switch @option{-L} to give specific names to the @code{init}
19434 and @code{final} procedures.  For example:
19435 @smallexample
19436   gnatbind -n int1.ali int2.ali -Lsal1
19437 @end smallexample
19438
19439 @item
19440 Compile the binder generated file:
19441 @smallexample
19442   gcc -c b~int2.adb
19443 @end smallexample
19444
19445 @item
19446 Link the dynamic library with all the necessary object files,
19447 indicating to the linker the names of the @code{init} (and possibly
19448 @code{final}) procedures for automatic initialization (and finalization).
19449 The built library should be placed in a directory different from
19450 the object directory.
19451
19452 @item
19453 Copy the @code{ALI} files of the interface to the library directory,
19454 add in this copy an indication that it is an interface to a SAL
19455 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19456 with letter ``P'') and make the modified copy of the @file{ALI} file
19457 read-only.
19458 @end itemize
19459
19460 @noindent
19461 Using SALs is not different from using other libraries
19462 (see @ref{Using a library}).
19463
19464 @node Creating a Stand-alone Library to be used in a non-Ada context
19465 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19466
19467 @noindent
19468 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19469 a non-Ada context.
19470
19471 The only extra step required is to ensure that library interface subprograms
19472 are compatible with the main program, by means of @code{pragma Export}
19473 or @code{pragma Convention}.
19474
19475 Here is an example of simple library interface for use with C main program:
19476
19477 @smallexample @c ada
19478 package My_Package is
19479
19480    procedure Do_Something;
19481    pragma Export (C, Do_Something, "do_something");
19482
19483    procedure Do_Something_Else;
19484    pragma Export (C, Do_Something_Else, "do_something_else");
19485
19486 end My_Package;
19487 @end smallexample
19488
19489 @noindent
19490 On the foreign language side, you must provide a ``foreign'' view of the
19491 library interface; remember that it should contain elaboration routines in
19492 addition to interface subprograms.
19493
19494 The example below shows the content of @code{mylib_interface.h} (note
19495 that there is no rule for the naming of this file, any name can be used)
19496 @smallexample
19497 /* the library elaboration procedure */
19498 extern void mylibinit (void);
19499
19500 /* the library finalization procedure */
19501 extern void mylibfinal (void);
19502
19503 /* the interface exported by the library */
19504 extern void do_something (void);
19505 extern void do_something_else (void);
19506 @end smallexample
19507
19508 @noindent
19509 Libraries built as explained above can be used from any program, provided
19510 that the elaboration procedures (named @code{mylibinit} in the previous
19511 example) are called before the library services are used. Any number of
19512 libraries can be used simultaneously, as long as the elaboration
19513 procedure of each library is called.
19514
19515 Below is an example of a C program that uses the @code{mylib} library.
19516
19517 @smallexample
19518 #include "mylib_interface.h"
19519
19520 int
19521 main (void)
19522 @{
19523    /* First, elaborate the library before using it */
19524    mylibinit ();
19525
19526    /* Main program, using the library exported entities */
19527    do_something ();
19528    do_something_else ();
19529
19530    /* Library finalization at the end of the program */
19531    mylibfinal ();
19532    return 0;
19533 @}
19534 @end smallexample
19535
19536 @noindent
19537 Note that invoking any library finalization procedure generated by
19538 @code{gnatbind} shuts down the Ada run-time environment.
19539 Consequently, the
19540 finalization of all Ada libraries must be performed at the end of the program.
19541 No call to these libraries or to the Ada run-time library should be made
19542 after the finalization phase.
19543
19544 @node Restrictions in Stand-alone Libraries
19545 @subsection Restrictions in Stand-alone Libraries
19546
19547 @noindent
19548 The pragmas listed below should be used with caution inside libraries,
19549 as they can create incompatibilities with other Ada libraries:
19550 @itemize @bullet
19551 @item pragma @code{Locking_Policy}
19552 @item pragma @code{Queuing_Policy}
19553 @item pragma @code{Task_Dispatching_Policy}
19554 @item pragma @code{Unreserve_All_Interrupts}
19555 @end itemize
19556
19557 @noindent
19558 When using a library that contains such pragmas, the user must make sure
19559 that all libraries use the same pragmas with the same values. Otherwise,
19560 @code{Program_Error} will
19561 be raised during the elaboration of the conflicting
19562 libraries. The usage of these pragmas and its consequences for the user
19563 should therefore be well documented.
19564
19565 Similarly, the traceback in the exception occurrence mechanism should be
19566 enabled or disabled in a consistent manner across all libraries.
19567 Otherwise, Program_Error will be raised during the elaboration of the
19568 conflicting libraries.
19569
19570 If the @code{Version} or @code{Body_Version}
19571 attributes are used inside a library, then you need to
19572 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19573 libraries, so that version identifiers can be properly computed.
19574 In practice these attributes are rarely used, so this is unlikely
19575 to be a consideration.
19576
19577 @node  Rebuilding the GNAT Run-Time Library
19578 @section Rebuilding the GNAT Run-Time Library
19579 @cindex GNAT Run-Time Library, rebuilding
19580 @cindex Building the GNAT Run-Time Library
19581 @cindex Rebuilding the GNAT Run-Time Library
19582 @cindex Run-Time Library, rebuilding
19583
19584 @noindent
19585 It may be useful to recompile the GNAT library in various contexts, the
19586 most important one being the use of partition-wide configuration pragmas
19587 such as @code{Normalize_Scalars}. A special Makefile called
19588 @code{Makefile.adalib} is provided to that effect and can be found in
19589 the directory containing the GNAT library. The location of this
19590 directory depends on the way the GNAT environment has been installed and can
19591 be determined by means of the command:
19592
19593 @smallexample
19594 $ gnatls -v
19595 @end smallexample
19596
19597 @noindent
19598 The last entry in the object search path usually contains the
19599 gnat library. This Makefile contains its own documentation and in
19600 particular the set of instructions needed to rebuild a new library and
19601 to use it.
19602
19603 @node Using the GNU make Utility
19604 @chapter Using the GNU @code{make} Utility
19605 @findex make
19606
19607 @noindent
19608 This chapter offers some examples of makefiles that solve specific
19609 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19610 make, make, GNU @code{make}}), nor does it try to replace the
19611 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19612
19613 All the examples in this section are specific to the GNU version of
19614 make. Although @command{make} is a standard utility, and the basic language
19615 is the same, these examples use some advanced features found only in
19616 @code{GNU make}.
19617
19618 @menu
19619 * Using gnatmake in a Makefile::
19620 * Automatically Creating a List of Directories::
19621 * Generating the Command Line Switches::
19622 * Overcoming Command Line Length Limits::
19623 @end menu
19624
19625 @node Using gnatmake in a Makefile
19626 @section Using gnatmake in a Makefile
19627 @findex makefile
19628 @cindex GNU make
19629
19630 @noindent
19631 Complex project organizations can be handled in a very powerful way by
19632 using GNU make combined with gnatmake. For instance, here is a Makefile
19633 which allows you to build each subsystem of a big project into a separate
19634 shared library. Such a makefile allows you to significantly reduce the link
19635 time of very big applications while maintaining full coherence at
19636 each step of the build process.
19637
19638 The list of dependencies are handled automatically by
19639 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19640 the appropriate directories.
19641
19642 Note that you should also read the example on how to automatically
19643 create the list of directories
19644 (@pxref{Automatically Creating a List of Directories})
19645 which might help you in case your project has a lot of subdirectories.
19646
19647 @smallexample
19648 @iftex
19649 @leftskip=0cm
19650 @font@heightrm=cmr8
19651 @heightrm
19652 @end iftex
19653 ## This Makefile is intended to be used with the following directory
19654 ## configuration:
19655 ##  - The sources are split into a series of csc (computer software components)
19656 ##    Each of these csc is put in its own directory.
19657 ##    Their name are referenced by the directory names.
19658 ##    They will be compiled into shared library (although this would also work
19659 ##    with static libraries
19660 ##  - The main program (and possibly other packages that do not belong to any
19661 ##    csc is put in the top level directory (where the Makefile is).
19662 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19663 ##                    \_ second_csc (sources) __ lib (will contain the library)
19664 ##                    \_ @dots{}
19665 ## Although this Makefile is build for shared library, it is easy to modify
19666 ## to build partial link objects instead (modify the lines with -shared and
19667 ## gnatlink below)
19668 ##
19669 ## With this makefile, you can change any file in the system or add any new
19670 ## file, and everything will be recompiled correctly (only the relevant shared
19671 ## objects will be recompiled, and the main program will be re-linked).
19672
19673 # The list of computer software component for your project. This might be
19674 # generated automatically.
19675 CSC_LIST=aa bb cc
19676
19677 # Name of the main program (no extension)
19678 MAIN=main
19679
19680 # If we need to build objects with -fPIC, uncomment the following line
19681 #NEED_FPIC=-fPIC
19682
19683 # The following variable should give the directory containing libgnat.so
19684 # You can get this directory through 'gnatls -v'. This is usually the last
19685 # directory in the Object_Path.
19686 GLIB=@dots{}
19687
19688 # The directories for the libraries
19689 # (This macro expands the list of CSC to the list of shared libraries, you
19690 # could simply use the expanded form:
19691 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19692 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19693
19694 $@{MAIN@}: objects $@{LIB_DIR@}
19695     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19696     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19697
19698 objects::
19699     # recompile the sources
19700     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19701
19702 # Note: In a future version of GNAT, the following commands will be simplified
19703 # by a new tool, gnatmlib
19704 $@{LIB_DIR@}:
19705     mkdir -p $@{dir $@@ @}
19706     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19707     cd $@{dir $@@ @} && cp -f ../*.ali .
19708
19709 # The dependencies for the modules
19710 # Note that we have to force the expansion of *.o, since in some cases
19711 # make won't be able to do it itself.
19712 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19713 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19714 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19715
19716 # Make sure all of the shared libraries are in the path before starting the
19717 # program
19718 run::
19719     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19720
19721 clean::
19722     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19723     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19724     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19725     $@{RM@} *.o *.ali $@{MAIN@}
19726 @end smallexample
19727
19728 @node Automatically Creating a List of Directories
19729 @section Automatically Creating a List of Directories
19730
19731 @noindent
19732 In most makefiles, you will have to specify a list of directories, and
19733 store it in a variable. For small projects, it is often easier to
19734 specify each of them by hand, since you then have full control over what
19735 is the proper order for these directories, which ones should be
19736 included.
19737
19738 However, in larger projects, which might involve hundreds of
19739 subdirectories, it might be more convenient to generate this list
19740 automatically.
19741
19742 The example below presents two methods. The first one, although less
19743 general, gives you more control over the list. It involves wildcard
19744 characters, that are automatically expanded by @command{make}. Its
19745 shortcoming is that you need to explicitly specify some of the
19746 organization of your project, such as for instance the directory tree
19747 depth, whether some directories are found in a separate tree, @enddots{}
19748
19749 The second method is the most general one. It requires an external
19750 program, called @command{find}, which is standard on all Unix systems. All
19751 the directories found under a given root directory will be added to the
19752 list.
19753
19754 @smallexample
19755 @iftex
19756 @leftskip=0cm
19757 @font@heightrm=cmr8
19758 @heightrm
19759 @end iftex
19760 # The examples below are based on the following directory hierarchy:
19761 # All the directories can contain any number of files
19762 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19763 #                       ->  ab
19764 #                       ->  ac
19765 #                ->  b  ->  ba  ->  baa
19766 #                       ->  bb
19767 #                       ->  bc
19768 # This Makefile creates a variable called DIRS, that can be reused any time
19769 # you need this list (see the other examples in this section)
19770
19771 # The root of your project's directory hierarchy
19772 ROOT_DIRECTORY=.
19773
19774 ####
19775 # First method: specify explicitly the list of directories
19776 # This allows you to specify any subset of all the directories you need.
19777 ####
19778
19779 DIRS := a/aa/ a/ab/ b/ba/
19780
19781 ####
19782 # Second method: use wildcards
19783 # Note that the argument(s) to wildcard below should end with a '/'.
19784 # Since wildcards also return file names, we have to filter them out
19785 # to avoid duplicate directory names.
19786 # We thus use make's @code{dir} and @code{sort} functions.
19787 # It sets DIRs to the following value (note that the directories aaa and baa
19788 # are not given, unless you change the arguments to wildcard).
19789 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19790 ####
19791
19792 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19793                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19794
19795 ####
19796 # Third method: use an external program
19797 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19798 # This is the most complete command: it sets DIRs to the following value:
19799 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19800 ####
19801
19802 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19803
19804 @end smallexample
19805
19806 @node Generating the Command Line Switches
19807 @section Generating the Command Line Switches
19808
19809 @noindent
19810 Once you have created the list of directories as explained in the
19811 previous section (@pxref{Automatically Creating a List of Directories}),
19812 you can easily generate the command line arguments to pass to gnatmake.
19813
19814 For the sake of completeness, this example assumes that the source path
19815 is not the same as the object path, and that you have two separate lists
19816 of directories.
19817
19818 @smallexample
19819 # see "Automatically creating a list of directories" to create
19820 # these variables
19821 SOURCE_DIRS=
19822 OBJECT_DIRS=
19823
19824 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19825 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19826
19827 all:
19828         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19829 @end smallexample
19830
19831 @node Overcoming Command Line Length Limits
19832 @section Overcoming Command Line Length Limits
19833
19834 @noindent
19835 One problem that might be encountered on big projects is that many
19836 operating systems limit the length of the command line. It is thus hard to give
19837 gnatmake the list of source and object directories.
19838
19839 This example shows how you can set up environment variables, which will
19840 make @command{gnatmake} behave exactly as if the directories had been
19841 specified on the command line, but have a much higher length limit (or
19842 even none on most systems).
19843
19844 It assumes that you have created a list of directories in your Makefile,
19845 using one of the methods presented in
19846 @ref{Automatically Creating a List of Directories}.
19847 For the sake of completeness, we assume that the object
19848 path (where the ALI files are found) is different from the sources patch.
19849
19850 Note a small trick in the Makefile below: for efficiency reasons, we
19851 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19852 expanded immediately by @code{make}. This way we overcome the standard
19853 make behavior which is to expand the variables only when they are
19854 actually used.
19855
19856 On Windows, if you are using the standard Windows command shell, you must
19857 replace colons with semicolons in the assignments to these variables.
19858
19859 @smallexample
19860 @iftex
19861 @leftskip=0cm
19862 @font@heightrm=cmr8
19863 @heightrm
19864 @end iftex
19865 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19866 # This is the same thing as putting the -I arguments on the command line.
19867 # (the equivalent of using -aI on the command line would be to define
19868 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19869 # You can of course have different values for these variables.
19870 #
19871 # Note also that we need to keep the previous values of these variables, since
19872 # they might have been set before running 'make' to specify where the GNAT
19873 # library is installed.
19874
19875 # see "Automatically creating a list of directories" to create these
19876 # variables
19877 SOURCE_DIRS=
19878 OBJECT_DIRS=
19879
19880 empty:=
19881 space:=$@{empty@} $@{empty@}
19882 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19883 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19884 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19885 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19886 export ADA_INCLUDE_PATH
19887 export ADA_OBJECT_PATH
19888
19889 all:
19890         gnatmake main_unit
19891 @end smallexample
19892 @end ifclear
19893
19894 @node Memory Management Issues
19895 @chapter Memory Management Issues
19896
19897 @noindent
19898 This chapter describes some useful memory pools provided in the GNAT library
19899 and in particular the GNAT Debug Pool facility, which can be used to detect
19900 incorrect uses of access values (including ``dangling references'').
19901 @ifclear vms
19902 It also describes the @command{gnatmem} tool, which can be used to track down
19903 ``memory leaks''.
19904 @end ifclear
19905
19906 @menu
19907 * Some Useful Memory Pools::
19908 * The GNAT Debug Pool Facility::
19909 @ifclear vms
19910 * The gnatmem Tool::
19911 @end ifclear
19912 @end menu
19913
19914 @node Some Useful Memory Pools
19915 @section Some Useful Memory Pools
19916 @findex Memory Pool
19917 @cindex storage, pool
19918
19919 @noindent
19920 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19921 storage pool. Allocations use the standard system call @code{malloc} while
19922 deallocations use the standard system call @code{free}. No reclamation is
19923 performed when the pool goes out of scope. For performance reasons, the
19924 standard default Ada allocators/deallocators do not use any explicit storage
19925 pools but if they did, they could use this storage pool without any change in
19926 behavior. That is why this storage pool is used  when the user
19927 manages to make the default implicit allocator explicit as in this example:
19928 @smallexample @c ada
19929    type T1 is access Something;
19930     -- no Storage pool is defined for T2
19931    type T2 is access Something_Else;
19932    for T2'Storage_Pool use T1'Storage_Pool;
19933    -- the above is equivalent to
19934    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19935 @end smallexample
19936
19937 @noindent
19938 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19939 pool. The allocation strategy is similar to @code{Pool_Local}'s
19940 except that the all
19941 storage allocated with this pool is reclaimed when the pool object goes out of
19942 scope. This pool provides a explicit mechanism similar to the implicit one
19943 provided by several Ada 83 compilers for allocations performed through a local
19944 access type and whose purpose was to reclaim memory when exiting the
19945 scope of a given local access. As an example, the following program does not
19946 leak memory even though it does not perform explicit deallocation:
19947
19948 @smallexample @c ada
19949 with System.Pool_Local;
19950 procedure Pooloc1 is
19951    procedure Internal is
19952       type A is access Integer;
19953       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19954       for A'Storage_Pool use X;
19955       v : A;
19956    begin
19957       for I in  1 .. 50 loop
19958          v := new Integer;
19959       end loop;
19960    end Internal;
19961 begin
19962    for I in  1 .. 100 loop
19963       Internal;
19964    end loop;
19965 end Pooloc1;
19966 @end smallexample
19967
19968 @noindent
19969 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19970 @code{Storage_Size} is specified for an access type.
19971 The whole storage for the pool is
19972 allocated at once, usually on the stack at the point where the access type is
19973 elaborated. It is automatically reclaimed when exiting the scope where the
19974 access type is defined. This package is not intended to be used directly by the
19975 user and it is implicitly used for each such declaration:
19976
19977 @smallexample @c ada
19978    type T1 is access Something;
19979    for T1'Storage_Size use 10_000;
19980 @end smallexample
19981
19982 @node The GNAT Debug Pool Facility
19983 @section The GNAT Debug Pool Facility
19984 @findex Debug Pool
19985 @cindex storage, pool, memory corruption
19986
19987 @noindent
19988 The use of unchecked deallocation and unchecked conversion can easily
19989 lead to incorrect memory references. The problems generated by such
19990 references are usually difficult to tackle because the symptoms can be
19991 very remote from the origin of the problem. In such cases, it is
19992 very helpful to detect the problem as early as possible. This is the
19993 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19994
19995 In order to use the GNAT specific debugging pool, the user must
19996 associate a debug pool object with each of the access types that may be
19997 related to suspected memory problems. See Ada Reference Manual 13.11.
19998 @smallexample @c ada
19999 type Ptr is access Some_Type;
20000 Pool : GNAT.Debug_Pools.Debug_Pool;
20001 for Ptr'Storage_Pool use Pool;
20002 @end smallexample
20003
20004 @noindent
20005 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
20006 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
20007 allow the user to redefine allocation and deallocation strategies. They
20008 also provide a checkpoint for each dereference, through the use of
20009 the primitive operation @code{Dereference} which is implicitly called at
20010 each dereference of an access value.
20011
20012 Once an access type has been associated with a debug pool, operations on
20013 values of the type may raise four distinct exceptions,
20014 which correspond to four potential kinds of memory corruption:
20015 @itemize @bullet
20016 @item
20017 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
20018 @item
20019 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
20020 @item
20021 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
20022 @item
20023 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
20024 @end itemize
20025
20026 @noindent
20027 For types associated with a Debug_Pool, dynamic allocation is performed using
20028 the standard GNAT allocation routine. References to all allocated chunks of
20029 memory are kept in an internal dictionary. Several deallocation strategies are
20030 provided, whereupon the user can choose to release the memory to the system,
20031 keep it allocated for further invalid access checks, or fill it with an easily
20032 recognizable pattern for debug sessions. The memory pattern is the old IBM
20033 hexadecimal convention: @code{16#DEADBEEF#}.
20034
20035 See the documentation in the file g-debpoo.ads for more information on the
20036 various strategies.
20037
20038 Upon each dereference, a check is made that the access value denotes a
20039 properly allocated memory location. Here is a complete example of use of
20040 @code{Debug_Pools}, that includes typical instances of  memory corruption:
20041 @smallexample @c ada
20042 @iftex
20043 @leftskip=0cm
20044 @end iftex
20045 with Gnat.Io; use Gnat.Io;
20046 with Unchecked_Deallocation;
20047 with Unchecked_Conversion;
20048 with GNAT.Debug_Pools;
20049 with System.Storage_Elements;
20050 with Ada.Exceptions; use Ada.Exceptions;
20051 procedure Debug_Pool_Test is
20052
20053    type T is access Integer;
20054    type U is access all T;
20055
20056    P : GNAT.Debug_Pools.Debug_Pool;
20057    for T'Storage_Pool use P;
20058
20059    procedure Free is new Unchecked_Deallocation (Integer, T);
20060    function UC is new Unchecked_Conversion (U, T);
20061    A, B : aliased T;
20062
20063    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20064
20065 begin
20066    Info (P);
20067    A := new Integer;
20068    B := new Integer;
20069    B := A;
20070    Info (P);
20071    Free (A);
20072    begin
20073       Put_Line (Integer'Image(B.all));
20074    exception
20075       when E : others => Put_Line ("raised: " & Exception_Name (E));
20076    end;
20077    begin
20078       Free (B);
20079    exception
20080       when E : others => Put_Line ("raised: " & Exception_Name (E));
20081    end;
20082    B := UC(A'Access);
20083    begin
20084       Put_Line (Integer'Image(B.all));
20085    exception
20086       when E : others => Put_Line ("raised: " & Exception_Name (E));
20087    end;
20088    begin
20089       Free (B);
20090    exception
20091       when E : others => Put_Line ("raised: " & Exception_Name (E));
20092    end;
20093    Info (P);
20094 end Debug_Pool_Test;
20095 @end smallexample
20096
20097 @noindent
20098 The debug pool mechanism provides the following precise diagnostics on the
20099 execution of this erroneous program:
20100 @smallexample
20101 Debug Pool info:
20102   Total allocated bytes :  0
20103   Total deallocated bytes :  0
20104   Current Water Mark:  0
20105   High Water Mark:  0
20106
20107 Debug Pool info:
20108   Total allocated bytes :  8
20109   Total deallocated bytes :  0
20110   Current Water Mark:  8
20111   High Water Mark:  8
20112
20113 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20114 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20115 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20116 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20117 Debug Pool info:
20118   Total allocated bytes :  8
20119   Total deallocated bytes :  4
20120   Current Water Mark:  4
20121   High Water Mark:  8
20122 @end smallexample
20123
20124 @ifclear vms
20125 @node The gnatmem Tool
20126 @section The @command{gnatmem} Tool
20127 @findex gnatmem
20128
20129 @noindent
20130 The @code{gnatmem} utility monitors dynamic allocation and
20131 deallocation activity in a program, and displays information about
20132 incorrect deallocations and possible sources of memory leaks.
20133 It is designed to work in association with a static runtime library
20134 only and in this context provides three types of information:
20135 @itemize @bullet
20136 @item
20137 General information concerning memory management, such as the total
20138 number of allocations and deallocations, the amount of allocated
20139 memory and the high water mark, i.e.@: the largest amount of allocated
20140 memory in the course of program execution.
20141
20142 @item
20143 Backtraces for all incorrect deallocations, that is to say deallocations
20144 which do not correspond to a valid allocation.
20145
20146 @item
20147 Information on each allocation that is potentially the origin of a memory
20148 leak.
20149 @end itemize
20150
20151 @menu
20152 * Running gnatmem::
20153 * Switches for gnatmem::
20154 * Example of gnatmem Usage::
20155 @end menu
20156
20157 @node Running gnatmem
20158 @subsection Running @code{gnatmem}
20159
20160 @noindent
20161 @code{gnatmem} makes use of the output created by the special version of
20162 allocation and deallocation routines that record call information. This
20163 allows to obtain accurate dynamic memory usage history at a minimal cost to
20164 the execution speed. Note however, that @code{gnatmem} is not supported on
20165 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20166 Solaris and Windows NT/2000/XP (x86).
20167
20168 @noindent
20169 The @code{gnatmem} command has the form
20170
20171 @smallexample
20172 @c    $ gnatmem @ovar{switches} user_program
20173 @c Expanding @ovar macro inline (explanation in macro def comments)
20174       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
20175 @end smallexample
20176
20177 @noindent
20178 The program must have been linked with the instrumented version of the
20179 allocation and deallocation routines. This is done by linking with the
20180 @file{libgmem.a} library. For correct symbolic backtrace information,
20181 the user program should be compiled with debugging options
20182 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20183
20184 @smallexample
20185 $ gnatmake -g my_program -largs -lgmem
20186 @end smallexample
20187
20188 @noindent
20189 As library @file{libgmem.a} contains an alternate body for package
20190 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20191 when an executable is linked with library @file{libgmem.a}. It is then not
20192 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20193
20194 @noindent
20195 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20196 This file contains information about all allocations and deallocations
20197 performed by the program. It is produced by the instrumented allocations and
20198 deallocations routines and will be used by @code{gnatmem}.
20199
20200 In order to produce symbolic backtrace information for allocations and
20201 deallocations performed by the GNAT run-time library, you need to use a
20202 version of that library that has been compiled with the @option{-g} switch
20203 (see @ref{Rebuilding the GNAT Run-Time Library}).
20204
20205 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20206 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20207 @option{-i} switch, gnatmem will assume that this file can be found in the
20208 current directory. For example, after you have executed @file{my_program},
20209 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20210
20211 @smallexample
20212 $ gnatmem my_program
20213 @end smallexample
20214
20215 @noindent
20216 This will produce the output with the following format:
20217
20218 *************** debut cc
20219 @smallexample
20220 $ gnatmem my_program
20221
20222 Global information
20223 ------------------
20224    Total number of allocations        :  45
20225    Total number of deallocations      :   6
20226    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20227    High Water Mark                    :  11.40 Kilobytes
20228
20229 .
20230 .
20231 .
20232 Allocation Root # 2
20233 -------------------
20234  Number of non freed allocations    :  11
20235  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20236  High Water Mark                    :   1.27 Kilobytes
20237  Backtrace                          :
20238    my_program.adb:23 my_program.alloc
20239 .
20240 .
20241 .
20242 @end smallexample
20243
20244 The first block of output gives general information. In this case, the
20245 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20246 Unchecked_Deallocation routine occurred.
20247
20248 @noindent
20249 Subsequent paragraphs display  information on all allocation roots.
20250 An allocation root is a specific point in the execution of the program
20251 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20252 construct. This root is represented by an execution backtrace (or subprogram
20253 call stack). By default the backtrace depth for allocations roots is 1, so
20254 that a root corresponds exactly to a source location. The backtrace can
20255 be made deeper, to make the root more specific.
20256
20257 @node Switches for gnatmem
20258 @subsection Switches for @code{gnatmem}
20259
20260 @noindent
20261 @code{gnatmem} recognizes the following switches:
20262
20263 @table @option
20264
20265 @item -q
20266 @cindex @option{-q} (@code{gnatmem})
20267 Quiet. Gives the minimum output needed to identify the origin of the
20268 memory leaks. Omits statistical information.
20269
20270 @item @var{N}
20271 @cindex @var{N} (@code{gnatmem})
20272 N is an integer literal (usually between 1 and 10) which controls the
20273 depth of the backtraces defining allocation root. The default value for
20274 N is 1. The deeper the backtrace, the more precise the localization of
20275 the root. Note that the total number of roots can depend on this
20276 parameter. This parameter must be specified @emph{before} the name of the
20277 executable to be analyzed, to avoid ambiguity.
20278
20279 @item -b n
20280 @cindex @option{-b} (@code{gnatmem})
20281 This switch has the same effect as just depth parameter.
20282
20283 @item -i @var{file}
20284 @cindex @option{-i} (@code{gnatmem})
20285 Do the @code{gnatmem} processing starting from @file{file}, rather than
20286 @file{gmem.out} in the current directory.
20287
20288 @item -m n
20289 @cindex @option{-m} (@code{gnatmem})
20290 This switch causes @code{gnatmem} to mask the allocation roots that have less
20291 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20292 examine even the roots that didn't result in leaks.
20293
20294 @item -s order
20295 @cindex @option{-s} (@code{gnatmem})
20296 This switch causes @code{gnatmem} to sort the allocation roots according to the
20297 specified order of sort criteria, each identified by a single letter. The
20298 currently supported criteria are @code{n, h, w} standing respectively for
20299 number of unfreed allocations, high watermark, and final watermark
20300 corresponding to a specific root. The default order is @code{nwh}.
20301
20302 @end table
20303
20304 @node Example of gnatmem Usage
20305 @subsection Example of @code{gnatmem} Usage
20306
20307 @noindent
20308 The following example shows the use of @code{gnatmem}
20309 on a simple memory-leaking program.
20310 Suppose that we have the following Ada program:
20311
20312 @smallexample @c ada
20313 @group
20314 @cartouche
20315 with Unchecked_Deallocation;
20316 procedure Test_Gm is
20317
20318    type T is array (1..1000) of Integer;
20319    type Ptr is access T;
20320    procedure Free is new Unchecked_Deallocation (T, Ptr);
20321    A : Ptr;
20322
20323    procedure My_Alloc is
20324    begin
20325       A := new T;
20326    end My_Alloc;
20327
20328    procedure My_DeAlloc is
20329       B : Ptr := A;
20330    begin
20331       Free (B);
20332    end My_DeAlloc;
20333
20334 begin
20335    My_Alloc;
20336    for I in 1 .. 5 loop
20337       for J in I .. 5 loop
20338          My_Alloc;
20339       end loop;
20340       My_Dealloc;
20341    end loop;
20342 end;
20343 @end cartouche
20344 @end group
20345 @end smallexample
20346
20347 @noindent
20348 The program needs to be compiled with debugging option and linked with
20349 @code{gmem} library:
20350
20351 @smallexample
20352 $ gnatmake -g test_gm -largs -lgmem
20353 @end smallexample
20354
20355 @noindent
20356 Then we execute the program as usual:
20357
20358 @smallexample
20359 $ test_gm
20360 @end smallexample
20361
20362 @noindent
20363 Then @code{gnatmem} is invoked simply with
20364 @smallexample
20365 $ gnatmem test_gm
20366 @end smallexample
20367
20368 @noindent
20369 which produces the following output (result may vary on different platforms):
20370
20371 @smallexample
20372 Global information
20373 ------------------
20374    Total number of allocations        :  18
20375    Total number of deallocations      :   5
20376    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20377    High Water Mark                    :  56.90 Kilobytes
20378
20379 Allocation Root # 1
20380 -------------------
20381  Number of non freed allocations    :  11
20382  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20383  High Water Mark                    :  46.88 Kilobytes
20384  Backtrace                          :
20385    test_gm.adb:11 test_gm.my_alloc
20386
20387 Allocation Root # 2
20388 -------------------
20389  Number of non freed allocations    :   1
20390  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20391  High Water Mark                    :  10.02 Kilobytes
20392  Backtrace                          :
20393    s-secsta.adb:81 system.secondary_stack.ss_init
20394
20395 Allocation Root # 3
20396 -------------------
20397  Number of non freed allocations    :   1
20398  Final Water Mark (non freed mem)   :  12 Bytes
20399  High Water Mark                    :  12 Bytes
20400  Backtrace                          :
20401    s-secsta.adb:181 system.secondary_stack.ss_init
20402 @end smallexample
20403
20404 @noindent
20405 Note that the GNAT run time contains itself a certain number of
20406 allocations that have no  corresponding deallocation,
20407 as shown here for root #2 and root
20408 #3. This is a normal behavior when the number of non-freed allocations
20409 is one, it allocates dynamic data structures that the run time needs for
20410 the complete lifetime of the program. Note also that there is only one
20411 allocation root in the user program with a single line back trace:
20412 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20413 program shows that 'My_Alloc' is called at 2 different points in the
20414 source (line 21 and line 24). If those two allocation roots need to be
20415 distinguished, the backtrace depth parameter can be used:
20416
20417 @smallexample
20418 $ gnatmem 3 test_gm
20419 @end smallexample
20420
20421 @noindent
20422 which will give the following output:
20423
20424 @smallexample
20425 Global information
20426 ------------------
20427    Total number of allocations        :  18
20428    Total number of deallocations      :   5
20429    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20430    High Water Mark                    :  56.90 Kilobytes
20431
20432 Allocation Root # 1
20433 -------------------
20434  Number of non freed allocations    :  10
20435  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20436  High Water Mark                    :  42.97 Kilobytes
20437  Backtrace                          :
20438    test_gm.adb:11 test_gm.my_alloc
20439    test_gm.adb:24 test_gm
20440    b_test_gm.c:52 main
20441
20442 Allocation Root # 2
20443 -------------------
20444  Number of non freed allocations    :   1
20445  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20446  High Water Mark                    :  10.02 Kilobytes
20447  Backtrace                          :
20448    s-secsta.adb:81  system.secondary_stack.ss_init
20449    s-secsta.adb:283 <system__secondary_stack___elabb>
20450    b_test_gm.c:33   adainit
20451
20452 Allocation Root # 3
20453 -------------------
20454  Number of non freed allocations    :   1
20455  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20456  High Water Mark                    :   3.91 Kilobytes
20457  Backtrace                          :
20458    test_gm.adb:11 test_gm.my_alloc
20459    test_gm.adb:21 test_gm
20460    b_test_gm.c:52 main
20461
20462 Allocation Root # 4
20463 -------------------
20464  Number of non freed allocations    :   1
20465  Final Water Mark (non freed mem)   :  12 Bytes
20466  High Water Mark                    :  12 Bytes
20467  Backtrace                          :
20468    s-secsta.adb:181 system.secondary_stack.ss_init
20469    s-secsta.adb:283 <system__secondary_stack___elabb>
20470    b_test_gm.c:33   adainit
20471 @end smallexample
20472
20473 @noindent
20474 The allocation root #1 of the first example has been split in 2 roots #1
20475 and #3 thanks to the more precise associated backtrace.
20476
20477 @end ifclear
20478
20479 @node Stack Related Facilities
20480 @chapter Stack Related Facilities
20481
20482 @noindent
20483 This chapter describes some useful tools associated with stack
20484 checking and analysis. In
20485 particular, it deals with dynamic and static stack usage measurements.
20486
20487 @menu
20488 * Stack Overflow Checking::
20489 * Static Stack Usage Analysis::
20490 * Dynamic Stack Usage Analysis::
20491 @end menu
20492
20493 @node Stack Overflow Checking
20494 @section Stack Overflow Checking
20495 @cindex Stack Overflow Checking
20496 @cindex -fstack-check
20497
20498 @noindent
20499 For most operating systems, @command{gcc} does not perform stack overflow
20500 checking by default. This means that if the main environment task or
20501 some other task exceeds the available stack space, then unpredictable
20502 behavior will occur. Most native systems offer some level of protection by
20503 adding a guard page at the end of each task stack. This mechanism is usually
20504 not enough for dealing properly with stack overflow situations because
20505 a large local variable could ``jump'' above the guard page.
20506 Furthermore, when the
20507 guard page is hit, there may not be any space left on the stack for executing
20508 the exception propagation code. Enabling stack checking avoids
20509 such situations.
20510
20511 To activate stack checking, compile all units with the gcc option
20512 @option{-fstack-check}. For example:
20513
20514 @smallexample
20515 gcc -c -fstack-check package1.adb
20516 @end smallexample
20517
20518 @noindent
20519 Units compiled with this option will generate extra instructions to check
20520 that any use of the stack (for procedure calls or for declaring local
20521 variables in declare blocks) does not exceed the available stack space.
20522 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20523
20524 For declared tasks, the stack size is controlled by the size
20525 given in an applicable @code{Storage_Size} pragma or by the value specified
20526 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20527 the default size as defined in the GNAT runtime otherwise.
20528
20529 For the environment task, the stack size depends on
20530 system defaults and is unknown to the compiler. Stack checking
20531 may still work correctly if a fixed
20532 size stack is allocated, but this cannot be guaranteed.
20533 @ifclear vms
20534 To ensure that a clean exception is signalled for stack
20535 overflow, set the environment variable
20536 @env{GNAT_STACK_LIMIT} to indicate the maximum
20537 stack area that can be used, as in:
20538 @cindex GNAT_STACK_LIMIT
20539
20540 @smallexample
20541 SET GNAT_STACK_LIMIT 1600
20542 @end smallexample
20543
20544 @noindent
20545 The limit is given in kilobytes, so the above declaration would
20546 set the stack limit of the environment task to 1.6 megabytes.
20547 Note that the only purpose of this usage is to limit the amount
20548 of stack used by the environment task. If it is necessary to
20549 increase the amount of stack for the environment task, then this
20550 is an operating systems issue, and must be addressed with the
20551 appropriate operating systems commands.
20552 @end ifclear
20553 @ifset vms
20554 To have a fixed size stack in the environment task, the stack must be put
20555 in the P0 address space and its size specified.  Use these switches to
20556 create a p0 image:
20557
20558 @smallexample
20559 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20560 @end smallexample
20561
20562 @noindent
20563 The quotes are required to keep case.  The number after @samp{STACK=} is the
20564 size of the environmental task stack in pagelets (512 bytes).  In this example
20565 the stack size is about 2 megabytes.
20566
20567 @noindent
20568 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20569 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20570 more details about the @option{/p0image} qualifier and the @option{stack}
20571 option.
20572 @end ifset
20573
20574 @node Static Stack Usage Analysis
20575 @section Static Stack Usage Analysis
20576 @cindex Static Stack Usage Analysis
20577 @cindex -fstack-usage
20578
20579 @noindent
20580 A unit compiled with @option{-fstack-usage} will generate an extra file
20581 that specifies
20582 the maximum amount of stack used, on a per-function basis.
20583 The file has the same
20584 basename as the target object file with a @file{.su} extension.
20585 Each line of this file is made up of three fields:
20586
20587 @itemize
20588 @item
20589 The name of the function.
20590 @item
20591 A number of bytes.
20592 @item
20593 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20594 @end itemize
20595
20596 The second field corresponds to the size of the known part of the function
20597 frame.
20598
20599 The qualifier @code{static} means that the function frame size
20600 is purely static.
20601 It usually means that all local variables have a static size.
20602 In this case, the second field is a reliable measure of the function stack
20603 utilization.
20604
20605 The qualifier @code{dynamic} means that the function frame size is not static.
20606 It happens mainly when some local variables have a dynamic size. When this
20607 qualifier appears alone, the second field is not a reliable measure
20608 of the function stack analysis. When it is qualified with  @code{bounded}, it
20609 means that the second field is a reliable maximum of the function stack
20610 utilization.
20611
20612 @node Dynamic Stack Usage Analysis
20613 @section Dynamic Stack Usage Analysis
20614
20615 @noindent
20616 It is possible to measure the maximum amount of stack used by a task, by
20617 adding a switch to @command{gnatbind}, as:
20618
20619 @smallexample
20620 $ gnatbind -u0 file
20621 @end smallexample
20622
20623 @noindent
20624 With this option, at each task termination, its stack usage is  output on
20625 @file{stderr}.
20626 It is not always convenient to output the stack usage when the program
20627 is still running. Hence, it is possible to delay this output until program
20628 termination. for a given number of tasks specified as the argument of the
20629 @option{-u} option. For instance:
20630
20631 @smallexample
20632 $ gnatbind -u100 file
20633 @end smallexample
20634
20635 @noindent
20636 will buffer the stack usage information of the first 100 tasks to terminate and
20637 output this info at program termination. Results are displayed in four
20638 columns:
20639
20640 @noindent
20641 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20642
20643 @noindent
20644 where:
20645
20646 @table @emph
20647 @item Index
20648 is a number associated with each task.
20649
20650 @item Task Name
20651 is the name of the task analyzed.
20652
20653 @item Stack Size
20654 is the maximum size for the stack.
20655
20656 @item Stack Usage
20657 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20658 is not entirely analyzed, and it's not possible to know exactly how
20659 much has actually been used. The report thus contains the theoretical stack usage
20660 (Value) and the possible variation (Variation) around this value.
20661
20662 @end table
20663
20664 @noindent
20665 The environment task stack, e.g., the stack that contains the main unit, is
20666 only processed when the environment variable GNAT_STACK_LIMIT is set.
20667
20668
20669 @c *********************************
20670 @c *            GNATCHECK          *
20671 @c *********************************
20672 @node Verifying Properties Using gnatcheck
20673 @chapter Verifying Properties Using @command{gnatcheck}
20674 @findex gnatcheck
20675 @cindex @command{gnatcheck}
20676
20677 @noindent
20678 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20679 of Ada source files according to a given set of semantic rules.
20680 @cindex ASIS
20681
20682 In order to check compliance with a given rule, @command{gnatcheck} has to
20683 semantically analyze the Ada sources.
20684 Therefore, checks can only be performed on
20685 legal Ada units. Moreover, when a unit depends semantically upon units located
20686 outside the current directory, the source search path has to be provided when
20687 calling @command{gnatcheck}, either through a specified project file or
20688 through @command{gnatcheck} switches as described below.
20689
20690 A number of rules are predefined in @command{gnatcheck} and are described
20691 later in this chapter.
20692 You can also add new rules, by modifying the @command{gnatcheck} code and
20693 rebuilding the tool. In order to add a simple rule making some local checks,
20694 a small amount of straightforward ASIS-based programming is usually needed.
20695
20696 Project support for @command{gnatcheck} is provided by the GNAT
20697 driver (see @ref{The GNAT Driver and Project Files}).
20698
20699 Invoking @command{gnatcheck} on the command line has the form:
20700
20701 @smallexample
20702 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
20703 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20704 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20705 @c Expanding @ovar macro inline (explanation in macro def comments)
20706 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
20707       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20708       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20709 @end smallexample
20710
20711 @noindent
20712 where
20713 @itemize @bullet
20714 @item
20715 @var{switches} specify the general tool options
20716
20717 @item
20718 Each @var{filename} is the name (including the extension) of a source
20719 file to process. ``Wildcards'' are allowed, and
20720 the file name may contain path information.
20721
20722 @item
20723 Each @var{arg_list_filename} is the name (including the extension) of a text
20724 file containing the names of the source files to process, separated by spaces
20725 or line breaks.
20726
20727 @item
20728 @var{gcc_switches} is a list of switches for
20729 @command{gcc}. They will be passed on to all compiler invocations made by
20730 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20731 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20732 and use the @option{-gnatec} switch to set the configuration file.
20733
20734 @item
20735 @var{rule_options} is a list of options for controlling a set of
20736 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20737 @end itemize
20738
20739 @noindent
20740 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20741 supplied.
20742
20743 @menu
20744 * Format of the Report File::
20745 * General gnatcheck Switches::
20746 * gnatcheck Rule Options::
20747 * Adding the Results of Compiler Checks to gnatcheck Output::
20748 * Project-Wide Checks::
20749 * Rule exemption::
20750 * Predefined Rules::
20751 * Example of gnatcheck Usage::
20752 @end menu
20753
20754 @node Format of the Report File
20755 @section Format of the Report File
20756 @cindex Report file (for @code{gnatcheck})
20757
20758 @noindent
20759 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20760 rule violations.
20761 It also creates a text file  that
20762 contains the complete report of the last gnatcheck run. By default this file
20763 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20764 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20765 name and/or location of the report file. This report contains:
20766 @itemize @bullet
20767 @item date and time of @command{gnatcheck} run, the version of
20768 the tool that has generated this report and the full parameters
20769 of the  @command{gnatcheck} invocation;
20770 @item list of enabled rules;
20771 @item total number of detected violations;
20772 @item list of source files where rule violations have been detected;
20773 @item list of source files where no violations have been detected.
20774 @end itemize
20775
20776 @node General gnatcheck Switches
20777 @section General @command{gnatcheck} Switches
20778
20779 @noindent
20780 The following switches control the general @command{gnatcheck} behavior
20781
20782 @table @option
20783 @c !sort!
20784 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20785 @item ^-a^/ALL^
20786 Process all units including those with read-only ALI files such as
20787 those from the GNAT Run-Time library.
20788
20789 @ifclear vms
20790 @ignore
20791 @cindex @option{-d} (@command{gnatcheck})
20792 @item -d
20793 Debug mode
20794 @end ignore
20795
20796 @cindex @option{-dd} (@command{gnatcheck})
20797 @item -dd
20798 Progress indicator mode (for use in GPS).
20799 @end ifclear
20800
20801 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20802 @item ^-h^/HELP^
20803 List the predefined and user-defined rules. For more details see
20804 @ref{Predefined Rules}.
20805
20806 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20807 @item ^-l^/LOCS^
20808 Use full source locations references in the report file. For a construct from
20809 a generic instantiation a full source location is a chain from the location
20810 of this construct in the generic unit to the place where this unit is
20811 instantiated.
20812
20813 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20814 @item ^-log^/LOG^
20815 Duplicate all the output sent to @file{stderr} into a log file. The log file
20816 is named @file{gnatcheck.log} and is located in the current directory.
20817
20818 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20819 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20820 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20821 the range 0@dots{}1000;
20822 the default value is 500. Zero means that there is no limitation on
20823 the number of diagnostic messages to be output.
20824
20825 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20826 @item ^-q^/QUIET^
20827 Quiet mode. All the diagnostics about rule violations are placed in the
20828 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20829
20830 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20831 @item ^-s^/SHORT^
20832 Short format of the report file (no version information, no list of applied
20833 rules, no list of checked sources is included)
20834
20835 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
20836 @item ^--include-file^/INCLUDE_FILE^
20837 Append the content of the specified text file to the report file
20838
20839 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20840 @item ^-t^/TIME^
20841 Print out execution time.
20842
20843 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20844 @item ^-v^/VERBOSE^
20845 Verbose mode; @command{gnatcheck} generates version information and then
20846 a trace of sources being processed.
20847
20848 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20849 @item ^-o ^/OUTPUT=^@var{report_file}
20850 Set name of report file file to @var{report_file} .
20851
20852 @end table
20853
20854 @node gnatcheck Rule Options
20855 @section @command{gnatcheck} Rule Options
20856
20857 @noindent
20858 The following options control the processing performed by
20859 @command{gnatcheck}.
20860
20861 @table @option
20862 @cindex @option{+ALL} (@command{gnatcheck})
20863 @item +ALL
20864 Turn all the rule checks ON.
20865
20866 @cindex @option{-ALL} (@command{gnatcheck})
20867 @item -ALL
20868 Turn all the rule checks OFF.
20869
20870 @cindex @option{+R} (@command{gnatcheck})
20871 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20872 Turn on the check for a specified rule with the specified parameter, if any.
20873 @var{rule_id} must be the identifier of one of the currently implemented rules
20874 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20875 are not case-sensitive. The @var{param} item must
20876 be a string representing a valid parameter(s) for the specified rule.
20877 If it contains any space characters then this string must be enclosed in
20878 quotation marks.
20879
20880 @cindex @option{-R} (@command{gnatcheck})
20881 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20882 Turn off the check for a specified rule with the specified parameter, if any.
20883
20884 @cindex @option{-from} (@command{gnatcheck})
20885 @item -from=@var{rule_option_filename}
20886 Read the rule options from the text file @var{rule_option_filename}, referred
20887 to as a ``coding standard file'' below.
20888
20889 @end table
20890
20891 @noindent
20892 The default behavior is that all the rule checks are disabled.
20893
20894 A coding standard file is a text file that contains a set of rule options
20895 described above.
20896 @cindex Coding standard file (for @code{gnatcheck})
20897 The file may contain empty lines and Ada-style comments (comment
20898 lines and end-of-line comments). There can be several rule options on a
20899 single line (separated by a space).
20900
20901 A coding standard file may reference other coding standard files by including
20902 more @option{-from=@var{rule_option_filename}}
20903 options, each such option being replaced with the content of the
20904 corresponding coding standard file during processing. In case a
20905 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20906 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20907 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20908 processing fails with an error message.
20909
20910
20911 @node Adding the Results of Compiler Checks to gnatcheck Output
20912 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20913
20914 @noindent
20915 The @command{gnatcheck} tool can include in the generated diagnostic messages
20916 and in
20917 the report file the results of the checks performed by the compiler. Though
20918 disabled by default, this effect may be obtained by using @option{+R} with
20919 the following rule identifiers and parameters:
20920
20921 @table @option
20922 @item Restrictions
20923 To record restrictions violations (which are performed by the compiler if the
20924 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20925 use the @code{Restrictions} rule
20926 with the same parameters as pragma
20927 @code{Restrictions} or @code{Restriction_Warnings}.
20928
20929 @item Style_Checks
20930 To record compiler style checks (@pxref{Style Checking}), use the
20931 @code{Style_Checks} rule.
20932 This rule takes a parameter in one of the following forms:
20933 @itemize
20934 @item
20935 @code{All_Checks},
20936 which enables the standard style checks corresponding to the @option{-gnatyy}
20937 GNAT style check option, or
20938
20939 @item
20940 a string with the same
20941 structure and semantics as the @code{string_LITERAL} parameter of the
20942 GNAT pragma @code{Style_Checks}
20943 (for further information about this pragma,
20944 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20945 @end itemize
20946
20947 @noindent
20948 For example, the
20949 @code{+RStyle_Checks:O} rule option activates
20950 the compiler style check that corresponds to
20951 @code{-gnatyO} style check option.
20952
20953 @item Warnings
20954 To record compiler warnings (@pxref{Warning Message Control}), use the
20955 @code{Warnings} rule with a parameter that is a valid
20956 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20957 (for further information about this pragma,
20958 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20959 Note that in case of gnatcheck
20960 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20961 all the specific warnings, but not suppresses the warning mode,
20962 and 'e' parameter, corresponding to @option{-gnatwe} that means
20963 "treat warnings as errors", does not have any effect.
20964
20965 @end table
20966
20967 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20968 option with the corresponding restriction name as a parameter. @code{-R} is
20969 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20970 warnings and style checks, use the corresponding warning and style options.
20971
20972 @node Project-Wide Checks
20973 @section Project-Wide Checks
20974 @cindex Project-wide checks (for @command{gnatcheck})
20975
20976 @noindent
20977 In order to perform checks on all units of a given project, you can use
20978 the GNAT driver along with the @option{-P} option:
20979 @smallexample
20980    gnat check -Pproj -rules -from=my_rules
20981 @end smallexample
20982
20983 @noindent
20984 If the project @code{proj} depends upon other projects, you can perform
20985 checks on the project closure using the @option{-U} option:
20986 @smallexample
20987    gnat check -Pproj -U -rules -from=my_rules
20988 @end smallexample
20989
20990 @noindent
20991 Finally, if not all the units are relevant to a particular main
20992 program in the project closure, you can perform checks for the set
20993 of units needed to create a given main program (unit closure) using
20994 the @option{-U} option followed by the name of the main unit:
20995 @smallexample
20996    gnat check -Pproj -U main -rules -from=my_rules
20997 @end smallexample
20998
20999
21000 @node Rule exemption
21001 @section Rule exemption
21002 @cindex Rule exemption (for @command{gnatcheck})
21003
21004 @noindent
21005 One of the most useful applications of @command{gnatcheck} is to
21006 automate the enforcement of project-specific coding standards,
21007 for example in safety-critical systems where particular features
21008 must be restricted in order to simplify the certification effort.
21009 However, it may sometimes be appropriate to violate a coding standard rule,
21010 and in such cases the rationale for the violation should be provided
21011 in the source program itself so that the individuals
21012 reviewing or maintaining the program can immediately understand the intent.
21013
21014 The @command{gnatcheck} tool supports this practice with the notion of
21015 a ``rule exemption'' covering a specific source code section. Normally
21016 rule violation messages are issued both on @file{stderr}
21017 and in a report file. In contrast, exempted violations are not listed on
21018 @file{stderr}; thus users invoking @command{gnatcheck} interactively
21019 (e.g. in its GPS interface) do not need to pay attention to known and
21020 justified violations. However, exempted violations along with their
21021 justification are documented in a special section of the report file that
21022 @command{gnatcheck} generates.
21023
21024 @menu
21025 * Using pragma Annotate to Control Rule Exemption::
21026 * gnatcheck Annotations Rules::
21027 @end menu
21028
21029 @node Using pragma Annotate to Control Rule Exemption
21030 @subsection Using pragma @code{Annotate} to Control Rule Exemption
21031 @cindex Using pragma Annotate to control rule exemption
21032
21033 @noindent
21034 Rule exemption is controlled by pragma @code{Annotate} when its first
21035 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21036 exemption control annotations is as follows:
21037
21038 @smallexample @c ada
21039 @group
21040 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21041
21042 @i{exemption_control} ::= Exempt_On | Exempt_Off
21043
21044 @i{Rule_Name}         ::= string_literal
21045
21046 @i{justification}     ::= string_literal
21047 @end group
21048 @end smallexample
21049
21050 @noindent
21051 When a @command{gnatcheck} annotation has more then four arguments,
21052 @command{gnatcheck} issues a warning and ignores the additional arguments.
21053 If the additional arguments do not follow the syntax above,
21054 @command{gnatcheck} emits a warning and ignores the annotation.
21055
21056 The @i{@code{Rule_Name}} argument should be the name of some existing
21057 @command{gnatcheck} rule.
21058 Otherwise a warning message is generated and the pragma is
21059 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21060 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21061
21062 A source code section where an exemption is active for a given rule is
21063 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21064
21065 @smallexample @c ada
21066 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
21067 -- source code section
21068 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
21069 @end smallexample
21070
21071
21072 @node gnatcheck Annotations Rules
21073 @subsection @command{gnatcheck} Annotations Rules
21074 @cindex @command{gnatcheck} annotations rules
21075
21076 @itemize @bullet
21077
21078 @item
21079 An ``Exempt_Off'' annotation can only appear after a corresponding
21080 ``Exempt_On'' annotation.
21081
21082 @item
21083 Exempted source code sections are only based on the source location of the
21084 annotations. Any source construct between the two
21085 annotations is part of the exempted source code section.
21086
21087 @item
21088 Exempted source code sections for different rules are independent. They can
21089 be nested or intersect with one another without limitation.
21090 Creating nested or intersecting source code sections for the same rule is
21091 not allowed.
21092
21093 @item
21094 Malformed exempted source code sections are reported by a warning, and
21095 the corresponding rule exemptions are ignored.
21096
21097 @item
21098 When an exempted source code section does not contain at least one violation
21099 of the exempted rule, a warning is emitted on @file{stderr}.
21100
21101 @item
21102 If an ``Exempt_On'' annotation pragma does not have a matching
21103 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21104 exemption for the given rule is ignored and a warning is issued.
21105 @end itemize
21106
21107
21108 @node Predefined Rules
21109 @section Predefined Rules
21110 @cindex Predefined rules (for @command{gnatcheck})
21111
21112 @ignore
21113 @c (Jan 2007) Since the global rules are still under development and are not
21114 @c documented, there is no point in explaining the difference between
21115 @c global and local rules
21116 @noindent
21117 A rule in @command{gnatcheck} is either local or global.
21118 A @emph{local rule} is a rule that applies to a well-defined section
21119 of a program and that can be checked by analyzing only this section.
21120 A @emph{global rule} requires analysis of some global properties of the
21121 whole program (mostly related to the program call graph).
21122 As of @value{NOW}, the implementation of global rules should be
21123 considered to be at a preliminary stage. You can use the
21124 @option{+GLOBAL} option to enable all the global rules, and the
21125 @option{-GLOBAL} rule option to disable all the global rules.
21126
21127 All the global rules in the list below are
21128 so indicated by marking them ``GLOBAL''.
21129 This +GLOBAL and -GLOBAL options are not
21130 included in the list of gnatcheck options above, because at the moment they
21131 are considered as a temporary debug options.
21132
21133 @command{gnatcheck} performs rule checks for generic
21134 instances only for global rules.  This limitation may be relaxed in a later
21135 release.
21136 @end ignore
21137
21138 @noindent
21139 The following subsections document the rules implemented in
21140 @command{gnatcheck}.
21141 The subsection title is the same as the rule identifier, which may be
21142 used as a parameter of the @option{+R} or @option{-R} options.
21143
21144
21145 @menu
21146 * Abstract_Type_Declarations::
21147 * Anonymous_Arrays::
21148 * Anonymous_Subtypes::
21149 * Blocks::
21150 * Boolean_Relational_Operators::
21151 @ignore
21152 * Ceiling_Violations::
21153 @end ignore
21154 * Complex_Inlined_Subprograms::
21155 * Controlled_Type_Declarations::
21156 * Declarations_In_Blocks::
21157 * Deep_Inheritance_Hierarchies::
21158 * Deeply_Nested_Generics::
21159 * Deeply_Nested_Inlining::
21160 @ignore
21161 * Deeply_Nested_Local_Inlining::
21162 @end ignore
21163 * Default_Parameters::
21164 * Direct_Calls_To_Primitives::
21165 * Discriminated_Records::
21166 * Enumeration_Ranges_In_CASE_Statements::
21167 * Exceptions_As_Control_Flow::
21168 * Exits_From_Conditional_Loops::
21169 * EXIT_Statements_With_No_Loop_Name::
21170 * Expanded_Loop_Exit_Names::
21171 * Explicit_Full_Discrete_Ranges::
21172 * Float_Equality_Checks::
21173 * Forbidden_Attributes::
21174 * Forbidden_Pragmas::
21175 * Function_Style_Procedures::
21176 * Generics_In_Subprograms::
21177 * GOTO_Statements::
21178 * Implicit_IN_Mode_Parameters::
21179 * Implicit_SMALL_For_Fixed_Point_Types::
21180 * Improperly_Located_Instantiations::
21181 * Improper_Returns::
21182 * Library_Level_Subprograms::
21183 * Local_Packages::
21184 @ignore
21185 * Improperly_Called_Protected_Entries::
21186 @end ignore
21187 * Metrics::
21188 * Misnamed_Controlling_Parameters::
21189 * Misnamed_Identifiers::
21190 * Multiple_Entries_In_Protected_Definitions::
21191 * Name_Clashes::
21192 * Non_Qualified_Aggregates::
21193 * Non_Short_Circuit_Operators::
21194 * Non_SPARK_Attributes::
21195 * Non_Tagged_Derived_Types::
21196 * Non_Visible_Exceptions::
21197 * Numeric_Literals::
21198 * OTHERS_In_Aggregates::
21199 * OTHERS_In_CASE_Statements::
21200 * OTHERS_In_Exception_Handlers::
21201 * Outer_Loop_Exits::
21202 * Overloaded_Operators::
21203 * Overly_Nested_Control_Structures::
21204 * Parameters_Out_Of_Order::
21205 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21206 * Positional_Actuals_For_Defaulted_Parameters::
21207 * Positional_Components::
21208 * Positional_Generic_Parameters::
21209 * Positional_Parameters::
21210 * Predefined_Numeric_Types::
21211 * Raising_External_Exceptions::
21212 * Raising_Predefined_Exceptions::
21213 * Separate_Numeric_Error_Handlers::
21214 @ignore
21215 * Recursion::
21216 * Side_Effect_Functions::
21217 @end ignore
21218 * Slices::
21219 * Too_Many_Parents::
21220 * Unassigned_OUT_Parameters::
21221 * Uncommented_BEGIN_In_Package_Bodies::
21222 * Unconditional_Exits::
21223 * Unconstrained_Array_Returns::
21224 * Universal_Ranges::
21225 * Unnamed_Blocks_And_Loops::
21226 @ignore
21227 * Unused_Subprograms::
21228 @end ignore
21229 * USE_PACKAGE_Clauses::
21230 * Visible_Components::
21231 * Volatile_Objects_Without_Address_Clauses::
21232 @end menu
21233
21234
21235 @node Abstract_Type_Declarations
21236 @subsection @code{Abstract_Type_Declarations}
21237 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21238
21239 @noindent
21240 Flag all declarations of abstract types. For an abstract private
21241 type, both the private and full type declarations are flagged.
21242
21243 This rule has no parameters.
21244
21245
21246 @node Anonymous_Arrays
21247 @subsection @code{Anonymous_Arrays}
21248 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21249
21250 @noindent
21251 Flag all anonymous array type definitions (by Ada semantics these can only
21252 occur in object declarations).
21253
21254 This rule has no parameters.
21255
21256 @node Anonymous_Subtypes
21257 @subsection @code{Anonymous_Subtypes}
21258 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21259
21260 @noindent
21261 Flag all uses of anonymous subtypes (except cases when subtype indication
21262 is a part of a record component definition, and this subtype indication
21263 depends on a discriminant). A use of an anonymous subtype is
21264 any instance of a subtype indication with a constraint, other than one
21265 that occurs immediately within a subtype declaration. Any use of a range
21266 other than as a constraint used immediately within a subtype declaration
21267 is considered as an anonymous subtype.
21268
21269 An effect of this rule is that @code{for} loops such as the following are
21270 flagged (since @code{1..N} is formally a ``range''):
21271
21272 @smallexample @c ada
21273 for I in 1 .. N loop
21274    @dots{}
21275 end loop;
21276 @end smallexample
21277
21278 @noindent
21279 Declaring an explicit subtype solves the problem:
21280
21281 @smallexample @c ada
21282 subtype S is Integer range 1..N;
21283 @dots{}
21284 for I in S loop
21285    @dots{}
21286 end loop;
21287 @end smallexample
21288
21289 @noindent
21290 This rule has no parameters.
21291
21292 @node Blocks
21293 @subsection @code{Blocks}
21294 @cindex @code{Blocks} rule (for @command{gnatcheck})
21295
21296 @noindent
21297 Flag each block statement.
21298
21299 This rule has no parameters.
21300
21301 @node Boolean_Relational_Operators
21302 @subsection @code{Boolean_Relational_Operators}
21303 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21304
21305 @noindent
21306 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21307 ``>='', ``='' and ``/='') for the predefined Boolean type.
21308 (This rule is useful in enforcing the SPARK language restrictions.)
21309
21310 Calls to predefined relational operators of any type derived from
21311 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21312 with these designators, and uses of operators that are renamings
21313 of the predefined relational operators for @code{Standard.Boolean},
21314 are likewise not detected.
21315
21316 This rule has no parameters.
21317
21318 @ignore
21319 @node Ceiling_Violations
21320 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21321 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21322
21323 @noindent
21324 Flag invocations of a protected operation by a task whose priority exceeds
21325 the protected object's ceiling.
21326
21327 As of @value{NOW}, this rule has the following limitations:
21328
21329 @itemize @bullet
21330
21331 @item
21332  We consider only pragmas Priority and Interrupt_Priority as means to define
21333   a task/protected operation priority. We do not consider the effect of using
21334   Ada.Dynamic_Priorities.Set_Priority procedure;
21335
21336 @item
21337  We consider only base task priorities, and no priority inheritance. That is,
21338   we do not make a difference between calls issued during task activation and
21339   execution of the sequence of statements from task body;
21340
21341 @item
21342  Any situation when the priority of protected operation caller is set by a
21343   dynamic expression (that is, the corresponding Priority or
21344   Interrupt_Priority pragma has a non-static expression as an argument) we
21345   treat as a priority inconsistency (and, therefore, detect this situation).
21346 @end itemize
21347
21348 @noindent
21349 At the moment the notion of the main subprogram is not implemented in
21350 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21351 if this subprogram can be a main subprogram of a partition) changes the
21352 priority of an environment task. So if we have more then one such pragma in
21353 the set of processed sources, the pragma that is processed last, defines the
21354 priority of an environment task.
21355
21356 This rule has no parameters.
21357 @end ignore
21358
21359 @node Controlled_Type_Declarations
21360 @subsection @code{Controlled_Type_Declarations}
21361 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21362
21363 @noindent
21364 Flag all declarations of controlled types. A declaration of a private type
21365 is flagged if its full declaration declares a controlled type. A declaration
21366 of a derived type is flagged if its ancestor type is controlled. Subtype
21367 declarations are not checked. A declaration of a type that itself is not a
21368 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21369 component is not checked.
21370
21371 This rule has no parameters.
21372
21373
21374 @node Complex_Inlined_Subprograms
21375 @subsection @code{Complex_Inlined_Subprograms}
21376 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21377
21378 @noindent
21379 Flags a subprogram (or generic subprogram) if
21380 pragma Inline is applied to the subprogram and at least one of the following
21381 conditions is met:
21382
21383 @itemize @bullet
21384 @item
21385 it contains at least one complex declaration such as a subprogram body,
21386 package, task, protected declaration, or a generic instantiation
21387 (except instantiation of @code{Ada.Unchecked_Conversion});
21388
21389 @item
21390 it contains at least one complex statement such as a loop, a case
21391 or a if statement, or a short circuit control form;
21392
21393 @item
21394 the number of statements exceeds
21395 a value specified by the @option{N} rule parameter;
21396 @end itemize
21397
21398 @noindent
21399 This rule has the following (mandatory) parameter for the @option{+R} option:
21400
21401 @table @emph
21402 @item N
21403 Positive integer specifying the maximum allowed total number of statements
21404 in the subprogram body.
21405 @end table
21406
21407
21408 @node Declarations_In_Blocks
21409 @subsection @code{Declarations_In_Blocks}
21410 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21411
21412 @noindent
21413 Flag all block statements containing local declarations. A @code{declare}
21414 block with an empty @i{declarative_part} or with a @i{declarative part}
21415 containing only pragmas and/or @code{use} clauses is not flagged.
21416
21417 This rule has no parameters.
21418
21419
21420 @node Deep_Inheritance_Hierarchies
21421 @subsection @code{Deep_Inheritance_Hierarchies}
21422 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21423
21424 @noindent
21425 Flags a tagged derived type declaration or an interface type declaration if
21426 its depth (in its inheritance
21427 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21428
21429 The inheritance depth of a tagged type or interface type is defined as 0 for
21430 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21431 depths of the immediate parent and immediate progenitors.
21432
21433 This rule does not flag private extension
21434 declarations. In the case of a private extension, the corresponding full
21435 declaration is checked.
21436
21437 This rule has the following (mandatory) parameter for the @option{+R} option:
21438
21439 @table @emph
21440 @item N
21441 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21442 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21443 of tagged and interface types.
21444 @end table
21445
21446
21447 @node Deeply_Nested_Generics
21448 @subsection @code{Deeply_Nested_Generics}
21449 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21450
21451 @noindent
21452 Flags a generic declaration nested in another generic declaration if
21453 the nesting level of the inner generic exceeds
21454 a value specified by the @option{N} rule parameter.
21455 The nesting level is the number of generic declaratons that enclose the given
21456 (generic) declaration. Formal packages are not flagged by this rule.
21457
21458 This rule has the following (mandatory) parameters for the @option{+R} option:
21459
21460 @table @emph
21461 @item N
21462 Positive integer specifying the maximal allowed nesting level
21463 for a generic declaration.
21464 @end table
21465
21466 @node Deeply_Nested_Inlining
21467 @subsection @code{Deeply_Nested_Inlining}
21468 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21469
21470 @noindent
21471 Flags a subprogram (or generic subprogram) if
21472 pragma Inline has been applied to the subprogram but the subprogram
21473 calls to another inlined subprogram that results in nested inlining
21474 with nesting depth exceeding the value specified by the
21475 @option{N} rule parameter.
21476
21477 This rule requires the global analysis of all the compilation units that
21478 are @command{gnatcheck} arguments; such analysis may affect the tool's
21479 performance.
21480
21481 This rule has the following (mandatory) parameter for the @option{+R} option:
21482
21483 @table @emph
21484 @item N
21485 Positive integer specifying the maximal allowed level of nested inlining.
21486 @end table
21487
21488
21489 @ignore
21490 @node Deeply_Nested_Local_Inlining
21491 @subsection @code{Deeply_Nested_Local_Inlining}
21492 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21493
21494 @noindent
21495 Flags a subprogram body if a pragma @code{Inline} is applied to the
21496 corresponding subprogram (or generic subprogram) and the body contains a call
21497 to another inlined subprogram that results in nested inlining with nesting
21498 depth more then a value specified by the @option{N} rule parameter.
21499 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21500 assumes that calls to subprograms in
21501 with'ed units are not inlided, so all the analysis of the depth of inlining is
21502 limited by the compilation unit where the subprogram body is located and the
21503 units it depends semantically upon. Such analysis may be usefull for the case
21504 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21505 the executable.
21506
21507 This rule has the following (mandatory) parameters for the @option{+R} option:
21508
21509 @table @emph
21510 @item N
21511 Positive integer specifying the maximal allowed level of nested inlining.
21512 @end table
21513
21514 @end ignore
21515
21516 @node Default_Parameters
21517 @subsection @code{Default_Parameters}
21518 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21519
21520 @noindent
21521 Flag all default expressions for subprogram parameters. Parameter
21522 declarations of formal and generic subprograms are also checked.
21523
21524 This rule has no parameters.
21525
21526
21527 @node Direct_Calls_To_Primitives
21528 @subsection @code{Direct_Calls_To_Primitives}
21529 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21530
21531 @noindent
21532 Flags any non-dispatching call to a dispatching primitive operation, except
21533 for the common idiom where a primitive subprogram for a tagged type
21534 directly calls the same primitive subprogram of the type's immediate ancestor.
21535
21536 This rule has no parameters.
21537
21538
21539 @node Discriminated_Records
21540 @subsection @code{Discriminated_Records}
21541 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21542
21543 @noindent
21544 Flag all declarations of record types with discriminants. Only the
21545 declarations of record and record extension types are checked. Incomplete,
21546 formal, private, derived and private extension type declarations are not
21547 checked. Task and protected type declarations also are not checked.
21548
21549 This rule has no parameters.
21550
21551
21552 @node Enumeration_Ranges_In_CASE_Statements
21553 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21554 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21555
21556 @noindent
21557 Flag each use of a range of enumeration literals as a choice in a
21558 @code{case} statement.
21559 All forms for specifying a range (explicit ranges
21560 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21561 An enumeration range is
21562 flagged even if contains exactly one enumeration value or no values at all. A
21563 type derived from an enumeration type is considered as an enumeration type.
21564
21565 This rule helps prevent maintenance problems arising from adding an
21566 enumeration value to a type and having it implicitly handled by an existing
21567 @code{case} statement with an enumeration range that includes the new literal.
21568
21569 This rule has no parameters.
21570
21571
21572 @node Exceptions_As_Control_Flow
21573 @subsection @code{Exceptions_As_Control_Flow}
21574 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21575
21576 @noindent
21577 Flag each place where an exception is explicitly raised and handled in the
21578 same subprogram body. A @code{raise} statement in an exception handler,
21579 package body, task body or entry body is not flagged.
21580
21581 The rule has no parameters.
21582
21583 @node Exits_From_Conditional_Loops
21584 @subsection @code{Exits_From_Conditional_Loops}
21585 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21586
21587 @noindent
21588 Flag any exit statement if it transfers the control out of a @code{for} loop
21589 or a @code{while} loop. This includes cases when the @code{exit} statement
21590 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21591 in some @code{for} or @code{while} loop, but transfers the control from some
21592 outer (inconditional) @code{loop} statement.
21593
21594 The rule has no parameters.
21595
21596
21597 @node EXIT_Statements_With_No_Loop_Name
21598 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21599 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21600
21601 @noindent
21602 Flag each @code{exit} statement that does not specify the name of the loop
21603 being exited.
21604
21605 The rule has no parameters.
21606
21607
21608 @node Expanded_Loop_Exit_Names
21609 @subsection @code{Expanded_Loop_Exit_Names}
21610 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21611
21612 @noindent
21613 Flag all expanded loop names in @code{exit} statements.
21614
21615 This rule has no parameters.
21616
21617 @node Explicit_Full_Discrete_Ranges
21618 @subsection @code{Explicit_Full_Discrete_Ranges}
21619 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21620
21621 @noindent
21622 Flag each discrete range that has the form @code{A'First .. A'Last}.
21623
21624 This rule has no parameters.
21625
21626 @node Float_Equality_Checks
21627 @subsection @code{Float_Equality_Checks}
21628 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21629
21630 @noindent
21631 Flag all calls to the predefined equality operations for floating-point types.
21632 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21633 User-defined equality operations are not flagged, nor are ``@code{=}''
21634 and ``@code{/=}'' operations for fixed-point types.
21635
21636 This rule has no parameters.
21637
21638
21639 @node Forbidden_Attributes
21640 @subsection @code{Forbidden_Attributes}
21641 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21642
21643 @noindent
21644 Flag each use of the specified attributes. The attributes to be detected are
21645 named in the rule's parameters.
21646
21647 This rule has the following parameters:
21648
21649 @itemize @bullet
21650 @item For the @option{+R} option
21651
21652 @table @asis
21653 @item @emph{Attribute_Designator}
21654 Adds the specified attribute to the set of attributes to be detected and sets
21655 the detection checks for all the specified attributes ON.
21656 If @emph{Attribute_Designator}
21657 does not denote any attribute defined in the Ada standard
21658 or in
21659 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21660 Manual}, it is treated as the name of unknown attribute.
21661
21662 @item @code{GNAT}
21663 All the GNAT-specific attributes are detected; this sets
21664 the detection checks for all the specified attributes ON.
21665
21666 @item @code{ALL}
21667 All attributes are detected; this sets the rule ON.
21668 @end table
21669
21670 @item For the @option{-R} option
21671 @table @asis
21672 @item @emph{Attribute_Designator}
21673 Removes the specified attribute from the set of attributes to be
21674 detected without affecting detection checks for
21675 other attributes. If @emph{Attribute_Designator} does not correspond to any
21676 attribute defined in the Ada standard or in
21677 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21678 this option is treated as turning OFF detection of all unknown attributes.
21679
21680 @item GNAT
21681 Turn OFF detection of all GNAT-specific attributes
21682
21683 @item ALL
21684 Clear the list of the attributes to be detected and
21685 turn the rule OFF.
21686 @end table
21687 @end itemize
21688
21689 @noindent
21690 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21691 have the syntax of an Ada identifier and therefore can not be considered as a
21692 (part of an) attribute designator, a diagnostic message is generated and the
21693 corresponding parameter is ignored. (If an attribute allows a static
21694 expression to be a part of the attribute designator, this expression is
21695 ignored by this rule.)
21696
21697 When more then one parameter is given in the same rule option, the parameters
21698 must be separated by commas.
21699
21700 If more then one option for this rule is specified for the gnatcheck call, a
21701 new option overrides the previous one(s).
21702
21703 The @option{+R} option with no parameters turns the rule ON, with the set of
21704 attributes to be detected defined by the previous rule options.
21705 (By default this set is empty, so if the only option specified for the rule is
21706 @option{+RForbidden_Attributes} (with
21707 no parameter), then the rule is enabled, but it does not detect anything).
21708 The @option{-R} option with no parameter turns the rule OFF, but it does not
21709 affect the set of attributes to be detected.
21710
21711
21712 @node Forbidden_Pragmas
21713 @subsection @code{Forbidden_Pragmas}
21714 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21715
21716 @noindent
21717 Flag each use of the specified pragmas.  The pragmas to be detected
21718 are named in the rule's  parameters.
21719
21720 This rule has the following parameters:
21721
21722 @itemize @bullet
21723 @item For the @option{+R} option
21724
21725 @table @asis
21726 @item @emph{Pragma_Name}
21727 Adds the specified pragma to the set of pragmas to be
21728 checked and sets the checks for all the specified pragmas
21729 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21730 does not correspond to any pragma name defined in the Ada
21731 standard or to the name of a GNAT-specific pragma defined
21732 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21733 Manual}, it is treated as the name of unknown pragma.
21734
21735 @item @code{GNAT}
21736 All the GNAT-specific pragmas are detected; this sets
21737 the checks for all the specified pragmas ON.
21738
21739 @item @code{ALL}
21740 All pragmas are detected; this sets the rule ON.
21741 @end table
21742
21743 @item For the @option{-R} option
21744 @table @asis
21745 @item @emph{Pragma_Name}
21746 Removes the specified pragma from the set of pragmas to be
21747 checked without affecting checks for
21748 other pragmas. @emph{Pragma_Name} is treated as a name
21749 of a pragma. If it does not correspond to any pragma
21750 defined in the Ada standard or to any name defined in
21751 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21752 this option is treated as turning OFF detection of all unknown pragmas.
21753
21754 @item GNAT
21755 Turn OFF detection of all GNAT-specific pragmas
21756
21757 @item ALL
21758 Clear the list of the pragmas to be detected and
21759 turn the rule OFF.
21760 @end table
21761 @end itemize
21762
21763 @noindent
21764 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21765 the syntax of an Ada identifier and therefore can not be considered
21766 as a pragma name, a diagnostic message is generated and the corresponding
21767 parameter is ignored.
21768
21769 When more then one parameter is given in the same rule option, the parameters
21770 must be separated by a comma.
21771
21772 If more then one option for this rule is specified for the @command{gnatcheck}
21773 call, a new option overrides the previous one(s).
21774
21775 The @option{+R} option with no parameters turns the rule ON with the set of
21776 pragmas to be detected defined by the previous rule options.
21777 (By default this set is empty, so if the only option specified for the rule is
21778 @option{+RForbidden_Pragmas} (with
21779 no parameter), then the rule is enabled, but it does not detect anything).
21780 The @option{-R} option with no parameter turns the rule OFF, but it does not
21781 affect the set of pragmas to be detected.
21782
21783
21784
21785
21786 @node Function_Style_Procedures
21787 @subsection @code{Function_Style_Procedures}
21788 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21789
21790 @noindent
21791 Flag each procedure that can be rewritten as a function. A procedure can be
21792 converted into a function if it has exactly one parameter of mode @code{out}
21793 and no parameters of mode @code{in out}. Procedure declarations,
21794 formal procedure declarations, and generic procedure declarations are always
21795 checked. Procedure
21796 bodies and body stubs are flagged only if they do not have corresponding
21797 separate declarations. Procedure renamings and procedure instantiations are
21798 not flagged.
21799
21800 If a procedure can be rewritten as a function, but its @code{out} parameter is
21801 of a limited type, it is not flagged.
21802
21803 Protected procedures are not flagged. Null procedures also are not flagged.
21804
21805 This rule has no parameters.
21806
21807
21808 @node Generics_In_Subprograms
21809 @subsection @code{Generics_In_Subprograms}
21810 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21811
21812 @noindent
21813 Flag each declaration of a generic unit in a subprogram. Generic
21814 declarations in the bodies of generic subprograms are also flagged.
21815 A generic unit nested in another generic unit is not flagged.
21816 If a generic unit is
21817 declared in a local package that is declared in a subprogram body, the
21818 generic unit is flagged.
21819
21820 This rule has no parameters.
21821
21822
21823 @node GOTO_Statements
21824 @subsection @code{GOTO_Statements}
21825 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21826
21827 @noindent
21828 Flag each occurrence of a @code{goto} statement.
21829
21830 This rule has no parameters.
21831
21832
21833 @node Implicit_IN_Mode_Parameters
21834 @subsection @code{Implicit_IN_Mode_Parameters}
21835 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21836
21837 @noindent
21838 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21839 Note that @code{access} parameters, although they technically behave
21840 like @code{in} parameters, are not flagged.
21841
21842 This rule has no parameters.
21843
21844
21845 @node Implicit_SMALL_For_Fixed_Point_Types
21846 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21847 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21848
21849 @noindent
21850 Flag each fixed point type declaration that lacks an explicit
21851 representation  clause to define its @code{'Small} value.
21852 Since @code{'Small} can be  defined only for ordinary fixed point types,
21853 decimal fixed point type declarations are not checked.
21854
21855 This rule has no parameters.
21856
21857
21858 @node Improperly_Located_Instantiations
21859 @subsection @code{Improperly_Located_Instantiations}
21860 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21861
21862 @noindent
21863 Flag all generic instantiations in library-level package specs
21864 (including library generic packages) and in all subprogram bodies.
21865
21866 Instantiations in task and entry bodies are not flagged. Instantiations in the
21867 bodies of protected subprograms are flagged.
21868
21869 This rule has no parameters.
21870
21871
21872
21873 @node Improper_Returns
21874 @subsection @code{Improper_Returns}
21875 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21876
21877 @noindent
21878 Flag each explicit @code{return} statement in procedures, and
21879 multiple @code{return} statements in functions.
21880 Diagnostic messages are generated for all @code{return} statements
21881 in a procedure (thus each procedure must be written so that it
21882 returns implicitly at the end of its statement part),
21883 and for all @code{return} statements in a function after the first one.
21884 This rule supports the stylistic convention that each subprogram
21885 should have no more than one point of normal return.
21886
21887 This rule has no parameters.
21888
21889
21890 @node Library_Level_Subprograms
21891 @subsection @code{Library_Level_Subprograms}
21892 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21893
21894 @noindent
21895 Flag all library-level subprograms (including generic subprogram instantiations).
21896
21897 This rule has no parameters.
21898
21899
21900 @node Local_Packages
21901 @subsection @code{Local_Packages}
21902 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21903
21904 @noindent
21905 Flag all local packages declared in package and generic package
21906 specs.
21907 Local packages in bodies are not flagged.
21908
21909 This rule has no parameters.
21910
21911 @ignore
21912 @node Improperly_Called_Protected_Entries
21913 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21914 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21915
21916 @noindent
21917 Flag each protected entry that can be called from more than one task.
21918
21919 This rule has no parameters.
21920 @end ignore
21921
21922 @node Metrics
21923 @subsection @code{Metrics}
21924 @cindex @code{Metrics} rule (for @command{gnatcheck})
21925
21926 @noindent
21927 There is a set of checks based on computing a metric value and comparing the
21928 result with the specified upper (or lower, depending on a specific metric)
21929 value specified for a given metric. A construct is flagged if a given metric
21930 is applicable (can be computed) for it and the computed value is greater
21931 then (lover then) the specified upper (lower) bound.
21932
21933 The name of any metric-based rule consists of the prefix @code{Metrics_}
21934 followed by the name of the corresponding metric (see the table below).
21935 For @option{+R} option, each metric-based rule has a numeric parameter
21936 specifying the bound (integer or real, depending on a metric), @option{-R}
21937 option for metric rules does not have a parameter.
21938
21939 The following table shows the metric names for that the corresponding
21940 metrics-based checks are supported by gnatcheck, including the
21941 constraint that must be satisfied by the bound that is specified for the check
21942 and what bound - upper (U) or lower (L) - should be specified.
21943
21944 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21945 @ifnothtml
21946 @headitem Check Name @tab Description @tab Bounds Value
21947 @end ifnothtml
21948 @ifhtml
21949 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21950 @end ifhtml
21951 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21952 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21953 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21954 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21955 @end multitable
21956
21957 @noindent
21958 The meaning and the computed values for all these metrics are exactly
21959 the same as for the corresponding metrics in @command{gnatmetric}.
21960
21961 @emph{Example:} the rule
21962 @smallexample
21963 +RMetrics_Cyclomatic_Complexity : 7
21964 @end smallexample
21965 @noindent
21966 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21967
21968 To turn OFF the check for cyclomatic complexity metric, use the following option:
21969 @smallexample
21970 -RMetrics_Cyclomatic_Complexity
21971 @end smallexample
21972
21973
21974 @node Misnamed_Controlling_Parameters
21975 @subsection @code{Misnamed_Controlling_Parameters}
21976 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21977
21978 @noindent
21979 Flags a declaration of a dispatching operation, if the first parameter is
21980 not a controlling one and its name is not @code{This} (the check for
21981 parameter name is not case-sensitive). Declarations of dispatching functions
21982 with controlling result and no controlling parameter are never flagged.
21983
21984 A subprogram body declaration, subprogram renaming declaration or subprogram
21985 body stub is flagged only if it is not a completion of a prior subprogram
21986 declaration.
21987
21988 This rule has no parameters.
21989
21990
21991
21992 @node Misnamed_Identifiers
21993 @subsection @code{Misnamed_Identifiers}
21994 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21995
21996 @noindent
21997 Flag the declaration of each identifier that does not have a suffix
21998 corresponding to the kind of entity being declared.
21999 The following declarations are checked:
22000
22001 @itemize @bullet
22002 @item
22003 type declarations
22004
22005 @item
22006 subtype declarations
22007
22008 @item
22009 constant declarations (but not number declarations)
22010
22011 @item
22012 package renaming declarations (but not generic package renaming
22013 declarations)
22014 @end itemize
22015
22016 @noindent
22017 This rule may have parameters. When used without parameters, the rule enforces
22018 the following checks:
22019
22020 @itemize @bullet
22021 @item
22022 type-defining names end with @code{_T}, unless the type is an access type,
22023 in which case the suffix must be @code{_A}
22024 @item
22025 constant names end with @code{_C}
22026 @item
22027 names defining package renamings end with @code{_R}
22028 @end itemize
22029
22030 @noindent
22031 Defining identifiers from incomplete type declarations are never flagged.
22032
22033 For a private type declaration (including private extensions), the defining
22034 identifier from the private type declaration is checked against the type
22035 suffix (even if the corresponding full declaration is an access type
22036 declaration), and the defining identifier from the corresponding full type
22037 declaration is not checked.
22038
22039 @noindent
22040 For a deferred constant, the defining name in the corresponding full constant
22041 declaration is not checked.
22042
22043 Defining names of formal types are not checked.
22044
22045 The rule may have the following parameters:
22046
22047 @itemize @bullet
22048 @item
22049 For the @option{+R} option:
22050 @table @code
22051 @item Default
22052 Sets the default listed above for all the names to be checked.
22053
22054 @item Type_Suffix=@emph{string}
22055 Specifies the suffix for a type name.
22056
22057 @item Access_Suffix=@emph{string}
22058 Specifies the suffix for an access type name. If
22059 this parameter is set, it overrides for access
22060 types the suffix set by the @code{Type_Suffix} parameter.
22061 For access types, @emph{string} may have the following format:
22062 @emph{suffix1(suffix2)}. That means that an access type name
22063 should have the @emph{suffix1} suffix except for the case when
22064 the designated type is also an access type, in this case the
22065 type name should have the @emph{suffix1 & suffix2} suffix.
22066
22067 @item Class_Access_Suffix=@emph{string}
22068 Specifies the suffix for the name of an access type that points to some class-wide
22069 type. If this parameter is set, it overrides for such access
22070 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22071 parameter.
22072
22073 @item Class_Subtype_Suffix=@emph{string}
22074 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22075
22076 @item Constant_Suffix=@emph{string}
22077 Specifies the suffix for a constant name.
22078
22079 @item Renaming_Suffix=@emph{string}
22080 Specifies the suffix for a package renaming name.
22081 @end table
22082
22083 @item
22084 For the @option{-R} option:
22085 @table @code
22086 @item All_Suffixes
22087 Remove all the suffixes specified for the
22088 identifier suffix checks, whether by default or
22089 as specified by other rule parameters. All the
22090 checks for this rule are disabled as a result.
22091
22092 @item Type_Suffix
22093 Removes the suffix specified for types. This
22094 disables checks for types but does not disable
22095 any other checks for this rule (including the
22096 check for access type names if @code{Access_Suffix} is
22097 set).
22098
22099 @item Access_Suffix
22100 Removes the suffix specified for access types.
22101 This disables checks for access type names but
22102 does not disable any other checks for this rule.
22103 If @code{Type_Suffix} is set, access type names are
22104 checked as ordinary type names.
22105
22106 @item Class_Access_Suffix
22107 Removes the suffix specified for access types pointing to class-wide
22108 type. This disables specific checks for names of access types pointing to
22109 class-wide types but does not disable any other checks for this rule.
22110 If @code{Type_Suffix} is set, access type names are
22111 checked as ordinary type names. If @code{Access_Suffix} is set, these
22112 access types are checked as any other access type name.
22113
22114 @item Class_Subtype_Suffix=@emph{string}
22115 Removes the suffix specified for subtype names.
22116 This disables checks for subtype names but
22117 does not disable any other checks for this rule.
22118
22119 @item Constant_Suffix
22120 Removes the suffix specified for constants. This
22121 disables checks for constant names but does not
22122 disable any other checks for this rule.
22123
22124 @item Renaming_Suffix
22125 Removes the suffix specified for package
22126 renamings. This disables checks for package
22127 renamings but does not disable any other checks
22128 for this rule.
22129 @end table
22130 @end itemize
22131
22132 @noindent
22133 If more than one parameter is used, parameters must be separated by commas.
22134
22135 If more than one  option is specified for the @command{gnatcheck} invocation,
22136 a new option overrides the previous one(s).
22137
22138 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22139 checks for all the
22140 name suffixes specified by previous options used for this rule.
22141
22142 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22143 all the checks but keeps
22144 all the suffixes specified by previous options used for this rule.
22145
22146 The @emph{string} value must be a valid suffix for an Ada identifier (after
22147 trimming all the leading and trailing space characters, if any).
22148 Parameters are not case sensitive, except the @emph{string} part.
22149
22150 If any error is detected in a rule parameter, the parameter is ignored.
22151 In such a case the options that are set for the rule are not
22152 specified.
22153
22154
22155
22156 @node Multiple_Entries_In_Protected_Definitions
22157 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22158 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22159
22160 @noindent
22161 Flag each protected definition (i.e., each protected object/type declaration)
22162 that defines more than one entry.
22163 Diagnostic messages are generated for all the entry declarations
22164 except the first one. An entry family is counted as one entry. Entries from
22165 the private part of the protected definition are also checked.
22166
22167 This rule has no parameters.
22168
22169 @node Name_Clashes
22170 @subsection @code{Name_Clashes}
22171 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22172
22173 @noindent
22174 Check that certain names are not used as defining identifiers. To activate
22175 this rule, you need to supply a reference to the dictionary file(s) as a rule
22176 parameter(s) (more then one dictionary file can be specified). If no
22177 dictionary file is set, this rule will not cause anything to be flagged.
22178 Only defining occurrences, not references, are checked.
22179 The check is not case-sensitive.
22180
22181 This rule is enabled by default, but without setting any corresponding
22182 dictionary file(s); thus the default effect is to do no checks.
22183
22184 A dictionary file is a plain text file. The maximum line length for this file
22185 is 1024 characters.  If the line is longer then this limit, extra characters
22186 are ignored.
22187
22188 Each line can be either an empty line, a comment line, or a line containing
22189 a list of identifiers separated by space or HT characters.
22190 A comment is an Ada-style comment (from @code{--} to end-of-line).
22191 Identifiers must follow the Ada syntax for identifiers.
22192 A line containing one or more identifiers may end with a comment.
22193
22194 @node Non_Qualified_Aggregates
22195 @subsection @code{Non_Qualified_Aggregates}
22196 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22197
22198 @noindent
22199 Flag each non-qualified aggregate.
22200 A non-qualified aggregate is an
22201 aggregate that is not the expression of a qualified expression. A
22202 string literal is not considered an aggregate, but an array
22203 aggregate of a string type is considered as a normal aggregate.
22204 Aggregates of anonymous array types are not flagged.
22205
22206 This rule has no parameters.
22207
22208
22209 @node Non_Short_Circuit_Operators
22210 @subsection @code{Non_Short_Circuit_Operators}
22211 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22212
22213 @noindent
22214 Flag all calls to predefined @code{and} and @code{or} operators for
22215 any boolean type. Calls to
22216 user-defined @code{and} and @code{or} and to operators defined by renaming
22217 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22218 operators for modular types or boolean array types are not flagged.
22219
22220 This rule has no parameters.
22221
22222
22223
22224 @node Non_SPARK_Attributes
22225 @subsection @code{Non_SPARK_Attributes}
22226 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22227
22228 @noindent
22229 The SPARK language defines the following subset of Ada 95 attribute
22230 designators as those that can be used in SPARK programs. The use of
22231 any other attribute is flagged.
22232
22233 @itemize @bullet
22234 @item @code{'Adjacent}
22235 @item @code{'Aft}
22236 @item @code{'Base}
22237 @item @code{'Ceiling}
22238 @item @code{'Component_Size}
22239 @item @code{'Compose}
22240 @item @code{'Copy_Sign}
22241 @item @code{'Delta}
22242 @item @code{'Denorm}
22243 @item @code{'Digits}
22244 @item @code{'Exponent}
22245 @item @code{'First}
22246 @item @code{'Floor}
22247 @item @code{'Fore}
22248 @item @code{'Fraction}
22249 @item @code{'Last}
22250 @item @code{'Leading_Part}
22251 @item @code{'Length}
22252 @item @code{'Machine}
22253 @item @code{'Machine_Emax}
22254 @item @code{'Machine_Emin}
22255 @item @code{'Machine_Mantissa}
22256 @item @code{'Machine_Overflows}
22257 @item @code{'Machine_Radix}
22258 @item @code{'Machine_Rounds}
22259 @item @code{'Max}
22260 @item @code{'Min}
22261 @item @code{'Model}
22262 @item @code{'Model_Emin}
22263 @item @code{'Model_Epsilon}
22264 @item @code{'Model_Mantissa}
22265 @item @code{'Model_Small}
22266 @item @code{'Modulus}
22267 @item @code{'Pos}
22268 @item @code{'Pred}
22269 @item @code{'Range}
22270 @item @code{'Remainder}
22271 @item @code{'Rounding}
22272 @item @code{'Safe_First}
22273 @item @code{'Safe_Last}
22274 @item @code{'Scaling}
22275 @item @code{'Signed_Zeros}
22276 @item @code{'Size}
22277 @item @code{'Small}
22278 @item @code{'Succ}
22279 @item @code{'Truncation}
22280 @item @code{'Unbiased_Rounding}
22281 @item @code{'Val}
22282 @item @code{'Valid}
22283 @end itemize
22284
22285 @noindent
22286 This rule has no parameters.
22287
22288
22289 @node Non_Tagged_Derived_Types
22290 @subsection @code{Non_Tagged_Derived_Types}
22291 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22292
22293 @noindent
22294 Flag all derived type declarations that do not have a record extension part.
22295
22296 This rule has no parameters.
22297
22298
22299
22300 @node Non_Visible_Exceptions
22301 @subsection @code{Non_Visible_Exceptions}
22302 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22303
22304 @noindent
22305 Flag constructs leading to the possibility of propagating an exception
22306 out of the scope in which the exception is declared.
22307 Two cases are detected:
22308
22309 @itemize @bullet
22310 @item
22311 An exception declaration in a subprogram body, task body or block
22312 statement is flagged if the body or statement does not contain a handler for
22313 that exception or a handler with an @code{others} choice.
22314
22315 @item
22316 A @code{raise} statement in an exception handler of a subprogram body,
22317 task body or block statement is flagged if it (re)raises a locally
22318 declared exception.  This may occur under the following circumstances:
22319 @itemize @minus
22320 @item
22321 it explicitly raises a locally declared exception, or
22322 @item
22323 it does not specify an exception name (i.e., it is simply @code{raise;})
22324 and the enclosing handler contains a locally declared exception in its
22325 exception choices.
22326 @end itemize
22327 @end itemize
22328
22329 @noindent
22330 Renamings of local exceptions are not flagged.
22331
22332 This rule has no parameters.
22333
22334
22335 @node Numeric_Literals
22336 @subsection @code{Numeric_Literals}
22337 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22338
22339 @noindent
22340 Flag each use of a numeric literal in an index expression, and in any
22341 circumstance except for the following:
22342
22343 @itemize @bullet
22344 @item
22345 a literal occurring in the initialization expression for a constant
22346 declaration or a named number declaration, or
22347
22348 @item
22349 an integer literal that is less than or equal to a value
22350 specified by the @option{N} rule parameter.
22351 @end itemize
22352
22353 @noindent
22354 This rule may have the following parameters for the @option{+R} option:
22355
22356 @table @asis
22357 @item @emph{N}
22358 @emph{N} is an integer literal used as the maximal value that is not flagged
22359 (i.e., integer literals not exceeding this value are allowed)
22360
22361 @item @code{ALL}
22362 All integer literals are flagged
22363 @end table
22364
22365 @noindent
22366 If no parameters are set, the maximum unflagged value is 1.
22367
22368 The last specified check limit (or the fact that there is no limit at
22369 all) is used when multiple @option{+R} options appear.
22370
22371 The @option{-R} option for this rule has no parameters.
22372 It disables the rule but retains the last specified maximum unflagged value.
22373 If the @option{+R} option subsequently appears, this value is used as the
22374 threshold for the check.
22375
22376
22377 @node OTHERS_In_Aggregates
22378 @subsection @code{OTHERS_In_Aggregates}
22379 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22380
22381 @noindent
22382 Flag each use of an @code{others} choice in extension aggregates.
22383 In record and array aggregates, an @code{others} choice is flagged unless
22384 it is used to refer to all components, or to all but one component.
22385
22386 If, in case of a named array aggregate, there are two associations, one
22387 with an @code{others} choice and another with a discrete range, the
22388 @code{others} choice is flagged even if the discrete range specifies
22389 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22390
22391 This rule has no parameters.
22392
22393 @node OTHERS_In_CASE_Statements
22394 @subsection @code{OTHERS_In_CASE_Statements}
22395 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22396
22397 @noindent
22398 Flag any use of an @code{others} choice in a @code{case} statement.
22399
22400 This rule has no parameters.
22401
22402 @node OTHERS_In_Exception_Handlers
22403 @subsection @code{OTHERS_In_Exception_Handlers}
22404 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22405
22406 @noindent
22407 Flag any use of an @code{others} choice in an exception handler.
22408
22409 This rule has no parameters.
22410
22411
22412 @node Outer_Loop_Exits
22413 @subsection @code{Outer_Loop_Exits}
22414 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22415
22416 @noindent
22417 Flag each @code{exit} statement containing a loop name that is not the name
22418 of the immediately enclosing @code{loop} statement.
22419
22420 This rule has no parameters.
22421
22422
22423 @node Overloaded_Operators
22424 @subsection @code{Overloaded_Operators}
22425 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22426
22427 @noindent
22428 Flag each function declaration that overloads an operator symbol.
22429 A function body is checked only if the body does not have a
22430 separate spec. Formal functions are also checked. For a
22431 renaming declaration, only renaming-as-declaration is checked
22432
22433 This rule has no parameters.
22434
22435
22436 @node Overly_Nested_Control_Structures
22437 @subsection @code{Overly_Nested_Control_Structures}
22438 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22439
22440 @noindent
22441 Flag each control structure whose nesting level exceeds the value provided
22442 in the rule parameter.
22443
22444 The control structures checked are the following:
22445
22446 @itemize @bullet
22447 @item    @code{if} statement
22448 @item    @code{case} statement
22449 @item    @code{loop} statement
22450 @item    Selective accept statement
22451 @item    Timed entry call statement
22452 @item    Conditional entry call
22453 @item    Asynchronous select statement
22454 @end itemize
22455
22456 @noindent
22457 The rule has the following parameter for the @option{+R} option:
22458
22459 @table @emph
22460 @item N
22461 Positive integer specifying the maximal control structure nesting
22462 level that is not flagged
22463 @end table
22464
22465 @noindent
22466 If the parameter for the @option{+R} option is not specified or
22467 if it is not a positive integer, @option{+R} option is ignored.
22468
22469 If more then one  option is specified for the gnatcheck call, the later option and
22470 new parameter override the previous one(s).
22471
22472
22473 @node Parameters_Out_Of_Order
22474 @subsection @code{Parameters_Out_Of_Order}
22475 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22476
22477 @noindent
22478 Flag each subprogram and entry declaration whose formal parameters are not
22479 ordered according to the following scheme:
22480
22481 @itemize @bullet
22482
22483 @item @code{in} and @code{access} parameters first,
22484 then @code{in out} parameters,
22485 and then @code{out} parameters;
22486
22487 @item for @code{in} mode, parameters with default initialization expressions
22488 occur last
22489 @end itemize
22490
22491 @noindent
22492 Only the first violation of the described order is flagged.
22493
22494 The following constructs are checked:
22495
22496 @itemize @bullet
22497 @item   subprogram declarations (including null procedures);
22498 @item   generic subprogram declarations;
22499 @item   formal subprogram declarations;
22500 @item   entry declarations;
22501 @item   subprogram bodies and subprogram body stubs that do not
22502 have separate specifications
22503 @end itemize
22504
22505 @noindent
22506 Subprogram renamings are not checked.
22507
22508 This rule has no parameters.
22509
22510
22511 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22512 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22513 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22514
22515 @noindent
22516 Flag each generic actual parameter corresponding to a generic formal
22517 parameter with a default initialization, if positional notation is used.
22518
22519 This rule has no parameters.
22520
22521 @node Positional_Actuals_For_Defaulted_Parameters
22522 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22523 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22524
22525 @noindent
22526 Flag each actual parameter to a subprogram or entry call where the
22527 corresponding formal parameter has a default expression, if positional
22528 notation is used.
22529
22530 This rule has no parameters.
22531
22532 @node Positional_Components
22533 @subsection @code{Positional_Components}
22534 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22535
22536 @noindent
22537 Flag each array, record and extension aggregate that includes positional
22538 notation.
22539
22540 This rule has no parameters.
22541
22542
22543 @node Positional_Generic_Parameters
22544 @subsection @code{Positional_Generic_Parameters}
22545 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22546
22547 @noindent
22548 Flag each positional actual generic parameter except for the case when
22549 the generic unit being iinstantiated has exactly one generic formal
22550 parameter.
22551
22552 This rule has no parameters.
22553
22554
22555 @node Positional_Parameters
22556 @subsection @code{Positional_Parameters}
22557 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22558
22559 @noindent
22560 Flag each positional parameter notation in a subprogram or entry call,
22561 except for the following:
22562
22563 @itemize @bullet
22564 @item
22565 Parameters of calls to of prefix or infix operators are not flagged
22566 @item
22567 If the called subprogram or entry has only one formal parameter,
22568 the parameter of the call is not flagged;
22569 @item
22570 If a subprogram call uses the @emph{Object.Operation} notation, then
22571 @itemize @minus
22572 @item
22573 the first parameter (that is, @emph{Object}) is not flagged;
22574 @item
22575 if the called subprogram has only two parameters, the second parameter
22576 of the call is not flagged;
22577 @end itemize
22578 @end itemize
22579
22580 @noindent
22581 This rule has no parameters.
22582
22583
22584
22585
22586 @node Predefined_Numeric_Types
22587 @subsection @code{Predefined_Numeric_Types}
22588 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22589
22590 @noindent
22591 Flag each explicit use of the name of any numeric type or subtype defined
22592 in package @code{Standard}.
22593
22594 The rationale for this rule is to detect when the
22595 program may depend on platform-specific characteristics of the implementation
22596 of the predefined numeric types. Note that this rule is over-pessimistic;
22597 for example, a program that uses @code{String} indexing
22598 likely needs a variable of type @code{Integer}.
22599 Another example is the flagging of predefined numeric types with explicit
22600 constraints:
22601
22602 @smallexample @c ada
22603     subtype My_Integer is Integer range Left .. Right;
22604     Vy_Var : My_Integer;
22605 @end smallexample
22606
22607 @noindent
22608 This rule detects only numeric types and subtypes defined in
22609 @code{Standard}. The use of numeric types and subtypes defined in other
22610 predefined packages (such as @code{System.Any_Priority} or
22611 @code{Ada.Text_IO.Count}) is not flagged
22612
22613 This rule has no parameters.
22614
22615
22616
22617 @node Raising_External_Exceptions
22618 @subsection @code{Raising_External_Exceptions}
22619 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22620
22621 @noindent
22622 Flag any @code{raise} statement, in a program unit declared in a library
22623 package or in a generic library package, for an exception that is
22624 neither a predefined exception nor an exception that is also declared (or
22625 renamed) in the visible part of the package.
22626
22627 This rule has no parameters.
22628
22629
22630
22631 @node Raising_Predefined_Exceptions
22632 @subsection @code{Raising_Predefined_Exceptions}
22633 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22634
22635 @noindent
22636 Flag each @code{raise} statement that raises a predefined exception
22637 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22638 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22639
22640 This rule has no parameters.
22641
22642 @node Separate_Numeric_Error_Handlers
22643 @subsection @code{Separate_Numeric_Error_Handlers}
22644 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22645
22646 @noindent
22647 Flags each exception handler that contains a choice for
22648 the predefined @code{Constraint_Error} exception, but does not contain
22649 the choice for the predefined @code{Numeric_Error} exception, or
22650 that contains the choice for @code{Numeric_Error}, but does not contain the
22651 choice for @code{Constraint_Error}.
22652
22653 This rule has no parameters.
22654
22655 @ignore
22656 @node Recursion
22657 @subsection @code{Recursion} (under construction, GLOBAL)
22658 @cindex @code{Recursion} rule (for @command{gnatcheck})
22659
22660 @noindent
22661 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22662 calls, of recursive subprograms are detected.
22663
22664 This rule has no parameters.
22665 @end ignore
22666
22667 @ignore
22668 @node Side_Effect_Functions
22669 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22670 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22671
22672 @noindent
22673 Flag functions with side effects.
22674
22675 We define a side effect as changing any data object that is not local for the
22676 body of this function.
22677
22678 At the moment, we do NOT consider a side effect any input-output operations
22679 (changing a state or a content of any file).
22680
22681 We do not consider protected functions for this rule (???)
22682
22683 There are the following sources of side effect:
22684
22685 @enumerate
22686 @item Explicit (or direct) side-effect:
22687
22688 @itemize @bullet
22689 @item
22690 direct assignment to a non-local variable;
22691
22692 @item
22693 direct call to an entity that is known to change some data object that is
22694      not local for the body of this function (Note, that if F1 calls F2 and F2
22695      does have a side effect, this does not automatically mean that F1 also
22696      have a side effect, because it may be the case that F2 is declared in
22697      F1's body and it changes some data object that is global for F2, but
22698      local for F1);
22699 @end itemize
22700
22701 @item Indirect side-effect:
22702 @itemize @bullet
22703 @item
22704 Subprogram calls implicitly issued by:
22705 @itemize @bullet
22706 @item
22707 computing initialization expressions from type declarations as a part
22708          of object elaboration or allocator evaluation;
22709 @item
22710 computing implicit parameters of subprogram or entry calls or generic
22711          instantiations;
22712 @end itemize
22713
22714 @item
22715 activation of a task that change some non-local data object (directly or
22716      indirectly);
22717
22718 @item
22719 elaboration code of a package that is a result of a package instantiation;
22720
22721 @item
22722 controlled objects;
22723 @end itemize
22724
22725 @item Situations when we can suspect a side-effect, but the full static check
22726 is either impossible or too hard:
22727 @itemize @bullet
22728 @item
22729 assignment to access variables or to the objects pointed by access
22730      variables;
22731
22732 @item
22733 call to a subprogram pointed by access-to-subprogram value
22734
22735 @item
22736 dispatching calls;
22737 @end itemize
22738 @end enumerate
22739
22740 @noindent
22741 This rule has no parameters.
22742 @end ignore
22743
22744 @node Slices
22745 @subsection @code{Slices}
22746 @cindex @code{Slices} rule (for @command{gnatcheck})
22747
22748 @noindent
22749 Flag all uses of array slicing
22750
22751 This rule has no parameters.
22752
22753
22754 @node Too_Many_Parents
22755 @subsection @code{Too_Many_Parents}
22756 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22757
22758 @noindent
22759 Flags any type declaration, single task declaration or single protected
22760 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22761 of the rule.
22762 A parent here is either a (sub)type denoted by the subtype mark from the
22763 parent_subtype_indication (in case of a derived type declaration), or
22764 any of the progenitors from the interface list, if any.
22765
22766 This rule has the following (mandatory) parameters for the @option{+R} option:
22767
22768 @table @emph
22769 @item N
22770 Positive integer specifying the maximal allowed number of parents.
22771 @end table
22772
22773
22774 @node Unassigned_OUT_Parameters
22775 @subsection @code{Unassigned_OUT_Parameters}
22776 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22777
22778 @noindent
22779 Flags procedures' @code{out} parameters that are not assigned, and
22780 identifies the contexts in which the assignments are missing.
22781
22782 An @code{out} parameter is flagged in the statements in the procedure
22783 body's handled sequence of statements (before the procedure body's
22784 @code{exception} part, if any) if this sequence of statements contains
22785 no assignments to the parameter.
22786
22787 An @code{out} parameter is flagged in an exception handler in the exception
22788 part of the procedure body's handled sequence of statements if the handler
22789 contains no assignment to the parameter.
22790
22791 Bodies of generic procedures are also considered.
22792
22793 The following are treated as assignments to an @code{out} parameter:
22794
22795 @itemize @bullet
22796 @item
22797 an assignment statement, with the parameter or some component as the target;
22798
22799 @item
22800 passing the parameter (or one of its components) as an @code{out} or
22801 @code{in out} parameter.
22802 @end itemize
22803
22804 @noindent
22805 This rule does not have any parameters.
22806
22807
22808
22809 @node Uncommented_BEGIN_In_Package_Bodies
22810 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22811 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22812
22813 @noindent
22814 Flags each package body with declarations and a statement part that does not
22815 include a trailing comment on the line containing the @code{begin} keyword;
22816 this trailing comment needs to specify the package name and nothing else.
22817 The @code{begin} is not flagged if the package body does not
22818 contain any declarations.
22819
22820 If the @code{begin} keyword is placed on the
22821 same line as the last declaration or the first statement, it is flagged
22822 independently of whether the line contains a trailing comment. The
22823 diagnostic message is attached to the line containing the first statement.
22824
22825 This rule has no parameters.
22826
22827 @node Unconditional_Exits
22828 @subsection @code{Unconditional_Exits}
22829 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22830
22831 @noindent
22832 Flag unconditional @code{exit} statements.
22833
22834 This rule has no parameters.
22835
22836 @node Unconstrained_Array_Returns
22837 @subsection @code{Unconstrained_Array_Returns}
22838 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22839
22840 @noindent
22841 Flag each function returning an unconstrained array. Function declarations,
22842 function bodies (and body stubs) having no separate specifications,
22843 and generic function instantiations are checked.
22844 Function calls and function renamings are
22845 not checked.
22846
22847 Generic function declarations, and function declarations in generic
22848 packages are not checked, instead this rule checks the results of
22849 generic instantiations (that is, expanded specification and expanded
22850 body corresponding to an instantiation).
22851
22852 This rule has no parameters.
22853
22854 @node Universal_Ranges
22855 @subsection @code{Universal_Ranges}
22856 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22857
22858 @noindent
22859 Flag discrete ranges that are a part of an index constraint, constrained
22860 array definition, or @code{for}-loop parameter specification, and whose bounds
22861 are both of type @i{universal_integer}. Ranges that have at least one
22862 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22863 or an expression of non-universal type) are not flagged.
22864
22865 This rule has no parameters.
22866
22867
22868 @node Unnamed_Blocks_And_Loops
22869 @subsection @code{Unnamed_Blocks_And_Loops}
22870 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22871
22872 @noindent
22873 Flag each unnamed block statement and loop statement.
22874
22875 The rule has no parameters.
22876
22877
22878
22879 @ignore
22880 @node Unused_Subprograms
22881 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22882 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22883
22884 @noindent
22885 Flag all unused subprograms.
22886
22887 This rule has no parameters.
22888 @end ignore
22889
22890
22891
22892
22893 @node USE_PACKAGE_Clauses
22894 @subsection @code{USE_PACKAGE_Clauses}
22895 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22896
22897 @noindent
22898 Flag all @code{use} clauses for packages; @code{use type} clauses are
22899 not flagged.
22900
22901 This rule has no parameters.
22902
22903
22904 @node Visible_Components
22905 @subsection @code{Visible_Components}
22906 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22907
22908 @noindent
22909 Flags all the type declarations located in the visible part of a library
22910 package or a library generic package that can declare a visible component. A
22911 type is considered as declaring a visible component if it contains a record
22912 definition by its own or as a part of a record extension. Type declaration is
22913 flagged even if it contains a record definition that defines no components.
22914
22915 Declarations located in private parts of local (generic) packages are not
22916 flagged. Declarations in private packages are not flagged.
22917
22918 This rule has no parameters.
22919
22920
22921 @node Volatile_Objects_Without_Address_Clauses
22922 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22923 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22924
22925 @noindent
22926 Flag each volatile object that does not have an address clause.
22927
22928 The following check is made: if the pragma @code{Volatile} is applied to a
22929 data object or to its type, then an address clause must
22930 be supplied for this object.
22931
22932 This rule does not check the components of data objects,
22933 array components that are volatile as a result of the pragma
22934 @code{Volatile_Components}, or objects that are volatile because
22935 they are atomic as a result of pragmas @code{Atomic} or
22936 @code{Atomic_Components}.
22937
22938 Only variable declarations, and not constant declarations, are checked.
22939
22940 This rule has no parameters.
22941
22942 @node Example of gnatcheck Usage
22943 @section Example of @command{gnatcheck} Usage
22944
22945 @noindent
22946 Here is a simple example. Suppose that in the current directory we have a
22947 project file named @file{gnatcheck_example.gpr} with the following content:
22948
22949 @smallexample @c projectfile
22950 project Gnatcheck_Example is
22951
22952    for Source_Dirs use ("src");
22953    for Object_Dir use "obj";
22954    for Main use ("main.adb");
22955
22956    package Check is
22957       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
22958    end Check;
22959
22960 end Gnatcheck_Example;
22961 @end smallexample
22962
22963 @noindent
22964 And the file named @file{coding_standard} is also located in the current
22965 directory and has the following content:
22966
22967 @smallexample
22968 -----------------------------------------------------
22969 -- This is a sample gnatcheck coding standard file --
22970 -----------------------------------------------------
22971
22972 --  First, turning on rules, that are directly implemented in gnatcheck
22973 +RAbstract_Type_Declarations
22974 +RAnonymous_Arrays
22975 +RLocal_Packages
22976 +RFloat_Equality_Checks
22977 +REXIT_Statements_With_No_Loop_Name
22978
22979 --  Then, activating compiler checks of interest:
22980 +RStyle_Checks:e
22981 --  This style check checks if a unit name is present on END keyword that
22982 --  is the end of the unit declaration
22983 @end smallexample
22984
22985 @noindent
22986 And the subdirectory @file{src} contains the following Ada sources:
22987
22988 @file{pack.ads}:
22989
22990 @smallexample @c ada
22991 package Pack is
22992    type T is abstract tagged private;
22993    procedure P (X : T) is abstract;
22994
22995    package Inner is
22996       type My_Float is digits 8;
22997       function Is_Equal (L, R : My_Float) return Boolean;
22998    end Inner;
22999 private
23000    type T is abstract tagged null record;
23001 end;
23002 @end smallexample
23003
23004 @noindent
23005 @file{pack.adb}:
23006
23007 @smallexample @c ada
23008 package body Pack is
23009    package body Inner is
23010       function Is_Equal (L, R : My_Float) return Boolean is
23011       begin
23012          return L = R;
23013       end;
23014    end Inner;
23015 end Pack;
23016 @end smallexample
23017
23018 @noindent
23019 and @file{main.adb}
23020
23021 @smallexample @c ada
23022 with Pack; use Pack;
23023 procedure Main is
23024
23025    pragma Annotate
23026      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
23027    Float_Array : array (1 .. 10) of Inner.My_Float;
23028    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
23029
23030    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
23031
23032    use Inner;
23033
23034    B : Boolean := False;
23035
23036 begin
23037    for J in Float_Array'Range loop
23038       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
23039          B := True;
23040          exit;
23041       end if;
23042    end loop;
23043 end Main;
23044 @end smallexample
23045
23046 @noindent
23047 And suppose we call @command{gnatcheck} from the current directory using
23048 the @command{gnat} driver:
23049
23050 @smallexample
23051    gnat check -Pgnatcheck_example.gpr
23052 @end smallexample
23053
23054 @noindent
23055 As a result, @command{gnatcheck} is called to check all the files from the
23056 project @file{gnatcheck_example.gpr} using the coding standard defined by
23057 the file @file{coding_standard}. As the result, the @command{gnatcheck}
23058 report file named @file{gnatcheck.out} will be created in the current
23059 directory, and it will have the following content:
23060
23061 @smallexample
23062 RULE CHECKING REPORT
23063
23064 1. OVERVIEW
23065
23066 Date and time of execution: 2009.10.28 14:17
23067 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
23068 Command line:
23069
23070 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
23071
23072 Coding standard (applied rules):
23073    Abstract_Type_Declarations
23074    Anonymous_Arrays
23075    EXIT_Statements_With_No_Loop_Name
23076    Float_Equality_Checks
23077    Local_Packages
23078
23079    Compiler style checks: -gnatye
23080
23081 Number of coding standard violations: 6
23082 Number of exempted coding standard violations: 1
23083
23084 2. DETECTED RULE VIOLATIONS
23085
23086 2.1. NON-EXEMPTED VIOLATIONS
23087
23088 Source files with non-exempted violations
23089    pack.ads
23090    pack.adb
23091    main.adb
23092
23093 List of violations grouped by files, and ordered by increasing source location:
23094
23095 pack.ads:2:4: declaration of abstract type
23096 pack.ads:5:4: declaration of local package
23097 pack.ads:10:30: declaration of abstract type
23098 pack.ads:11:1: (style) "end Pack" required
23099 pack.adb:5:19: use of equality operation for float values
23100 pack.adb:6:7: (style) "end Is_Equal" required
23101 main.adb:9:26: anonymous array type
23102 main.adb:19:10: exit statement with no loop name
23103
23104 2.2. EXEMPTED VIOLATIONS
23105
23106 Source files with exempted violations
23107    main.adb
23108
23109 List of violations grouped by files, and ordered by increasing source location:
23110
23111 main.adb:6:18: anonymous array type
23112    (this one is fine)
23113
23114 2.3. SOURCE FILES WITH NO VIOLATION
23115
23116    No files without violations
23117
23118 END OF REPORT
23119 @end smallexample
23120
23121
23122 @c *********************************
23123 @node Creating Sample Bodies Using gnatstub
23124 @chapter Creating Sample Bodies Using @command{gnatstub}
23125 @findex gnatstub
23126
23127 @noindent
23128 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
23129 for library unit declarations.
23130
23131 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
23132 driver (see @ref{The GNAT Driver and Project Files}).
23133
23134 To create a body stub, @command{gnatstub} has to compile the library
23135 unit declaration. Therefore, bodies can be created only for legal
23136 library units. Moreover, if a library unit depends semantically upon
23137 units located outside the current directory, you have to provide
23138 the source search path when calling @command{gnatstub}, see the description
23139 of @command{gnatstub} switches below.
23140
23141 By default, all the program unit body stubs generated by @code{gnatstub}
23142 raise the predefined @code{Program_Error} exception, which will catch
23143 accidental calls of generated stubs. This behavior can be changed with
23144 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
23145
23146 @menu
23147 * Running gnatstub::
23148 * Switches for gnatstub::
23149 @end menu
23150
23151 @node Running gnatstub
23152 @section Running @command{gnatstub}
23153
23154 @noindent
23155 @command{gnatstub} has the command-line interface of the form
23156
23157 @smallexample
23158 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
23159 @c Expanding @ovar macro inline (explanation in macro def comments)
23160 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
23161 @end smallexample
23162
23163 @noindent
23164 where
23165 @table @var
23166 @item filename
23167 is the name of the source file that contains a library unit declaration
23168 for which a body must be created. The file name may contain the path
23169 information.
23170 The file name does not have to follow the GNAT file name conventions. If the
23171 name
23172 does not follow GNAT file naming conventions, the name of the body file must
23173 be provided
23174 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
23175 If the file name follows the GNAT file naming
23176 conventions and the name of the body file is not provided,
23177 @command{gnatstub}
23178 creates the name
23179 of the body file from the argument file name by replacing the @file{.ads}
23180 suffix
23181 with the @file{.adb} suffix.
23182
23183 @item directory
23184 indicates the directory in which the body stub is to be placed (the default
23185 is the
23186 current directory)
23187
23188 @item @samp{@var{gcc_switches}} is a list of switches for
23189 @command{gcc}. They will be passed on to all compiler invocations made by
23190 @command{gnatelim} to generate the ASIS trees. Here you can provide
23191 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
23192 use the @option{-gnatec} switch to set the configuration file etc.
23193
23194 @item switches
23195 is an optional sequence of switches as described in the next section
23196 @end table
23197
23198 @node Switches for gnatstub
23199 @section Switches for @command{gnatstub}
23200
23201 @table @option
23202 @c !sort!
23203
23204 @item ^-f^/FULL^
23205 @cindex @option{^-f^/FULL^} (@command{gnatstub})
23206 If the destination directory already contains a file with the name of the
23207 body file
23208 for the argument spec file, replace it with the generated body stub.
23209
23210 @item ^-hs^/HEADER=SPEC^
23211 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
23212 Put the comment header (i.e., all the comments preceding the
23213 compilation unit) from the source of the library unit declaration
23214 into the body stub.
23215
23216 @item ^-hg^/HEADER=GENERAL^
23217 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
23218 Put a sample comment header into the body stub.
23219
23220 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
23221 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
23222 Use the content of the file as the comment header for a generated body stub.
23223
23224 @ifclear vms
23225 @item -IDIR
23226 @cindex @option{-IDIR} (@command{gnatstub})
23227 @itemx -I-
23228 @cindex @option{-I-} (@command{gnatstub})
23229 @end ifclear
23230 @ifset vms
23231 @item /NOCURRENT_DIRECTORY
23232 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23233 @end ifset
23234 ^These switches have ^This switch has^ the same meaning as in calls to
23235 @command{gcc}.
23236 ^They define ^It defines ^ the source search path in the call to
23237 @command{gcc} issued
23238 by @command{gnatstub} to compile an argument source file.
23239
23240 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23241 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23242 This switch has the same meaning as in calls to @command{gcc}.
23243 It defines the additional configuration file to be passed to the call to
23244 @command{gcc} issued
23245 by @command{gnatstub} to compile an argument source file.
23246
23247 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23248 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23249 (@var{n} is a non-negative integer). Set the maximum line length in the
23250 body stub to @var{n}; the default is 79. The maximum value that can be
23251 specified is 32767. Note that in the special case of configuration
23252 pragma files, the maximum is always 32767 regardless of whether or
23253 not this switch appears.
23254
23255 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23256 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23257 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23258 the generated body sample to @var{n}.
23259 The default indentation is 3.
23260
23261 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23262 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23263 Order local bodies alphabetically. (By default local bodies are ordered
23264 in the same way as the corresponding local specs in the argument spec file.)
23265
23266 @item ^-i^/INDENTATION=^@var{n}
23267 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23268 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23269
23270 @item ^-k^/TREE_FILE=SAVE^
23271 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23272 Do not remove the tree file (i.e., the snapshot of the compiler internal
23273 structures used by @command{gnatstub}) after creating the body stub.
23274
23275 @item ^-l^/LINE_LENGTH=^@var{n}
23276 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23277 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23278
23279 @item ^--no-exception^/NO_EXCEPTION^
23280 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23281 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23282 This is not always possible for function stubs.
23283
23284 @item ^--no-local-header^/NO_LOCAL_HEADER^
23285 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23286 Do not place local comment header with unit name before body stub for a
23287 unit.
23288
23289 @item ^-o ^/BODY=^@var{body-name}
23290 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23291 Body file name.  This should be set if the argument file name does not
23292 follow
23293 the GNAT file naming
23294 conventions. If this switch is omitted the default name for the body will be
23295 obtained
23296 from the argument file name according to the GNAT file naming conventions.
23297
23298 @item ^-q^/QUIET^
23299 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23300 Quiet mode: do not generate a confirmation when a body is
23301 successfully created, and do not generate a message when a body is not
23302 required for an
23303 argument unit.
23304
23305 @item ^-r^/TREE_FILE=REUSE^
23306 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23307 Reuse the tree file (if it exists) instead of creating it.  Instead of
23308 creating the tree file for the library unit declaration, @command{gnatstub}
23309 tries to find it in the current directory and use it for creating
23310 a body. If the tree file is not found, no body is created. This option
23311 also implies @option{^-k^/SAVE^}, whether or not
23312 the latter is set explicitly.
23313
23314 @item ^-t^/TREE_FILE=OVERWRITE^
23315 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23316 Overwrite the existing tree file.  If the current directory already
23317 contains the file which, according to the GNAT file naming rules should
23318 be considered as a tree file for the argument source file,
23319 @command{gnatstub}
23320 will refuse to create the tree file needed to create a sample body
23321 unless this option is set.
23322
23323 @item ^-v^/VERBOSE^
23324 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23325 Verbose mode: generate version information.
23326
23327 @end table
23328
23329 @c *********************************
23330 @node Generating Ada Bindings for C and C++ headers
23331 @chapter Generating Ada Bindings for C and C++ headers
23332 @findex binding
23333
23334 @noindent
23335 GNAT now comes with a binding generator for C and C++ headers which is
23336 intended to do 95% of the tedious work of generating Ada specs from C
23337 or C++ header files.
23338
23339 Note that this capability is not intended to generate 100% correct Ada specs,
23340 and will is some cases require manual adjustments, although it can often
23341 be used out of the box in practice.
23342
23343 Some of the known limitations include:
23344
23345 @itemize @bullet
23346 @item only very simple character constant macros are translated into Ada
23347 constants. Function macros (macros with arguments) are partially translated
23348 as comments, to be completed manually if needed.
23349 @item some extensions (e.g. vector types) are not supported
23350 @item pointers to pointers or complex structures are mapped to System.Address
23351 @end itemize
23352
23353 The code generated is using the Ada 2005 syntax, which makes it
23354 easier to interface with other languages than previous versions of Ada.
23355
23356 @menu
23357 * Running the binding generator::
23358 * Generating bindings for C++ headers::
23359 * Switches::
23360 @end menu
23361
23362 @node Running the binding generator
23363 @section Running the binding generator
23364
23365 @noindent
23366 The binding generator is part of the @command{gcc} compiler and can be
23367 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23368 spec files for the header files specified on the command line, and all
23369 header files needed by these files transitivitely. For example:
23370
23371 @smallexample
23372 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23373 $ gcc -c -gnat05 *.ads
23374 @end smallexample
23375
23376 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23377 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23378 correspond to the files @file{/usr/include/time.h},
23379 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23380 mode these Ada specs.
23381
23382 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23383 and will attempt to generate corresponding Ada comments.
23384
23385 If you want to generate a single Ada file and not the transitive closure, you
23386 can use instead the @option{-fdump-ada-spec-slim} switch.
23387
23388 Note that we recommend when possible to use the @command{g++} driver to
23389 generate bindings, even for most C headers, since this will in general
23390 generate better Ada specs. For generating bindings for C++ headers, it is
23391 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23392 is equivalent in this case. If @command{g++} cannot work on your C headers
23393 because of incompatibilities between C and C++, then you can fallback to
23394 @command{gcc} instead.
23395
23396 For an example of better bindings generated from the C++ front-end,
23397 the name of the parameters (when available) are actually ignored by the C
23398 front-end. Consider the following C header:
23399
23400 @smallexample
23401 extern void foo (int variable);
23402 @end smallexample
23403
23404 with the C front-end, @code{variable} is ignored, and the above is handled as:
23405
23406 @smallexample
23407 extern void foo (int);
23408 @end smallexample
23409
23410 generating a generic:
23411
23412 @smallexample
23413 procedure foo (param1 : int);
23414 @end smallexample
23415
23416 with the C++ front-end, the name is available, and we generate:
23417
23418 @smallexample
23419 procedure foo (variable : int);
23420 @end smallexample
23421
23422 In some cases, the generated bindings will be more complete or more meaningful
23423 when defining some macros, which you can do via the @option{-D} switch. This
23424 is for example the case with @file{Xlib.h} under GNU/Linux:
23425
23426 @smallexample
23427 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23428 @end smallexample
23429
23430 The above will generate more complete bindings than a straight call without
23431 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23432
23433 In other cases, it is not possible to parse a header file in a stand alone
23434 manner, because other include files need to be included first. In this
23435 case, the solution is to create a small header file including the needed
23436 @code{#include} and possible @code{#define} directives. For example, to
23437 generate Ada bindings for @file{readline/readline.h}, you need to first
23438 include @file{stdio.h}, so you can create a file with the following two
23439 lines in e.g. @file{readline1.h}:
23440
23441 @smallexample
23442 #include <stdio.h>
23443 #include <readline/readline.h>
23444 @end smallexample
23445
23446 and then generate Ada bindings from this file:
23447
23448 @smallexample
23449 $ g++ -c -fdump-ada-spec readline1.h
23450 @end smallexample
23451
23452 @node Generating bindings for C++ headers
23453 @section Generating bindings for C++ headers
23454
23455 @noindent
23456 Generating bindings for C++ headers is done using the same options, always
23457 with the @command{g++} compiler.
23458
23459 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23460 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23461 multiple inheritance of abstract classes will be mapped to Ada interfaces
23462 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23463 information on interfacing to C++).
23464
23465 For example, given the following C++ header file:
23466
23467 @smallexample
23468 @group
23469 @cartouche
23470 class Carnivore @{
23471 public:
23472    virtual int Number_Of_Teeth () = 0;
23473 @};
23474
23475 class Domestic @{
23476 public:
23477    virtual void Set_Owner (char* Name) = 0;
23478 @};
23479
23480 class Animal @{
23481 public:
23482   int Age_Count;
23483   virtual void Set_Age (int New_Age);
23484 @};
23485
23486 class Dog : Animal, Carnivore, Domestic @{
23487  public:
23488   int  Tooth_Count;
23489   char *Owner;
23490
23491   virtual int  Number_Of_Teeth ();
23492   virtual void Set_Owner (char* Name);
23493
23494   Dog();
23495 @};
23496 @end cartouche
23497 @end group
23498 @end smallexample
23499
23500 The corresponding Ada code is generated:
23501
23502 @smallexample @c ada
23503 @group
23504 @cartouche
23505   package Class_Carnivore is
23506     type Carnivore is limited interface;
23507     pragma Import (CPP, Carnivore);
23508
23509     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23510   end;
23511   use Class_Carnivore;
23512
23513   package Class_Domestic is
23514     type Domestic is limited interface;
23515     pragma Import (CPP, Domestic);
23516
23517     procedure Set_Owner
23518       (this : access Domestic;
23519        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23520   end;
23521   use Class_Domestic;
23522
23523   package Class_Animal is
23524     type Animal is tagged limited record
23525       Age_Count : aliased int;
23526     end record;
23527     pragma Import (CPP, Animal);
23528
23529     procedure Set_Age (this : access Animal; New_Age : int);
23530     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23531   end;
23532   use Class_Animal;
23533
23534   package Class_Dog is
23535     type Dog is new Animal and Carnivore and Domestic with record
23536       Tooth_Count : aliased int;
23537       Owner : Interfaces.C.Strings.chars_ptr;
23538     end record;
23539     pragma Import (CPP, Dog);
23540
23541     function Number_Of_Teeth (this : access Dog) return int;
23542     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23543
23544     procedure Set_Owner
23545       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23546     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23547
23548     function New_Dog return Dog;
23549     pragma CPP_Constructor (New_Dog);
23550     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23551   end;
23552   use Class_Dog;
23553 @end cartouche
23554 @end group
23555 @end smallexample
23556
23557 @node Switches
23558 @section Switches
23559
23560 @table @option
23561 @item -fdump-ada-spec
23562 @cindex @option{-fdump-ada-spec} (@command{gcc})
23563 Generate Ada spec files for the given header files transitively (including
23564 all header files that these headers depend upon).
23565
23566 @item -fdump-ada-spec-slim
23567 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23568 Generate Ada spec files for the header files specified on the command line
23569 only.
23570
23571 @item -C
23572 @cindex @option{-C} (@command{gcc})
23573 Extract comments from headers and generate Ada comments in the Ada spec files.
23574 @end table
23575
23576 @node Other Utility Programs
23577 @chapter Other Utility Programs
23578
23579 @noindent
23580 This chapter discusses some other utility programs available in the Ada
23581 environment.
23582
23583 @menu
23584 * Using Other Utility Programs with GNAT::
23585 * The External Symbol Naming Scheme of GNAT::
23586 * Converting Ada Files to html with gnathtml::
23587 * Installing gnathtml::
23588 @ifset vms
23589 * LSE::
23590 * Profiling::
23591 @end ifset
23592 @end menu
23593
23594 @node Using Other Utility Programs with GNAT
23595 @section Using Other Utility Programs with GNAT
23596
23597 @noindent
23598 The object files generated by GNAT are in standard system format and in
23599 particular the debugging information uses this format. This means
23600 programs generated by GNAT can be used with existing utilities that
23601 depend on these formats.
23602
23603 @ifclear vms
23604 In general, any utility program that works with C will also often work with
23605 Ada programs generated by GNAT. This includes software utilities such as
23606 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23607 as Purify.
23608 @end ifclear
23609
23610 @node The External Symbol Naming Scheme of GNAT
23611 @section The External Symbol Naming Scheme of GNAT
23612
23613 @noindent
23614 In order to interpret the output from GNAT, when using tools that are
23615 originally intended for use with other languages, it is useful to
23616 understand the conventions used to generate link names from the Ada
23617 entity names.
23618
23619 All link names are in all lowercase letters. With the exception of library
23620 procedure names, the mechanism used is simply to use the full expanded
23621 Ada name with dots replaced by double underscores. For example, suppose
23622 we have the following package spec:
23623
23624 @smallexample @c ada
23625 @group
23626 @cartouche
23627 package QRS is
23628    MN : Integer;
23629 end QRS;
23630 @end cartouche
23631 @end group
23632 @end smallexample
23633
23634 @noindent
23635 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23636 the corresponding link name is @code{qrs__mn}.
23637 @findex Export
23638 Of course if a @code{pragma Export} is used this may be overridden:
23639
23640 @smallexample @c ada
23641 @group
23642 @cartouche
23643 package Exports is
23644    Var1 : Integer;
23645    pragma Export (Var1, C, External_Name => "var1_name");
23646    Var2 : Integer;
23647    pragma Export (Var2, C, Link_Name => "var2_link_name");
23648 end Exports;
23649 @end cartouche
23650 @end group
23651 @end smallexample
23652
23653 @noindent
23654 In this case, the link name for @var{Var1} is whatever link name the
23655 C compiler would assign for the C function @var{var1_name}. This typically
23656 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23657 system conventions, but other possibilities exist. The link name for
23658 @var{Var2} is @var{var2_link_name}, and this is not operating system
23659 dependent.
23660
23661 @findex _main
23662 One exception occurs for library level procedures. A potential ambiguity
23663 arises between the required name @code{_main} for the C main program,
23664 and the name we would otherwise assign to an Ada library level procedure
23665 called @code{Main} (which might well not be the main program).
23666
23667 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23668 names. So if we have a library level procedure such as
23669
23670 @smallexample @c ada
23671 @group
23672 @cartouche
23673 procedure Hello (S : String);
23674 @end cartouche
23675 @end group
23676 @end smallexample
23677
23678 @noindent
23679 the external name of this procedure will be @var{_ada_hello}.
23680
23681
23682 @node Converting Ada Files to html with gnathtml
23683 @section Converting Ada Files to HTML with @code{gnathtml}
23684
23685 @noindent
23686 This @code{Perl} script allows Ada source files to be browsed using
23687 standard Web browsers. For installation procedure, see the section
23688 @xref{Installing gnathtml}.
23689
23690 Ada reserved keywords are highlighted in a bold font and Ada comments in
23691 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23692 switch to suppress the generation of cross-referencing information, user
23693 defined variables and types will appear in a different color; you will
23694 be able to click on any identifier and go to its declaration.
23695
23696 The command line is as follow:
23697 @smallexample
23698 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23699 @c Expanding @ovar macro inline (explanation in macro def comments)
23700 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
23701 @end smallexample
23702
23703 @noindent
23704 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23705 an html file for every ada file, and a global file called @file{index.htm}.
23706 This file is an index of every identifier defined in the files.
23707
23708 The available ^switches^options^ are the following ones:
23709
23710 @table @option
23711 @item -83
23712 @cindex @option{-83} (@code{gnathtml})
23713 Only the Ada 83 subset of keywords will be highlighted.
23714
23715 @item -cc @var{color}
23716 @cindex @option{-cc} (@code{gnathtml})
23717 This option allows you to change the color used for comments. The default
23718 value is green. The color argument can be any name accepted by html.
23719
23720 @item -d
23721 @cindex @option{-d} (@code{gnathtml})
23722 If the Ada files depend on some other files (for instance through
23723 @code{with} clauses, the latter files will also be converted to html.
23724 Only the files in the user project will be converted to html, not the files
23725 in the run-time library itself.
23726
23727 @item -D
23728 @cindex @option{-D} (@code{gnathtml})
23729 This command is the same as @option{-d} above, but @command{gnathtml} will
23730 also look for files in the run-time library, and generate html files for them.
23731
23732 @item -ext @var{extension}
23733 @cindex @option{-ext} (@code{gnathtml})
23734 This option allows you to change the extension of the generated HTML files.
23735 If you do not specify an extension, it will default to @file{htm}.
23736
23737 @item -f
23738 @cindex @option{-f} (@code{gnathtml})
23739 By default, gnathtml will generate html links only for global entities
23740 ('with'ed units, global variables and types,@dots{}).  If you specify
23741 @option{-f} on the command line, then links will be generated for local
23742 entities too.
23743
23744 @item -l @var{number}
23745 @cindex @option{-l} (@code{gnathtml})
23746 If this ^switch^option^ is provided and @var{number} is not 0, then
23747 @code{gnathtml} will number the html files every @var{number} line.
23748
23749 @item -I @var{dir}
23750 @cindex @option{-I} (@code{gnathtml})
23751 Specify a directory to search for library files (@file{.ALI} files) and
23752 source files. You can provide several -I switches on the command line,
23753 and the directories will be parsed in the order of the command line.
23754
23755 @item -o @var{dir}
23756 @cindex @option{-o} (@code{gnathtml})
23757 Specify the output directory for html files. By default, gnathtml will
23758 saved the generated html files in a subdirectory named @file{html/}.
23759
23760 @item -p @var{file}
23761 @cindex @option{-p} (@code{gnathtml})
23762 If you are using Emacs and the most recent Emacs Ada mode, which provides
23763 a full Integrated Development Environment for compiling, checking,
23764 running and debugging applications, you may use @file{.gpr} files
23765 to give the directories where Emacs can find sources and object files.
23766
23767 Using this ^switch^option^, you can tell gnathtml to use these files.
23768 This allows you to get an html version of your application, even if it
23769 is spread over multiple directories.
23770
23771 @item -sc @var{color}
23772 @cindex @option{-sc} (@code{gnathtml})
23773 This ^switch^option^ allows you to change the color used for symbol
23774 definitions.
23775 The default value is red. The color argument can be any name accepted by html.
23776
23777 @item -t @var{file}
23778 @cindex @option{-t} (@code{gnathtml})
23779 This ^switch^option^ provides the name of a file. This file contains a list of
23780 file names to be converted, and the effect is exactly as though they had
23781 appeared explicitly on the command line. This
23782 is the recommended way to work around the command line length limit on some
23783 systems.
23784
23785 @end table
23786
23787 @node Installing gnathtml
23788 @section Installing @code{gnathtml}
23789
23790 @noindent
23791 @code{Perl} needs to be installed on your machine to run this script.
23792 @code{Perl} is freely available for almost every architecture and
23793 Operating System via the Internet.
23794
23795 On Unix systems, you  may want to modify  the  first line of  the script
23796 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23797 is. The syntax of this line is:
23798 @smallexample
23799 #!full_path_name_to_perl
23800 @end smallexample
23801
23802 @noindent
23803 Alternatively, you may run the script using the following command line:
23804
23805 @smallexample
23806 @c $ perl gnathtml.pl @ovar{switches} @var{files}
23807 @c Expanding @ovar macro inline (explanation in macro def comments)
23808 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
23809 @end smallexample
23810
23811 @ifset vms
23812 @node LSE
23813 @section LSE
23814 @findex LSE
23815
23816 @noindent
23817 The GNAT distribution provides an Ada 95 template for the HP Language
23818 Sensitive Editor (LSE), a component of DECset. In order to
23819 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23820
23821 @node Profiling
23822 @section Profiling
23823 @findex PCA
23824
23825 @noindent
23826 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23827 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23828 the collection phase with the /DEBUG qualifier.
23829
23830 @smallexample
23831 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23832 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23833 $ RUN/DEBUG <PROGRAM_NAME>
23834 @end smallexample
23835 @noindent
23836 @end ifset
23837
23838 @ifclear vms
23839 @c ******************************
23840 @node Code Coverage and Profiling
23841 @chapter Code Coverage and Profiling
23842 @cindex Code Coverage
23843 @cindex Profiling
23844
23845 @noindent
23846 This chapter describes how to use @code{gcov} - coverage testing tool - and
23847 @code{gprof} - profiler tool - on your Ada programs.
23848
23849 @menu
23850 * Code Coverage of Ada Programs using gcov::
23851 * Profiling an Ada Program using gprof::
23852 @end menu
23853
23854 @node Code Coverage of Ada Programs using gcov
23855 @section Code Coverage of Ada Programs using gcov
23856 @cindex gcov
23857 @cindex -fprofile-arcs
23858 @cindex -ftest-coverage
23859 @cindex -coverage
23860 @cindex Code Coverage
23861
23862 @noindent
23863 @code{gcov} is a test coverage program: it analyzes the execution of a given
23864 program on selected tests, to help you determine the portions of the program
23865 that are still untested.
23866
23867 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23868 User's Guide. You can refer to this documentation for a more complete
23869 description.
23870
23871 This chapter provides a quick startup guide, and
23872 details some Gnat-specific features.
23873
23874 @menu
23875 * Quick startup guide::
23876 * Gnat specifics::
23877 @end menu
23878
23879 @node Quick startup guide
23880 @subsection Quick startup guide
23881
23882 In order to perform coverage analysis of a program using @code{gcov}, 3
23883 steps are needed:
23884
23885 @itemize @bullet
23886 @item
23887 Code instrumentation during the compilation process
23888 @item
23889 Execution of the instrumented program
23890 @item
23891 Execution of the @code{gcov} tool to generate the result.
23892 @end itemize
23893
23894 The code instrumentation needed by gcov is created at the object level:
23895 The source code is not modified in any way, because the instrumentation code is
23896 inserted by gcc during the compilation process. To compile your code with code
23897 coverage activated, you need to recompile your whole project using the
23898 switches
23899 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23900 @code{-fprofile-arcs}.
23901
23902 @smallexample
23903 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23904    -largs -fprofile-arcs
23905 @end smallexample
23906
23907 This compilation process will create @file{.gcno} files together with
23908 the usual object files.
23909
23910 Once the program is compiled with coverage instrumentation, you can
23911 run it as many times as needed - on portions of a test suite for
23912 example. The first execution will produce @file{.gcda} files at the
23913 same location as the @file{.gcno} files.  The following executions
23914 will update those files, so that a cumulative result of the covered
23915 portions of the program is generated.
23916
23917 Finally, you need to call the @code{gcov} tool. The different options of
23918 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23919
23920 This will create annotated source files with a @file{.gcov} extension:
23921 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23922
23923 @node Gnat specifics
23924 @subsection Gnat specifics
23925
23926 Because Ada semantics, portions of the source code may be shared among
23927 several object files. This is the case for example when generics are
23928 involved, when inlining is active  or when declarations generate  initialisation
23929 calls. In order to take
23930 into account this shared code, you need to call @code{gcov} on all
23931 source files of the tested program at once.
23932
23933 The list of source files might exceed the system's maximum command line
23934 length. In order to bypass this limitation, a new mechanism has been
23935 implemented in @code{gcov}: you can now list all your project's files into a
23936 text file, and provide this file to gcov as a parameter,  preceded by a @@
23937 (e.g. @samp{gcov @@mysrclist.txt}).
23938
23939 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23940 not supported as there can be unresolved symbols during the final link.
23941
23942 @node Profiling an Ada Program using gprof
23943 @section Profiling an Ada Program using gprof
23944 @cindex gprof
23945 @cindex -pg
23946 @cindex Profiling
23947
23948 @noindent
23949 This section is not meant to be an exhaustive documentation of @code{gprof}.
23950 Full documentation for it can be found in the GNU Profiler User's Guide
23951 documentation that is part of this GNAT distribution.
23952
23953 Profiling a program helps determine the parts of a program that are executed
23954 most often, and are therefore the most time-consuming.
23955
23956 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23957 better handle Ada programs and multitasking.
23958 It is currently supported on the following platforms
23959 @itemize @bullet
23960 @item
23961 linux x86/x86_64
23962 @item
23963 solaris sparc/sparc64/x86
23964 @item
23965 windows x86
23966 @end itemize
23967
23968 @noindent
23969 In order to profile a program using @code{gprof}, 3 steps are needed:
23970
23971 @itemize @bullet
23972 @item
23973 Code instrumentation, requiring a full recompilation of the project with the
23974 proper switches.
23975 @item
23976 Execution of the program under the analysis conditions, i.e. with the desired
23977 input.
23978 @item
23979 Analysis of the results using the @code{gprof} tool.
23980 @end itemize
23981
23982 @noindent
23983 The following sections detail the different steps, and indicate how
23984 to interpret the results:
23985 @menu
23986 * Compilation for profiling::
23987 * Program execution::
23988 * Running gprof::
23989 * Interpretation of profiling results::
23990 @end menu
23991
23992 @node Compilation for profiling
23993 @subsection Compilation for profiling
23994 @cindex -pg
23995 @cindex Profiling
23996
23997 In order to profile a program the first step is to tell the compiler
23998 to generate the necessary profiling information. The compiler switch to be used
23999 is @code{-pg}, which must be added to other compilation switches. This
24000 switch needs to be specified both during compilation and link stages, and can
24001 be specified once when using gnatmake:
24002
24003 @smallexample
24004 gnatmake -f -pg -P my_project
24005 @end smallexample
24006
24007 @noindent
24008 Note that only the objects that were compiled with the @samp{-pg} switch will be
24009 profiled; if you need to profile your whole project, use the
24010 @samp{-f} gnatmake switch to force full recompilation.
24011
24012 @node Program execution
24013 @subsection Program execution
24014
24015 @noindent
24016 Once the program has been compiled for profiling, you can run it as usual.
24017
24018 The only constraint imposed by profiling is that the program must terminate
24019 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
24020 properly analyzed.
24021
24022 Once the program completes execution, a data file called @file{gmon.out} is
24023 generated in the directory where the program was launched from. If this file
24024 already exists, it will be overwritten.
24025
24026 @node Running gprof
24027 @subsection Running gprof
24028
24029 @noindent
24030 The @code{gprof} tool is called as follow:
24031
24032 @smallexample
24033 gprof my_prog gmon.out
24034 @end smallexample
24035
24036 @noindent
24037 or simpler:
24038
24039 @smallexample
24040 gprof my_prog
24041 @end smallexample
24042
24043 @noindent
24044 The complete form of the gprof command line is the following:
24045
24046 @smallexample
24047 gprof [^switches^options^] [executable [data-file]]
24048 @end smallexample
24049
24050 @noindent
24051 @code{gprof} supports numerous ^switch^options^. The order of these
24052 ^switch^options^ does not matter. The full list of options can be found in
24053 the GNU Profiler User's Guide documentation that comes with this documentation.
24054
24055 The following is the subset of those switches that is most relevant:
24056
24057 @table @option
24058
24059 @item --demangle[=@var{style}]
24060 @itemx --no-demangle
24061 @cindex @option{--demangle} (@code{gprof})
24062 These options control whether symbol names should be demangled when
24063 printing output.  The default is to demangle C++ symbols.  The
24064 @code{--no-demangle} option may be used to turn off demangling. Different
24065 compilers have different mangling styles.  The optional demangling style
24066 argument can be used to choose an appropriate demangling style for your
24067 compiler, in particular Ada symbols generated by GNAT can be demangled using
24068 @code{--demangle=gnat}.
24069
24070 @item -e @var{function_name}
24071 @cindex @option{-e} (@code{gprof})
24072 The @samp{-e @var{function}} option tells @code{gprof} not to print
24073 information about the function @var{function_name} (and its
24074 children@dots{}) in the call graph.  The function will still be listed
24075 as a child of any functions that call it, but its index number will be
24076 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
24077 given; only one @var{function_name} may be indicated with each @samp{-e}
24078 option.
24079
24080 @item -E @var{function_name}
24081 @cindex @option{-E} (@code{gprof})
24082 The @code{-E @var{function}} option works like the @code{-e} option, but
24083 execution time spent in the function (and children who were not called from
24084 anywhere else), will not be used to compute the percentages-of-time for
24085 the call graph.  More than one @samp{-E} option may be given; only one
24086 @var{function_name} may be indicated with each @samp{-E} option.
24087
24088 @item -f @var{function_name}
24089 @cindex @option{-f} (@code{gprof})
24090 The @samp{-f @var{function}} option causes @code{gprof} to limit the
24091 call graph to the function @var{function_name} and its children (and
24092 their children@dots{}).  More than one @samp{-f} option may be given;
24093 only one @var{function_name} may be indicated with each @samp{-f}
24094 option.
24095
24096 @item -F @var{function_name}
24097 @cindex @option{-F} (@code{gprof})
24098 The @samp{-F @var{function}} option works like the @code{-f} option, but
24099 only time spent in the function and its children (and their
24100 children@dots{}) will be used to determine total-time and
24101 percentages-of-time for the call graph.  More than one @samp{-F} option
24102 may be given; only one @var{function_name} may be indicated with each
24103 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
24104
24105 @end table
24106
24107 @node Interpretation of profiling results
24108 @subsection Interpretation of profiling results
24109
24110 @noindent
24111
24112 The results of the profiling analysis are represented by two arrays: the
24113 'flat profile' and the 'call graph'. Full documentation of those outputs
24114 can be found in the GNU Profiler User's Guide.
24115
24116 The flat profile shows the time spent in each function of the program, and how
24117 many time it has been called. This allows you to locate easily the most
24118 time-consuming functions.
24119
24120 The call graph shows, for each subprogram, the subprograms that call it,
24121 and the subprograms that it calls. It also provides an estimate of the time
24122 spent in each of those callers/called subprograms.
24123 @end ifclear
24124
24125 @c ******************************
24126 @node Running and Debugging Ada Programs
24127 @chapter Running and Debugging Ada Programs
24128 @cindex Debugging
24129
24130 @noindent
24131 This chapter discusses how to debug Ada programs.
24132 @ifset vms
24133 It applies to GNAT on the Alpha OpenVMS platform;
24134 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
24135 since HP has implemented Ada support in the OpenVMS debugger on I64.
24136 @end ifset
24137
24138 An incorrect Ada program may be handled in three ways by the GNAT compiler:
24139
24140 @enumerate
24141 @item
24142 The illegality may be a violation of the static semantics of Ada. In
24143 that case GNAT diagnoses the constructs in the program that are illegal.
24144 It is then a straightforward matter for the user to modify those parts of
24145 the program.
24146
24147 @item
24148 The illegality may be a violation of the dynamic semantics of Ada. In
24149 that case the program compiles and executes, but may generate incorrect
24150 results, or may terminate abnormally with some exception.
24151
24152 @item
24153 When presented with a program that contains convoluted errors, GNAT
24154 itself may terminate abnormally without providing full diagnostics on
24155 the incorrect user program.
24156 @end enumerate
24157
24158 @menu
24159 * The GNAT Debugger GDB::
24160 * Running GDB::
24161 * Introduction to GDB Commands::
24162 * Using Ada Expressions::
24163 * Calling User-Defined Subprograms::
24164 * Using the Next Command in a Function::
24165 * Ada Exceptions::
24166 * Ada Tasks::
24167 * Debugging Generic Units::
24168 * GNAT Abnormal Termination or Failure to Terminate::
24169 * Naming Conventions for GNAT Source Files::
24170 * Getting Internal Debugging Information::
24171 * Stack Traceback::
24172 @end menu
24173
24174 @cindex Debugger
24175 @findex gdb
24176
24177 @node The GNAT Debugger GDB
24178 @section The GNAT Debugger GDB
24179
24180 @noindent
24181 @code{GDB} is a general purpose, platform-independent debugger that
24182 can be used to debug mixed-language programs compiled with @command{gcc},
24183 and in particular is capable of debugging Ada programs compiled with
24184 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
24185 complex Ada data structures.
24186
24187 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
24188 @ifset vms
24189 located in the GNU:[DOCS] directory,
24190 @end ifset
24191 for full details on the usage of @code{GDB}, including a section on
24192 its usage on programs. This manual should be consulted for full
24193 details. The section that follows is a brief introduction to the
24194 philosophy and use of @code{GDB}.
24195
24196 When GNAT programs are compiled, the compiler optionally writes debugging
24197 information into the generated object file, including information on
24198 line numbers, and on declared types and variables. This information is
24199 separate from the generated code. It makes the object files considerably
24200 larger, but it does not add to the size of the actual executable that
24201 will be loaded into memory, and has no impact on run-time performance. The
24202 generation of debug information is triggered by the use of the
24203 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
24204 used to carry out the compilations. It is important to emphasize that
24205 the use of these options does not change the generated code.
24206
24207 The debugging information is written in standard system formats that
24208 are used by many tools, including debuggers and profilers. The format
24209 of the information is typically designed to describe C types and
24210 semantics, but GNAT implements a translation scheme which allows full
24211 details about Ada types and variables to be encoded into these
24212 standard C formats. Details of this encoding scheme may be found in
24213 the file exp_dbug.ads in the GNAT source distribution. However, the
24214 details of this encoding are, in general, of no interest to a user,
24215 since @code{GDB} automatically performs the necessary decoding.
24216
24217 When a program is bound and linked, the debugging information is
24218 collected from the object files, and stored in the executable image of
24219 the program. Again, this process significantly increases the size of
24220 the generated executable file, but it does not increase the size of
24221 the executable program itself. Furthermore, if this program is run in
24222 the normal manner, it runs exactly as if the debug information were
24223 not present, and takes no more actual memory.
24224
24225 However, if the program is run under control of @code{GDB}, the
24226 debugger is activated.  The image of the program is loaded, at which
24227 point it is ready to run.  If a run command is given, then the program
24228 will run exactly as it would have if @code{GDB} were not present. This
24229 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
24230 entirely non-intrusive until a breakpoint is encountered.  If no
24231 breakpoint is ever hit, the program will run exactly as it would if no
24232 debugger were present. When a breakpoint is hit, @code{GDB} accesses
24233 the debugging information and can respond to user commands to inspect
24234 variables, and more generally to report on the state of execution.
24235
24236 @c **************
24237 @node Running GDB
24238 @section Running GDB
24239
24240 @noindent
24241 This section describes how to initiate the debugger.
24242 @c The above sentence is really just filler, but it was otherwise
24243 @c clumsy to get the first paragraph nonindented given the conditional
24244 @c nature of the description
24245
24246 @ifclear vms
24247 The debugger can be launched from a @code{GPS} menu or
24248 directly from the command line. The description below covers the latter use.
24249 All the commands shown can be used in the @code{GPS} debug console window,
24250 but there are usually more GUI-based ways to achieve the same effect.
24251 @end ifclear
24252
24253 The command to run @code{GDB} is
24254
24255 @smallexample
24256 $ ^gdb program^GDB PROGRAM^
24257 @end smallexample
24258
24259 @noindent
24260 where @code{^program^PROGRAM^} is the name of the executable file. This
24261 activates the debugger and results in a prompt for debugger commands.
24262 The simplest command is simply @code{run}, which causes the program to run
24263 exactly as if the debugger were not present. The following section
24264 describes some of the additional commands that can be given to @code{GDB}.
24265
24266 @c *******************************
24267 @node Introduction to GDB Commands
24268 @section Introduction to GDB Commands
24269
24270 @noindent
24271 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24272 Debugging with GDB, gdb, Debugging with GDB},
24273 @ifset vms
24274 located in the GNU:[DOCS] directory,
24275 @end ifset
24276 for extensive documentation on the use
24277 of these commands, together with examples of their use. Furthermore,
24278 the command @command{help} invoked from within GDB activates a simple help
24279 facility which summarizes the available commands and their options.
24280 In this section we summarize a few of the most commonly
24281 used commands to give an idea of what @code{GDB} is about. You should create
24282 a simple program with debugging information and experiment with the use of
24283 these @code{GDB} commands on the program as you read through the
24284 following section.
24285
24286 @table @code
24287 @item set args @var{arguments}
24288 The @var{arguments} list above is a list of arguments to be passed to
24289 the program on a subsequent run command, just as though the arguments
24290 had been entered on a normal invocation of the program. The @code{set args}
24291 command is not needed if the program does not require arguments.
24292
24293 @item run
24294 The @code{run} command causes execution of the program to start from
24295 the beginning. If the program is already running, that is to say if
24296 you are currently positioned at a breakpoint, then a prompt will ask
24297 for confirmation that you want to abandon the current execution and
24298 restart.
24299
24300 @item breakpoint @var{location}
24301 The breakpoint command sets a breakpoint, that is to say a point at which
24302 execution will halt and @code{GDB} will await further
24303 commands. @var{location} is
24304 either a line number within a file, given in the format @code{file:linenumber},
24305 or it is the name of a subprogram. If you request that a breakpoint be set on
24306 a subprogram that is overloaded, a prompt will ask you to specify on which of
24307 those subprograms you want to breakpoint. You can also
24308 specify that all of them should be breakpointed. If the program is run
24309 and execution encounters the breakpoint, then the program
24310 stops and @code{GDB} signals that the breakpoint was encountered by
24311 printing the line of code before which the program is halted.
24312
24313 @item breakpoint exception @var{name}
24314 A special form of the breakpoint command which breakpoints whenever
24315 exception @var{name} is raised.
24316 If @var{name} is omitted,
24317 then a breakpoint will occur when any exception is raised.
24318
24319 @item print @var{expression}
24320 This will print the value of the given expression. Most simple
24321 Ada expression formats are properly handled by @code{GDB}, so the expression
24322 can contain function calls, variables, operators, and attribute references.
24323
24324 @item continue
24325 Continues execution following a breakpoint, until the next breakpoint or the
24326 termination of the program.
24327
24328 @item step
24329 Executes a single line after a breakpoint. If the next statement
24330 is a subprogram call, execution continues into (the first statement of)
24331 the called subprogram.
24332
24333 @item next
24334 Executes a single line. If this line is a subprogram call, executes and
24335 returns from the call.
24336
24337 @item list
24338 Lists a few lines around the current source location. In practice, it
24339 is usually more convenient to have a separate edit window open with the
24340 relevant source file displayed. Successive applications of this command
24341 print subsequent lines. The command can be given an argument which is a
24342 line number, in which case it displays a few lines around the specified one.
24343
24344 @item backtrace
24345 Displays a backtrace of the call chain. This command is typically
24346 used after a breakpoint has occurred, to examine the sequence of calls that
24347 leads to the current breakpoint. The display includes one line for each
24348 activation record (frame) corresponding to an active subprogram.
24349
24350 @item up
24351 At a breakpoint, @code{GDB} can display the values of variables local
24352 to the current frame. The command @code{up} can be used to
24353 examine the contents of other active frames, by moving the focus up
24354 the stack, that is to say from callee to caller, one frame at a time.
24355
24356 @item down
24357 Moves the focus of @code{GDB} down from the frame currently being
24358 examined to the frame of its callee (the reverse of the previous command),
24359
24360 @item frame @var{n}
24361 Inspect the frame with the given number. The value 0 denotes the frame
24362 of the current breakpoint, that is to say the top of the call stack.
24363
24364 @end table
24365
24366 @noindent
24367 The above list is a very short introduction to the commands that
24368 @code{GDB} provides. Important additional capabilities, including conditional
24369 breakpoints, the ability to execute command sequences on a breakpoint,
24370 the ability to debug at the machine instruction level and many other
24371 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24372 Debugging with GDB}.  Note that most commands can be abbreviated
24373 (for example, c for continue, bt for backtrace).
24374
24375 @node Using Ada Expressions
24376 @section Using Ada Expressions
24377 @cindex Ada expressions
24378
24379 @noindent
24380 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24381 extensions. The philosophy behind the design of this subset is
24382
24383 @itemize @bullet
24384 @item
24385 That @code{GDB} should provide basic literals and access to operations for
24386 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24387 leaving more sophisticated computations to subprograms written into the
24388 program (which therefore may be called from @code{GDB}).
24389
24390 @item
24391 That type safety and strict adherence to Ada language restrictions
24392 are not particularly important to the @code{GDB} user.
24393
24394 @item
24395 That brevity is important to the @code{GDB} user.
24396 @end itemize
24397
24398 @noindent
24399 Thus, for brevity, the debugger acts as if there were
24400 implicit @code{with} and @code{use} clauses in effect for all user-written
24401 packages, thus making it unnecessary to fully qualify most names with
24402 their packages, regardless of context. Where this causes ambiguity,
24403 @code{GDB} asks the user's intent.
24404
24405 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24406 GDB, gdb, Debugging with GDB}.
24407
24408 @node Calling User-Defined Subprograms
24409 @section Calling User-Defined Subprograms
24410
24411 @noindent
24412 An important capability of @code{GDB} is the ability to call user-defined
24413 subprograms while debugging. This is achieved simply by entering
24414 a subprogram call statement in the form:
24415
24416 @smallexample
24417 call subprogram-name (parameters)
24418 @end smallexample
24419
24420 @noindent
24421 The keyword @code{call} can be omitted in the normal case where the
24422 @code{subprogram-name} does not coincide with any of the predefined
24423 @code{GDB} commands.
24424
24425 The effect is to invoke the given subprogram, passing it the
24426 list of parameters that is supplied. The parameters can be expressions and
24427 can include variables from the program being debugged. The
24428 subprogram must be defined
24429 at the library level within your program, and @code{GDB} will call the
24430 subprogram within the environment of your program execution (which
24431 means that the subprogram is free to access or even modify variables
24432 within your program).
24433
24434 The most important use of this facility is in allowing the inclusion of
24435 debugging routines that are tailored to particular data structures
24436 in your program. Such debugging routines can be written to provide a suitably
24437 high-level description of an abstract type, rather than a low-level dump
24438 of its physical layout. After all, the standard
24439 @code{GDB print} command only knows the physical layout of your
24440 types, not their abstract meaning. Debugging routines can provide information
24441 at the desired semantic level and are thus enormously useful.
24442
24443 For example, when debugging GNAT itself, it is crucial to have access to
24444 the contents of the tree nodes used to represent the program internally.
24445 But tree nodes are represented simply by an integer value (which in turn
24446 is an index into a table of nodes).
24447 Using the @code{print} command on a tree node would simply print this integer
24448 value, which is not very useful. But the PN routine (defined in file
24449 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24450 a useful high level representation of the tree node, which includes the
24451 syntactic category of the node, its position in the source, the integers
24452 that denote descendant nodes and parent node, as well as varied
24453 semantic information. To study this example in more detail, you might want to
24454 look at the body of the PN procedure in the stated file.
24455
24456 @node Using the Next Command in a Function
24457 @section Using the Next Command in a Function
24458
24459 @noindent
24460 When you use the @code{next} command in a function, the current source
24461 location will advance to the next statement as usual. A special case
24462 arises in the case of a @code{return} statement.
24463
24464 Part of the code for a return statement is the ``epilog'' of the function.
24465 This is the code that returns to the caller. There is only one copy of
24466 this epilog code, and it is typically associated with the last return
24467 statement in the function if there is more than one return. In some
24468 implementations, this epilog is associated with the first statement
24469 of the function.
24470
24471 The result is that if you use the @code{next} command from a return
24472 statement that is not the last return statement of the function you
24473 may see a strange apparent jump to the last return statement or to
24474 the start of the function. You should simply ignore this odd jump.
24475 The value returned is always that from the first return statement
24476 that was stepped through.
24477
24478 @node Ada Exceptions
24479 @section Breaking on Ada Exceptions
24480 @cindex Exceptions
24481
24482 @noindent
24483 You can set breakpoints that trip when your program raises
24484 selected exceptions.
24485
24486 @table @code
24487 @item break exception
24488 Set a breakpoint that trips whenever (any task in the) program raises
24489 any exception.
24490
24491 @item break exception @var{name}
24492 Set a breakpoint that trips whenever (any task in the) program raises
24493 the exception @var{name}.
24494
24495 @item break exception unhandled
24496 Set a breakpoint that trips whenever (any task in the) program raises an
24497 exception for which there is no handler.
24498
24499 @item info exceptions
24500 @itemx info exceptions @var{regexp}
24501 The @code{info exceptions} command permits the user to examine all defined
24502 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24503 argument, prints out only those exceptions whose name matches @var{regexp}.
24504 @end table
24505
24506 @node Ada Tasks
24507 @section Ada Tasks
24508 @cindex Tasks
24509
24510 @noindent
24511 @code{GDB} allows the following task-related commands:
24512
24513 @table @code
24514 @item info tasks
24515 This command shows a list of current Ada tasks, as in the following example:
24516
24517 @smallexample
24518 @iftex
24519 @leftskip=0cm
24520 @end iftex
24521 (gdb) info tasks
24522   ID       TID P-ID   Thread Pri State                 Name
24523    1   8088000   0   807e000  15 Child Activation Wait main_task
24524    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24525    3   809a800   1   80a4800  15 Child Activation Wait a
24526 *  4   80ae800   3   80b8000  15 Running               c
24527 @end smallexample
24528
24529 @noindent
24530 In this listing, the asterisk before the first task indicates it to be the
24531 currently running task. The first column lists the task ID that is used
24532 to refer to tasks in the following commands.
24533
24534 @item break @var{linespec} task @var{taskid}
24535 @itemx break @var{linespec} task @var{taskid} if @dots{}
24536 @cindex Breakpoints and tasks
24537 These commands are like the @code{break @dots{} thread @dots{}}.
24538 @var{linespec} specifies source lines.
24539
24540 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24541 to specify that you only want @code{GDB} to stop the program when a
24542 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24543 numeric task identifiers assigned by @code{GDB}, shown in the first
24544 column of the @samp{info tasks} display.
24545
24546 If you do not specify @samp{task @var{taskid}} when you set a
24547 breakpoint, the breakpoint applies to @emph{all} tasks of your
24548 program.
24549
24550 You can use the @code{task} qualifier on conditional breakpoints as
24551 well; in this case, place @samp{task @var{taskid}} before the
24552 breakpoint condition (before the @code{if}).
24553
24554 @item task @var{taskno}
24555 @cindex Task switching
24556
24557 This command allows to switch to the task referred by @var{taskno}. In
24558 particular, This allows to browse the backtrace of the specified
24559 task. It is advised to switch back to the original task before
24560 continuing execution otherwise the scheduling of the program may be
24561 perturbed.
24562 @end table
24563
24564 @noindent
24565 For more detailed information on the tasking support,
24566 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24567
24568 @node Debugging Generic Units
24569 @section Debugging Generic Units
24570 @cindex Debugging Generic Units
24571 @cindex Generics
24572
24573 @noindent
24574 GNAT always uses code expansion for generic instantiation. This means that
24575 each time an instantiation occurs, a complete copy of the original code is
24576 made, with appropriate substitutions of formals by actuals.
24577
24578 It is not possible to refer to the original generic entities in
24579 @code{GDB}, but it is always possible to debug a particular instance of
24580 a generic, by using the appropriate expanded names. For example, if we have
24581
24582 @smallexample @c ada
24583 @group
24584 @cartouche
24585 procedure g is
24586
24587    generic package k is
24588       procedure kp (v1 : in out integer);
24589    end k;
24590
24591    package body k is
24592       procedure kp (v1 : in out integer) is
24593       begin
24594          v1 := v1 + 1;
24595       end kp;
24596    end k;
24597
24598    package k1 is new k;
24599    package k2 is new k;
24600
24601    var : integer := 1;
24602
24603 begin
24604    k1.kp (var);
24605    k2.kp (var);
24606    k1.kp (var);
24607    k2.kp (var);
24608 end;
24609 @end cartouche
24610 @end group
24611 @end smallexample
24612
24613 @noindent
24614 Then to break on a call to procedure kp in the k2 instance, simply
24615 use the command:
24616
24617 @smallexample
24618 (gdb) break g.k2.kp
24619 @end smallexample
24620
24621 @noindent
24622 When the breakpoint occurs, you can step through the code of the
24623 instance in the normal manner and examine the values of local variables, as for
24624 other units.
24625
24626 @node GNAT Abnormal Termination or Failure to Terminate
24627 @section GNAT Abnormal Termination or Failure to Terminate
24628 @cindex GNAT Abnormal Termination or Failure to Terminate
24629
24630 @noindent
24631 When presented with programs that contain serious errors in syntax
24632 or semantics,
24633 GNAT may on rare occasions  experience problems in operation, such
24634 as aborting with a
24635 segmentation fault or illegal memory access, raising an internal
24636 exception, terminating abnormally, or failing to terminate at all.
24637 In such cases, you can activate
24638 various features of GNAT that can help you pinpoint the construct in your
24639 program that is the likely source of the problem.
24640
24641 The following strategies are presented in increasing order of
24642 difficulty, corresponding to your experience in using GNAT and your
24643 familiarity with compiler internals.
24644
24645 @enumerate
24646 @item
24647 Run @command{gcc} with the @option{-gnatf}. This first
24648 switch causes all errors on a given line to be reported. In its absence,
24649 only the first error on a line is displayed.
24650
24651 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24652 are encountered, rather than after compilation is terminated. If GNAT
24653 terminates prematurely or goes into an infinite loop, the last error
24654 message displayed may help to pinpoint the culprit.
24655
24656 @item
24657 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24658 mode, @command{gcc} produces ongoing information about the progress of the
24659 compilation and provides the name of each procedure as code is
24660 generated. This switch allows you to find which Ada procedure was being
24661 compiled when it encountered a code generation problem.
24662
24663 @item
24664 @cindex @option{-gnatdc} switch
24665 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24666 switch that does for the front-end what @option{^-v^VERBOSE^} does
24667 for the back end. The system prints the name of each unit,
24668 either a compilation unit or nested unit, as it is being analyzed.
24669 @item
24670 Finally, you can start
24671 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24672 front-end of GNAT, and can be run independently (normally it is just
24673 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24674 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24675 @code{where} command is the first line of attack; the variable
24676 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24677 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24678 which the execution stopped, and @code{input_file name} indicates the name of
24679 the source file.
24680 @end enumerate
24681
24682 @node Naming Conventions for GNAT Source Files
24683 @section Naming Conventions for GNAT Source Files
24684
24685 @noindent
24686 In order to examine the workings of the GNAT system, the following
24687 brief description of its organization may be helpful:
24688
24689 @itemize @bullet
24690 @item
24691 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24692
24693 @item
24694 All files prefixed with @file{^par^PAR^} are components of the parser. The
24695 numbers correspond to chapters of the Ada Reference Manual. For example,
24696 parsing of select statements can be found in @file{par-ch9.adb}.
24697
24698 @item
24699 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24700 numbers correspond to chapters of the Ada standard. For example, all
24701 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24702 addition, some features of the language require sufficient special processing
24703 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24704 dynamic dispatching, etc.
24705
24706 @item
24707 All files prefixed with @file{^exp^EXP^} perform normalization and
24708 expansion of the intermediate representation (abstract syntax tree, or AST).
24709 these files use the same numbering scheme as the parser and semantics files.
24710 For example, the construction of record initialization procedures is done in
24711 @file{exp_ch3.adb}.
24712
24713 @item
24714 The files prefixed with @file{^bind^BIND^} implement the binder, which
24715 verifies the consistency of the compilation, determines an order of
24716 elaboration, and generates the bind file.
24717
24718 @item
24719 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24720 data structures used by the front-end.
24721
24722 @item
24723 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24724 the abstract syntax tree as produced by the parser.
24725
24726 @item
24727 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24728 all entities, computed during semantic analysis.
24729
24730 @item
24731 Library management issues are dealt with in files with prefix
24732 @file{^lib^LIB^}.
24733
24734 @item
24735 @findex Ada
24736 @cindex Annex A
24737 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24738 defined in Annex A.
24739
24740 @item
24741 @findex Interfaces
24742 @cindex Annex B
24743 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24744 defined in Annex B.
24745
24746 @item
24747 @findex System
24748 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24749 both language-defined children and GNAT run-time routines.
24750
24751 @item
24752 @findex GNAT
24753 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24754 general-purpose packages, fully documented in their specs. All
24755 the other @file{.c} files are modifications of common @command{gcc} files.
24756 @end itemize
24757
24758 @node Getting Internal Debugging Information
24759 @section Getting Internal Debugging Information
24760
24761 @noindent
24762 Most compilers have internal debugging switches and modes. GNAT
24763 does also, except GNAT internal debugging switches and modes are not
24764 secret. A summary and full description of all the compiler and binder
24765 debug flags are in the file @file{debug.adb}. You must obtain the
24766 sources of the compiler to see the full detailed effects of these flags.
24767
24768 The switches that print the source of the program (reconstructed from
24769 the internal tree) are of general interest for user programs, as are the
24770 options to print
24771 the full internal tree, and the entity table (the symbol table
24772 information). The reconstructed source provides a readable version of the
24773 program after the front-end has completed analysis and  expansion,
24774 and is useful when studying the performance of specific constructs.
24775 For example, constraint checks are indicated, complex aggregates
24776 are replaced with loops and assignments, and tasking primitives
24777 are replaced with run-time calls.
24778
24779 @node Stack Traceback
24780 @section Stack Traceback
24781 @cindex traceback
24782 @cindex stack traceback
24783 @cindex stack unwinding
24784
24785 @noindent
24786 Traceback is a mechanism to display the sequence of subprogram calls that
24787 leads to a specified execution point in a program. Often (but not always)
24788 the execution point is an instruction at which an exception has been raised.
24789 This mechanism is also known as @i{stack unwinding} because it obtains
24790 its information by scanning the run-time stack and recovering the activation
24791 records of all active subprograms. Stack unwinding is one of the most
24792 important tools for program debugging.
24793
24794 The first entry stored in traceback corresponds to the deepest calling level,
24795 that is to say the subprogram currently executing the instruction
24796 from which we want to obtain the traceback.
24797
24798 Note that there is no runtime performance penalty when stack traceback
24799 is enabled, and no exception is raised during program execution.
24800
24801 @menu
24802 * Non-Symbolic Traceback::
24803 * Symbolic Traceback::
24804 @end menu
24805
24806 @node Non-Symbolic Traceback
24807 @subsection Non-Symbolic Traceback
24808 @cindex traceback, non-symbolic
24809
24810 @noindent
24811 Note: this feature is not supported on all platforms. See
24812 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24813 platforms.
24814
24815 @menu
24816 * Tracebacks From an Unhandled Exception::
24817 * Tracebacks From Exception Occurrences (non-symbolic)::
24818 * Tracebacks From Anywhere in a Program (non-symbolic)::
24819 @end menu
24820
24821 @node Tracebacks From an Unhandled Exception
24822 @subsubsection Tracebacks From an Unhandled Exception
24823
24824 @noindent
24825 A runtime non-symbolic traceback is a list of addresses of call instructions.
24826 To enable this feature you must use the @option{-E}
24827 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24828 of exception information. You can retrieve this information using the
24829 @code{addr2line} tool.
24830
24831 Here is a simple example:
24832
24833 @smallexample @c ada
24834 @cartouche
24835 procedure STB is
24836
24837    procedure P1 is
24838    begin
24839       raise Constraint_Error;
24840    end P1;
24841
24842    procedure P2 is
24843    begin
24844       P1;
24845    end P2;
24846
24847 begin
24848    P2;
24849 end STB;
24850 @end cartouche
24851 @end smallexample
24852
24853 @smallexample
24854 $ gnatmake stb -bargs -E
24855 $ stb
24856
24857 Execution terminated by unhandled exception
24858 Exception name: CONSTRAINT_ERROR
24859 Message: stb.adb:5
24860 Call stack traceback locations:
24861 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24862 @end smallexample
24863
24864 @noindent
24865 As we see the traceback lists a sequence of addresses for the unhandled
24866 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24867 guess that this exception come from procedure P1. To translate these
24868 addresses into the source lines where the calls appear, the
24869 @code{addr2line} tool, described below, is invaluable. The use of this tool
24870 requires the program to be compiled with debug information.
24871
24872 @smallexample
24873 $ gnatmake -g stb -bargs -E
24874 $ stb
24875
24876 Execution terminated by unhandled exception
24877 Exception name: CONSTRAINT_ERROR
24878 Message: stb.adb:5
24879 Call stack traceback locations:
24880 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24881
24882 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24883    0x4011f1 0x77e892a4
24884
24885 00401373 at d:/stb/stb.adb:5
24886 0040138B at d:/stb/stb.adb:10
24887 0040139C at d:/stb/stb.adb:14
24888 00401335 at d:/stb/b~stb.adb:104
24889 004011C4 at /build/@dots{}/crt1.c:200
24890 004011F1 at /build/@dots{}/crt1.c:222
24891 77E892A4 in ?? at ??:0
24892 @end smallexample
24893
24894 @noindent
24895 The @code{addr2line} tool has several other useful options:
24896
24897 @table @code
24898 @item --functions
24899 to get the function name corresponding to any location
24900
24901 @item --demangle=gnat
24902 to use the gnat decoding mode for the function names. Note that
24903 for binutils version 2.9.x the option is simply @option{--demangle}.
24904 @end table
24905
24906 @smallexample
24907 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24908    0x40139c 0x401335 0x4011c4 0x4011f1
24909
24910 00401373 in stb.p1 at d:/stb/stb.adb:5
24911 0040138B in stb.p2 at d:/stb/stb.adb:10
24912 0040139C in stb at d:/stb/stb.adb:14
24913 00401335 in main at d:/stb/b~stb.adb:104
24914 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24915 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24916 @end smallexample
24917
24918 @noindent
24919 From this traceback we can see that the exception was raised in
24920 @file{stb.adb} at line 5, which was reached from a procedure call in
24921 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24922 which contains the call to the main program.
24923 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24924 and the output will vary from platform to platform.
24925
24926 It is also possible to use @code{GDB} with these traceback addresses to debug
24927 the program. For example, we can break at a given code location, as reported
24928 in the stack traceback:
24929
24930 @smallexample
24931 $ gdb -nw stb
24932 @ifclear vms
24933 @noindent
24934 Furthermore, this feature is not implemented inside Windows DLL. Only
24935 the non-symbolic traceback is reported in this case.
24936 @end ifclear
24937
24938 (gdb) break *0x401373
24939 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24940 @end smallexample
24941
24942 @noindent
24943 It is important to note that the stack traceback addresses
24944 do not change when debug information is included. This is particularly useful
24945 because it makes it possible to release software without debug information (to
24946 minimize object size), get a field report that includes a stack traceback
24947 whenever an internal bug occurs, and then be able to retrieve the sequence
24948 of calls with the same program compiled with debug information.
24949
24950 @node Tracebacks From Exception Occurrences (non-symbolic)
24951 @subsubsection Tracebacks From Exception Occurrences
24952
24953 @noindent
24954 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24955 The stack traceback is attached to the exception information string, and can
24956 be retrieved in an exception handler within the Ada program, by means of the
24957 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24958
24959 @smallexample @c ada
24960 with Ada.Text_IO;
24961 with Ada.Exceptions;
24962
24963 procedure STB is
24964
24965    use Ada;
24966    use Ada.Exceptions;
24967
24968    procedure P1 is
24969       K : Positive := 1;
24970    begin
24971       K := K - 1;
24972    exception
24973       when E : others =>
24974          Text_IO.Put_Line (Exception_Information (E));
24975    end P1;
24976
24977    procedure P2 is
24978    begin
24979       P1;
24980    end P2;
24981
24982 begin
24983    P2;
24984 end STB;
24985 @end smallexample
24986
24987 @noindent
24988 This program will output:
24989
24990 @smallexample
24991 $ stb
24992
24993 Exception name: CONSTRAINT_ERROR
24994 Message: stb.adb:12
24995 Call stack traceback locations:
24996 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24997 @end smallexample
24998
24999 @node Tracebacks From Anywhere in a Program (non-symbolic)
25000 @subsubsection Tracebacks From Anywhere in a Program
25001
25002 @noindent
25003 It is also possible to retrieve a stack traceback from anywhere in a
25004 program. For this you need to
25005 use the @code{GNAT.Traceback} API. This package includes a procedure called
25006 @code{Call_Chain} that computes a complete stack traceback, as well as useful
25007 display procedures described below. It is not necessary to use the
25008 @option{-E gnatbind} option in this case, because the stack traceback mechanism
25009 is invoked explicitly.
25010
25011 @noindent
25012 In the following example we compute a traceback at a specific location in
25013 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
25014 convert addresses to strings:
25015
25016 @smallexample @c ada
25017 with Ada.Text_IO;
25018 with GNAT.Traceback;
25019 with GNAT.Debug_Utilities;
25020
25021 procedure STB is
25022
25023    use Ada;
25024    use GNAT;
25025    use GNAT.Traceback;
25026
25027    procedure P1 is
25028       TB  : Tracebacks_Array (1 .. 10);
25029       --  We are asking for a maximum of 10 stack frames.
25030       Len : Natural;
25031       --  Len will receive the actual number of stack frames returned.
25032    begin
25033       Call_Chain (TB, Len);
25034
25035       Text_IO.Put ("In STB.P1 : ");
25036
25037       for K in 1 .. Len loop
25038          Text_IO.Put (Debug_Utilities.Image (TB (K)));
25039          Text_IO.Put (' ');
25040       end loop;
25041
25042       Text_IO.New_Line;
25043    end P1;
25044
25045    procedure P2 is
25046    begin
25047       P1;
25048    end P2;
25049
25050 begin
25051    P2;
25052 end STB;
25053 @end smallexample
25054
25055 @smallexample
25056 $ gnatmake -g stb
25057 $ stb
25058
25059 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
25060 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
25061 @end smallexample
25062
25063 @noindent
25064 You can then get further information by invoking the @code{addr2line}
25065 tool as described earlier (note that the hexadecimal addresses
25066 need to be specified in C format, with a leading ``0x'').
25067
25068 @node Symbolic Traceback
25069 @subsection Symbolic Traceback
25070 @cindex traceback, symbolic
25071
25072 @noindent
25073 A symbolic traceback is a stack traceback in which procedure names are
25074 associated with each code location.
25075
25076 @noindent
25077 Note that this feature is not supported on all platforms. See
25078 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
25079 list of currently supported platforms.
25080
25081 @noindent
25082 Note that the symbolic traceback requires that the program be compiled
25083 with debug information. If it is not compiled with debug information
25084 only the non-symbolic information will be valid.
25085
25086 @menu
25087 * Tracebacks From Exception Occurrences (symbolic)::
25088 * Tracebacks From Anywhere in a Program (symbolic)::
25089 @end menu
25090
25091 @node Tracebacks From Exception Occurrences (symbolic)
25092 @subsubsection Tracebacks From Exception Occurrences
25093
25094 @smallexample @c ada
25095 with Ada.Text_IO;
25096 with GNAT.Traceback.Symbolic;
25097
25098 procedure STB is
25099
25100    procedure P1 is
25101    begin
25102       raise Constraint_Error;
25103    end P1;
25104
25105    procedure P2 is
25106    begin
25107       P1;
25108    end P2;
25109
25110    procedure P3 is
25111    begin
25112       P2;
25113    end P3;
25114
25115 begin
25116    P3;
25117 exception
25118    when E : others =>
25119       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
25120 end STB;
25121 @end smallexample
25122
25123 @smallexample
25124 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
25125 $ stb
25126
25127 0040149F in stb.p1 at stb.adb:8
25128 004014B7 in stb.p2 at stb.adb:13
25129 004014CF in stb.p3 at stb.adb:18
25130 004015DD in ada.stb at stb.adb:22
25131 00401461 in main at b~stb.adb:168
25132 004011C4 in __mingw_CRTStartup at crt1.c:200
25133 004011F1 in mainCRTStartup at crt1.c:222
25134 77E892A4 in ?? at ??:0
25135 @end smallexample
25136
25137 @noindent
25138 In the above example the ``.\'' syntax in the @command{gnatmake} command
25139 is currently required by @command{addr2line} for files that are in
25140 the current working directory.
25141 Moreover, the exact sequence of linker options may vary from platform
25142 to platform.
25143 The above @option{-largs} section is for Windows platforms. By contrast,
25144 under Unix there is no need for the @option{-largs} section.
25145 Differences across platforms are due to details of linker implementation.
25146
25147 @node Tracebacks From Anywhere in a Program (symbolic)
25148 @subsubsection Tracebacks From Anywhere in a Program
25149
25150 @noindent
25151 It is possible to get a symbolic stack traceback
25152 from anywhere in a program, just as for non-symbolic tracebacks.
25153 The first step is to obtain a non-symbolic
25154 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
25155 information. Here is an example:
25156
25157 @smallexample @c ada
25158 with Ada.Text_IO;
25159 with GNAT.Traceback;
25160 with GNAT.Traceback.Symbolic;
25161
25162 procedure STB is
25163
25164    use Ada;
25165    use GNAT.Traceback;
25166    use GNAT.Traceback.Symbolic;
25167
25168    procedure P1 is
25169       TB  : Tracebacks_Array (1 .. 10);
25170       --  We are asking for a maximum of 10 stack frames.
25171       Len : Natural;
25172       --  Len will receive the actual number of stack frames returned.
25173    begin
25174       Call_Chain (TB, Len);
25175       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
25176    end P1;
25177
25178    procedure P2 is
25179    begin
25180       P1;
25181    end P2;
25182
25183 begin
25184    P2;
25185 end STB;
25186 @end smallexample
25187
25188 @c ******************************
25189 @ifset vms
25190 @node Compatibility with HP Ada
25191 @chapter Compatibility with HP Ada
25192 @cindex Compatibility
25193
25194 @noindent
25195 @cindex DEC Ada
25196 @cindex HP Ada
25197 @cindex Compatibility between GNAT and HP Ada
25198 This chapter compares HP Ada (formerly known as ``DEC Ada'')
25199 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
25200 GNAT is highly compatible
25201 with HP Ada, and it should generally be straightforward to port code
25202 from the HP Ada environment to GNAT. However, there are a few language
25203 and implementation differences of which the user must be aware. These
25204 differences are discussed in this chapter. In
25205 addition, the operating environment and command structure for the
25206 compiler are different, and these differences are also discussed.
25207
25208 For further details on these and other compatibility issues,
25209 see Appendix E of the HP publication
25210 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
25211
25212 Except where otherwise indicated, the description of GNAT for OpenVMS
25213 applies to both the Alpha and I64 platforms.
25214
25215 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
25216 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25217
25218 The discussion in this chapter addresses specifically the implementation
25219 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
25220 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
25221 GNAT always follows the Alpha implementation.
25222
25223 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
25224 attributes are recognized, although only a subset of them can sensibly
25225 be implemented.  The description of pragmas in
25226 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
25227 indicates whether or not they are applicable to non-VMS systems.
25228
25229 @menu
25230 * Ada Language Compatibility::
25231 * Differences in the Definition of Package System::
25232 * Language-Related Features::
25233 * The Package STANDARD::
25234 * The Package SYSTEM::
25235 * Tasking and Task-Related Features::
25236 * Pragmas and Pragma-Related Features::
25237 * Library of Predefined Units::
25238 * Bindings::
25239 * Main Program Definition::
25240 * Implementation-Defined Attributes::
25241 * Compiler and Run-Time Interfacing::
25242 * Program Compilation and Library Management::
25243 * Input-Output::
25244 * Implementation Limits::
25245 * Tools and Utilities::
25246 @end menu
25247
25248 @node Ada Language Compatibility
25249 @section Ada Language Compatibility
25250
25251 @noindent
25252 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25253 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25254 with Ada 83, and therefore Ada 83 programs will compile
25255 and run under GNAT with
25256 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25257 provides details on specific incompatibilities.
25258
25259 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25260 as well as the pragma @code{ADA_83}, to force the compiler to
25261 operate in Ada 83 mode. This mode does not guarantee complete
25262 conformance to Ada 83, but in practice is sufficient to
25263 eliminate most sources of incompatibilities.
25264 In particular, it eliminates the recognition of the
25265 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25266 in Ada 83 programs is legal, and handles the cases of packages
25267 with optional bodies, and generics that instantiate unconstrained
25268 types without the use of @code{(<>)}.
25269
25270 @node Differences in the Definition of Package System
25271 @section Differences in the Definition of Package @code{System}
25272
25273 @noindent
25274 An Ada compiler is allowed to add
25275 implementation-dependent declarations to package @code{System}.
25276 In normal mode,
25277 GNAT does not take advantage of this permission, and the version of
25278 @code{System} provided by GNAT exactly matches that defined in the Ada
25279 Reference Manual.
25280
25281 However, HP Ada adds an extensive set of declarations to package
25282 @code{System},
25283 as fully documented in the HP Ada manuals. To minimize changes required
25284 for programs that make use of these extensions, GNAT provides the pragma
25285 @code{Extend_System} for extending the definition of package System. By using:
25286 @cindex pragma @code{Extend_System}
25287 @cindex @code{Extend_System} pragma
25288
25289 @smallexample @c ada
25290 @group
25291 @cartouche
25292 pragma Extend_System (Aux_DEC);
25293 @end cartouche
25294 @end group
25295 @end smallexample
25296
25297 @noindent
25298 the set of definitions in @code{System} is extended to include those in
25299 package @code{System.Aux_DEC}.
25300 @cindex @code{System.Aux_DEC} package
25301 @cindex @code{Aux_DEC} package (child of @code{System})
25302 These definitions are incorporated directly into package @code{System},
25303 as though they had been declared there. For a
25304 list of the declarations added, see the spec of this package,
25305 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25306 @cindex @file{s-auxdec.ads} file
25307 The pragma @code{Extend_System} is a configuration pragma, which means that
25308 it can be placed in the file @file{gnat.adc}, so that it will automatically
25309 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25310 for further details.
25311
25312 An alternative approach that avoids the use of the non-standard
25313 @code{Extend_System} pragma is to add a context clause to the unit that
25314 references these facilities:
25315
25316 @smallexample @c ada
25317 @cartouche
25318 with System.Aux_DEC;
25319 use  System.Aux_DEC;
25320 @end cartouche
25321 @end smallexample
25322
25323 @noindent
25324 The effect is not quite semantically identical to incorporating
25325 the declarations directly into package @code{System},
25326 but most programs will not notice a difference
25327 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25328 to reference the entities directly in package @code{System}.
25329 For units containing such references,
25330 the prefixes must either be removed, or the pragma @code{Extend_System}
25331 must be used.
25332
25333 @node Language-Related Features
25334 @section Language-Related Features
25335
25336 @noindent
25337 The following sections highlight differences in types,
25338 representations of types, operations, alignment, and
25339 related topics.
25340
25341 @menu
25342 * Integer Types and Representations::
25343 * Floating-Point Types and Representations::
25344 * Pragmas Float_Representation and Long_Float::
25345 * Fixed-Point Types and Representations::
25346 * Record and Array Component Alignment::
25347 * Address Clauses::
25348 * Other Representation Clauses::
25349 @end menu
25350
25351 @node Integer Types and Representations
25352 @subsection Integer Types and Representations
25353
25354 @noindent
25355 The set of predefined integer types is identical in HP Ada and GNAT.
25356 Furthermore the representation of these integer types is also identical,
25357 including the capability of size clauses forcing biased representation.
25358
25359 In addition,
25360 HP Ada for OpenVMS Alpha systems has defined the
25361 following additional integer types in package @code{System}:
25362
25363 @itemize @bullet
25364
25365 @item
25366 @code{INTEGER_8}
25367
25368 @item
25369 @code{INTEGER_16}
25370
25371 @item
25372 @code{INTEGER_32}
25373
25374 @item
25375 @code{INTEGER_64}
25376
25377 @item
25378 @code{LARGEST_INTEGER}
25379 @end itemize
25380
25381 @noindent
25382 In GNAT, the first four of these types may be obtained from the
25383 standard Ada package @code{Interfaces}.
25384 Alternatively, by use of the pragma @code{Extend_System}, identical
25385 declarations can be referenced directly in package @code{System}.
25386 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25387
25388 @node Floating-Point Types and Representations
25389 @subsection Floating-Point Types and Representations
25390 @cindex Floating-Point types
25391
25392 @noindent
25393 The set of predefined floating-point types is identical in HP Ada and GNAT.
25394 Furthermore the representation of these floating-point
25395 types is also identical. One important difference is that the default
25396 representation for HP Ada is @code{VAX_Float}, but the default representation
25397 for GNAT is IEEE.
25398
25399 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25400 pragma @code{Float_Representation} as described in the HP Ada
25401 documentation.
25402 For example, the declarations:
25403
25404 @smallexample @c ada
25405 @cartouche
25406 type F_Float is digits 6;
25407 pragma Float_Representation (VAX_Float, F_Float);
25408 @end cartouche
25409 @end smallexample
25410
25411 @noindent
25412 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25413 format.
25414 This set of declarations actually appears in @code{System.Aux_DEC},
25415 which contains
25416 the full set of additional floating-point declarations provided in
25417 the HP Ada version of package @code{System}.
25418 This and similar declarations may be accessed in a user program
25419 by using pragma @code{Extend_System}. The use of this
25420 pragma, and the related pragma @code{Long_Float} is described in further
25421 detail in the following section.
25422
25423 @node Pragmas Float_Representation and Long_Float
25424 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25425
25426 @noindent
25427 HP Ada provides the pragma @code{Float_Representation}, which
25428 acts as a program library switch to allow control over
25429 the internal representation chosen for the predefined
25430 floating-point types declared in the package @code{Standard}.
25431 The format of this pragma is as follows:
25432
25433 @smallexample @c ada
25434 @cartouche
25435 pragma Float_Representation(VAX_Float | IEEE_Float);
25436 @end cartouche
25437 @end smallexample
25438
25439 @noindent
25440 This pragma controls the representation of floating-point
25441 types as follows:
25442
25443 @itemize @bullet
25444 @item
25445 @code{VAX_Float} specifies that floating-point
25446 types are represented by default with the VAX system hardware types
25447 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25448 Note that the @code{H-floating}
25449 type was available only on VAX systems, and is not available
25450 in either HP Ada or GNAT.
25451
25452 @item
25453 @code{IEEE_Float} specifies that floating-point
25454 types are represented by default with the IEEE single and
25455 double floating-point types.
25456 @end itemize
25457
25458 @noindent
25459 GNAT provides an identical implementation of the pragma
25460 @code{Float_Representation}, except that it functions as a
25461 configuration pragma. Note that the
25462 notion of configuration pragma corresponds closely to the
25463 HP Ada notion of a program library switch.
25464
25465 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25466 which is different
25467 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25468 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25469 advisable to change the format of numbers passed to standard library
25470 routines, and if necessary explicit type conversions may be needed.
25471
25472 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25473 efficient, and (given that it conforms to an international standard)
25474 potentially more portable.
25475 The situation in which @code{VAX_Float} may be useful is in interfacing
25476 to existing code and data that expect the use of @code{VAX_Float}.
25477 In such a situation use the predefined @code{VAX_Float}
25478 types in package @code{System}, as extended by
25479 @code{Extend_System}. For example, use @code{System.F_Float}
25480 to specify the 32-bit @code{F-Float} format.
25481
25482 @noindent
25483 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25484 to allow control over the internal representation chosen
25485 for the predefined type @code{Long_Float} and for floating-point
25486 type declarations with digits specified in the range 7 .. 15.
25487 The format of this pragma is as follows:
25488
25489 @smallexample @c ada
25490 @cartouche
25491 pragma Long_Float (D_FLOAT | G_FLOAT);
25492 @end cartouche
25493 @end smallexample
25494
25495 @node Fixed-Point Types and Representations
25496 @subsection Fixed-Point Types and Representations
25497
25498 @noindent
25499 On HP Ada for OpenVMS Alpha systems, rounding is
25500 away from zero for both positive and negative numbers.
25501 Therefore, @code{+0.5} rounds to @code{1},
25502 and @code{-0.5} rounds to @code{-1}.
25503
25504 On GNAT the results of operations
25505 on fixed-point types are in accordance with the Ada
25506 rules. In particular, results of operations on decimal
25507 fixed-point types are truncated.
25508
25509 @node Record and Array Component Alignment
25510 @subsection Record and Array Component Alignment
25511
25512 @noindent
25513 On HP Ada for OpenVMS Alpha, all non-composite components
25514 are aligned on natural boundaries. For example, 1-byte
25515 components are aligned on byte boundaries, 2-byte
25516 components on 2-byte boundaries, 4-byte components on 4-byte
25517 byte boundaries, and so on. The OpenVMS Alpha hardware
25518 runs more efficiently with naturally aligned data.
25519
25520 On GNAT, alignment rules are compatible
25521 with HP Ada for OpenVMS Alpha.
25522
25523 @node Address Clauses
25524 @subsection Address Clauses
25525
25526 @noindent
25527 In HP Ada and GNAT, address clauses are supported for
25528 objects and imported subprograms.
25529 The predefined type @code{System.Address} is a private type
25530 in both compilers on Alpha OpenVMS, with the same representation
25531 (it is simply a machine pointer). Addition, subtraction, and comparison
25532 operations are available in the standard Ada package
25533 @code{System.Storage_Elements}, or in package @code{System}
25534 if it is extended to include @code{System.Aux_DEC} using a
25535 pragma @code{Extend_System} as previously described.
25536
25537 Note that code that @code{with}'s both this extended package @code{System}
25538 and the package @code{System.Storage_Elements} should not @code{use}
25539 both packages, or ambiguities will result. In general it is better
25540 not to mix these two sets of facilities. The Ada package was
25541 designed specifically to provide the kind of features that HP Ada
25542 adds directly to package @code{System}.
25543
25544 The type @code{System.Address} is a 64-bit integer type in GNAT for
25545 I64 OpenVMS.  For more information,
25546 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25547
25548 GNAT is compatible with HP Ada in its handling of address
25549 clauses, except for some limitations in
25550 the form of address clauses for composite objects with
25551 initialization. Such address clauses are easily replaced
25552 by the use of an explicitly-defined constant as described
25553 in the Ada Reference Manual (13.1(22)). For example, the sequence
25554 of declarations:
25555
25556 @smallexample @c ada
25557 @cartouche
25558 X, Y : Integer := Init_Func;
25559 Q : String (X .. Y) := "abc";
25560 @dots{}
25561 for Q'Address use Compute_Address;
25562 @end cartouche
25563 @end smallexample
25564
25565 @noindent
25566 will be rejected by GNAT, since the address cannot be computed at the time
25567 that @code{Q} is declared. To achieve the intended effect, write instead:
25568
25569 @smallexample @c ada
25570 @group
25571 @cartouche
25572 X, Y : Integer := Init_Func;
25573 Q_Address : constant Address := Compute_Address;
25574 Q : String (X .. Y) := "abc";
25575 @dots{}
25576 for Q'Address use Q_Address;
25577 @end cartouche
25578 @end group
25579 @end smallexample
25580
25581 @noindent
25582 which will be accepted by GNAT (and other Ada compilers), and is also
25583 compatible with Ada 83. A fuller description of the restrictions
25584 on address specifications is found in @ref{Top, GNAT Reference Manual,
25585 About This Guide, gnat_rm, GNAT Reference Manual}.
25586
25587 @node Other Representation Clauses
25588 @subsection Other Representation Clauses
25589
25590 @noindent
25591 GNAT implements in a compatible manner all the representation
25592 clauses supported by HP Ada. In addition, GNAT
25593 implements the representation clause forms that were introduced in Ada 95,
25594 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25595
25596 @node The Package STANDARD
25597 @section The Package @code{STANDARD}
25598
25599 @noindent
25600 The package @code{STANDARD}, as implemented by HP Ada, is fully
25601 described in the @cite{Ada Reference Manual} and in the
25602 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25603 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25604
25605 In addition, HP Ada supports the Latin-1 character set in
25606 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25607 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25608 the type @code{WIDE_CHARACTER}.
25609
25610 The floating-point types supported by GNAT are those
25611 supported by HP Ada, but the defaults are different, and are controlled by
25612 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25613
25614 @node The Package SYSTEM
25615 @section The Package @code{SYSTEM}
25616
25617 @noindent
25618 HP Ada provides a specific version of the package
25619 @code{SYSTEM} for each platform on which the language is implemented.
25620 For the complete spec of the package @code{SYSTEM}, see
25621 Appendix F of the @cite{HP Ada Language Reference Manual}.
25622
25623 On HP Ada, the package @code{SYSTEM} includes the following conversion
25624 functions:
25625 @itemize @bullet
25626 @item @code{TO_ADDRESS(INTEGER)}
25627
25628 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25629
25630 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25631
25632 @item @code{TO_INTEGER(ADDRESS)}
25633
25634 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25635
25636 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25637 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25638 @end itemize
25639
25640 @noindent
25641 By default, GNAT supplies a version of @code{SYSTEM} that matches
25642 the definition given in the @cite{Ada Reference Manual}.
25643 This
25644 is a subset of the HP system definitions, which is as
25645 close as possible to the original definitions. The only difference
25646 is that the definition of @code{SYSTEM_NAME} is different:
25647
25648 @smallexample @c ada
25649 @cartouche
25650 type Name is (SYSTEM_NAME_GNAT);
25651 System_Name : constant Name := SYSTEM_NAME_GNAT;
25652 @end cartouche
25653 @end smallexample
25654
25655 @noindent
25656 Also, GNAT adds the Ada declarations for
25657 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25658
25659 However, the use of the following pragma causes GNAT
25660 to extend the definition of package @code{SYSTEM} so that it
25661 encompasses the full set of HP-specific extensions,
25662 including the functions listed above:
25663
25664 @smallexample @c ada
25665 @cartouche
25666 pragma Extend_System (Aux_DEC);
25667 @end cartouche
25668 @end smallexample
25669
25670 @noindent
25671 The pragma @code{Extend_System} is a configuration pragma that
25672 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25673 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25674
25675 HP Ada does not allow the recompilation of the package
25676 @code{SYSTEM}. Instead HP Ada provides several pragmas
25677 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25678 to modify values in the package @code{SYSTEM}.
25679 On OpenVMS Alpha systems, the pragma
25680 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25681 its single argument.
25682
25683 GNAT does permit the recompilation of package @code{SYSTEM} using
25684 the special switch @option{-gnatg}, and this switch can be used if
25685 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25686 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25687 or @code{MEMORY_SIZE} by any other means.
25688
25689 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25690 enumeration literal @code{SYSTEM_NAME_GNAT}.
25691
25692 The definitions provided by the use of
25693
25694 @smallexample @c ada
25695 pragma Extend_System (AUX_Dec);
25696 @end smallexample
25697
25698 @noindent
25699 are virtually identical to those provided by the HP Ada 83 package
25700 @code{SYSTEM}. One important difference is that the name of the
25701 @code{TO_ADDRESS}
25702 function for type @code{UNSIGNED_LONGWORD} is changed to
25703 @code{TO_ADDRESS_LONG}.
25704 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25705 discussion of why this change was necessary.
25706
25707 @noindent
25708 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25709 is in fact
25710 an extension to Ada 83 not strictly compatible with the reference manual.
25711 GNAT, in order to be exactly compatible with the standard,
25712 does not provide this capability. In HP Ada 83, the
25713 point of this definition is to deal with a call like:
25714
25715 @smallexample @c ada
25716 TO_ADDRESS (16#12777#);
25717 @end smallexample
25718
25719 @noindent
25720 Normally, according to Ada 83 semantics, one would expect this to be
25721 ambiguous, since it matches both the @code{INTEGER} and
25722 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25723 However, in HP Ada 83, there is no ambiguity, since the
25724 definition using @i{universal_integer} takes precedence.
25725
25726 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25727 it is
25728 not possible to be 100% compatible. Since there are many programs using
25729 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25730 GNAT was
25731 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25732 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25733
25734 @smallexample @c ada
25735 function To_Address (X : Integer) return Address;
25736 pragma Pure_Function (To_Address);
25737
25738 function To_Address_Long (X : Unsigned_Longword) return Address;
25739 pragma Pure_Function (To_Address_Long);
25740 @end smallexample
25741
25742 @noindent
25743 This means that programs using @code{TO_ADDRESS} for
25744 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25745
25746 @node Tasking and Task-Related Features
25747 @section Tasking and Task-Related Features
25748
25749 @noindent
25750 This section compares the treatment of tasking in GNAT
25751 and in HP Ada for OpenVMS Alpha.
25752 The GNAT description applies to both Alpha and I64 OpenVMS.
25753 For detailed information on tasking in
25754 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25755 relevant run-time reference manual.
25756
25757 @menu
25758 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25759 * Assigning Task IDs::
25760 * Task IDs and Delays::
25761 * Task-Related Pragmas::
25762 * Scheduling and Task Priority::
25763 * The Task Stack::
25764 * External Interrupts::
25765 @end menu
25766
25767 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25768 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25769
25770 @noindent
25771 On OpenVMS Alpha systems, each Ada task (except a passive
25772 task) is implemented as a single stream of execution
25773 that is created and managed by the kernel. On these
25774 systems, HP Ada tasking support is based on DECthreads,
25775 an implementation of the POSIX standard for threads.
25776
25777 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25778 code that calls DECthreads routines can be used together.
25779 The interaction between Ada tasks and DECthreads routines
25780 can have some benefits. For example when on OpenVMS Alpha,
25781 HP Ada can call C code that is already threaded.
25782
25783 GNAT uses the facilities of DECthreads,
25784 and Ada tasks are mapped to threads.
25785
25786 @node Assigning Task IDs
25787 @subsection Assigning Task IDs
25788
25789 @noindent
25790 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25791 the environment task that executes the main program. On
25792 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25793 that have been created but are not yet activated.
25794
25795 On OpenVMS Alpha systems, task IDs are assigned at
25796 activation. On GNAT systems, task IDs are also assigned at
25797 task creation but do not have the same form or values as
25798 task ID values in HP Ada. There is no null task, and the
25799 environment task does not have a specific task ID value.
25800
25801 @node Task IDs and Delays
25802 @subsection Task IDs and Delays
25803
25804 @noindent
25805 On OpenVMS Alpha systems, tasking delays are implemented
25806 using Timer System Services. The Task ID is used for the
25807 identification of the timer request (the @code{REQIDT} parameter).
25808 If Timers are used in the application take care not to use
25809 @code{0} for the identification, because cancelling such a timer
25810 will cancel all timers and may lead to unpredictable results.
25811
25812 @node Task-Related Pragmas
25813 @subsection Task-Related Pragmas
25814
25815 @noindent
25816 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25817 specification of the size of the guard area for a task
25818 stack. (The guard area forms an area of memory that has no
25819 read or write access and thus helps in the detection of
25820 stack overflow.) On OpenVMS Alpha systems, if the pragma
25821 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25822 area is created. In the absence of a pragma @code{TASK_STORAGE},
25823 a default guard area is created.
25824
25825 GNAT supplies the following task-related pragmas:
25826
25827 @itemize @bullet
25828 @item  @code{TASK_INFO}
25829
25830 This pragma appears within a task definition and
25831 applies to the task in which it appears. The argument
25832 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25833
25834 @item  @code{TASK_STORAGE}
25835
25836 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25837 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25838 @code{SUPPRESS}, and @code{VOLATILE}.
25839 @end itemize
25840 @node Scheduling and Task Priority
25841 @subsection Scheduling and Task Priority
25842
25843 @noindent
25844 HP Ada implements the Ada language requirement that
25845 when two tasks are eligible for execution and they have
25846 different priorities, the lower priority task does not
25847 execute while the higher priority task is waiting. The HP
25848 Ada Run-Time Library keeps a task running until either the
25849 task is suspended or a higher priority task becomes ready.
25850
25851 On OpenVMS Alpha systems, the default strategy is round-
25852 robin with preemption. Tasks of equal priority take turns
25853 at the processor. A task is run for a certain period of
25854 time and then placed at the tail of the ready queue for
25855 its priority level.
25856
25857 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25858 which can be used to enable or disable round-robin
25859 scheduling of tasks with the same priority.
25860 See the relevant HP Ada run-time reference manual for
25861 information on using the pragmas to control HP Ada task
25862 scheduling.
25863
25864 GNAT follows the scheduling rules of Annex D (Real-Time
25865 Annex) of the @cite{Ada Reference Manual}. In general, this
25866 scheduling strategy is fully compatible with HP Ada
25867 although it provides some additional constraints (as
25868 fully documented in Annex D).
25869 GNAT implements time slicing control in a manner compatible with
25870 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25871 are identical to the HP Ada 83 pragma of the same name.
25872 Note that it is not possible to mix GNAT tasking and
25873 HP Ada 83 tasking in the same program, since the two run-time
25874 libraries are not compatible.
25875
25876 @node The Task Stack
25877 @subsection The Task Stack
25878
25879 @noindent
25880 In HP Ada, a task stack is allocated each time a
25881 non-passive task is activated. As soon as the task is
25882 terminated, the storage for the task stack is deallocated.
25883 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25884 a default stack size is used. Also, regardless of the size
25885 specified, some additional space is allocated for task
25886 management purposes. On OpenVMS Alpha systems, at least
25887 one page is allocated.
25888
25889 GNAT handles task stacks in a similar manner. In accordance with
25890 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25891 an alternative method for controlling the task stack size.
25892 The specification of the attribute @code{T'STORAGE_SIZE} is also
25893 supported in a manner compatible with HP Ada.
25894
25895 @node External Interrupts
25896 @subsection External Interrupts
25897
25898 @noindent
25899 On HP Ada, external interrupts can be associated with task entries.
25900 GNAT is compatible with HP Ada in its handling of external interrupts.
25901
25902 @node Pragmas and Pragma-Related Features
25903 @section Pragmas and Pragma-Related Features
25904
25905 @noindent
25906 Both HP Ada and GNAT supply all language-defined pragmas
25907 as specified by the Ada 83 standard. GNAT also supplies all
25908 language-defined pragmas introduced by Ada 95 and Ada 2005.
25909 In addition, GNAT implements the implementation-defined pragmas
25910 from HP Ada 83.
25911
25912 @itemize @bullet
25913 @item  @code{AST_ENTRY}
25914
25915 @item  @code{COMMON_OBJECT}
25916
25917 @item  @code{COMPONENT_ALIGNMENT}
25918
25919 @item  @code{EXPORT_EXCEPTION}
25920
25921 @item  @code{EXPORT_FUNCTION}
25922
25923 @item  @code{EXPORT_OBJECT}
25924
25925 @item  @code{EXPORT_PROCEDURE}
25926
25927 @item  @code{EXPORT_VALUED_PROCEDURE}
25928
25929 @item  @code{FLOAT_REPRESENTATION}
25930
25931 @item  @code{IDENT}
25932
25933 @item  @code{IMPORT_EXCEPTION}
25934
25935 @item  @code{IMPORT_FUNCTION}
25936
25937 @item  @code{IMPORT_OBJECT}
25938
25939 @item  @code{IMPORT_PROCEDURE}
25940
25941 @item  @code{IMPORT_VALUED_PROCEDURE}
25942
25943 @item  @code{INLINE_GENERIC}
25944
25945 @item  @code{INTERFACE_NAME}
25946
25947 @item  @code{LONG_FLOAT}
25948
25949 @item  @code{MAIN_STORAGE}
25950
25951 @item  @code{PASSIVE}
25952
25953 @item  @code{PSECT_OBJECT}
25954
25955 @item  @code{SHARE_GENERIC}
25956
25957 @item  @code{SUPPRESS_ALL}
25958
25959 @item  @code{TASK_STORAGE}
25960
25961 @item  @code{TIME_SLICE}
25962
25963 @item  @code{TITLE}
25964 @end itemize
25965
25966 @noindent
25967 These pragmas are all fully implemented, with the exception of @code{TITLE},
25968 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25969 recognized, but which have no
25970 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25971 use of Ada protected objects. In GNAT, all generics are inlined.
25972
25973 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25974 a separate subprogram specification which must appear before the
25975 subprogram body.
25976
25977 GNAT also supplies a number of implementation-defined pragmas as follows:
25978 @itemize @bullet
25979 @item  @code{ABORT_DEFER}
25980
25981 @item  @code{ADA_83}
25982
25983 @item  @code{ADA_95}
25984
25985 @item  @code{ADA_05}
25986
25987 @item  @code{ANNOTATE}
25988
25989 @item  @code{ASSERT}
25990
25991 @item  @code{C_PASS_BY_COPY}
25992
25993 @item  @code{CPP_CLASS}
25994
25995 @item  @code{CPP_CONSTRUCTOR}
25996
25997 @item  @code{CPP_DESTRUCTOR}
25998
25999 @item  @code{DEBUG}
26000
26001 @item  @code{EXTEND_SYSTEM}
26002
26003 @item  @code{LINKER_ALIAS}
26004
26005 @item  @code{LINKER_SECTION}
26006
26007 @item  @code{MACHINE_ATTRIBUTE}
26008
26009 @item  @code{NO_RETURN}
26010
26011 @item  @code{PURE_FUNCTION}
26012
26013 @item  @code{SOURCE_FILE_NAME}
26014
26015 @item  @code{SOURCE_REFERENCE}
26016
26017 @item  @code{TASK_INFO}
26018
26019 @item  @code{UNCHECKED_UNION}
26020
26021 @item  @code{UNIMPLEMENTED_UNIT}
26022
26023 @item  @code{UNIVERSAL_DATA}
26024
26025 @item  @code{UNSUPPRESS}
26026
26027 @item  @code{WARNINGS}
26028
26029 @item  @code{WEAK_EXTERNAL}
26030 @end itemize
26031
26032 @noindent
26033 For full details on these GNAT implementation-defined pragmas,
26034 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
26035 Manual}.
26036
26037 @menu
26038 * Restrictions on the Pragma INLINE::
26039 * Restrictions on the Pragma INTERFACE::
26040 * Restrictions on the Pragma SYSTEM_NAME::
26041 @end menu
26042
26043 @node Restrictions on the Pragma INLINE
26044 @subsection Restrictions on Pragma @code{INLINE}
26045
26046 @noindent
26047 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
26048 @itemize @bullet
26049 @item  Parameters cannot have a task type.
26050
26051 @item  Function results cannot be task types, unconstrained
26052 array types, or unconstrained types with discriminants.
26053
26054 @item  Bodies cannot declare the following:
26055 @itemize @bullet
26056 @item  Subprogram body or stub (imported subprogram is allowed)
26057
26058 @item  Tasks
26059
26060 @item  Generic declarations
26061
26062 @item  Instantiations
26063
26064 @item  Exceptions
26065
26066 @item  Access types (types derived from access types allowed)
26067
26068 @item  Array or record types
26069
26070 @item  Dependent tasks
26071
26072 @item  Direct recursive calls of subprogram or containing
26073 subprogram, directly or via a renaming
26074
26075 @end itemize
26076 @end itemize
26077
26078 @noindent
26079 In GNAT, the only restriction on pragma @code{INLINE} is that the
26080 body must occur before the call if both are in the same
26081 unit, and the size must be appropriately small. There are
26082 no other specific restrictions which cause subprograms to
26083 be incapable of being inlined.
26084
26085 @node  Restrictions on the Pragma INTERFACE
26086 @subsection  Restrictions on Pragma @code{INTERFACE}
26087
26088 @noindent
26089 The following restrictions on pragma @code{INTERFACE}
26090 are enforced by both HP Ada and GNAT:
26091 @itemize @bullet
26092 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
26093 Default is the default on OpenVMS Alpha systems.
26094
26095 @item  Parameter passing: Language specifies default
26096 mechanisms but can be overridden with an @code{EXPORT} pragma.
26097
26098 @itemize @bullet
26099 @item  Ada: Use internal Ada rules.
26100
26101 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
26102 record or task type. Result cannot be a string, an
26103 array, or a record.
26104
26105 @item  Fortran: Parameters cannot have a task type. Result cannot
26106 be a string, an array, or a record.
26107 @end itemize
26108 @end itemize
26109
26110 @noindent
26111 GNAT is entirely upwards compatible with HP Ada, and in addition allows
26112 record parameters for all languages.
26113
26114 @node  Restrictions on the Pragma SYSTEM_NAME
26115 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
26116
26117 @noindent
26118 For HP Ada for OpenVMS Alpha, the enumeration literal
26119 for the type @code{NAME} is @code{OPENVMS_AXP}.
26120 In GNAT, the enumeration
26121 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
26122
26123 @node  Library of Predefined Units
26124 @section  Library of Predefined Units
26125
26126 @noindent
26127 A library of predefined units is provided as part of the
26128 HP Ada and GNAT implementations. HP Ada does not provide
26129 the package @code{MACHINE_CODE} but instead recommends importing
26130 assembler code.
26131
26132 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
26133 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
26134 version.
26135 The HP Ada Predefined Library units are modified to remove post-Ada 83
26136 incompatibilities and to make them interoperable with GNAT
26137 (@pxref{Changes to DECLIB}, for details).
26138 The units are located in the @file{DECLIB} directory.
26139
26140 The GNAT RTL is contained in
26141 the @file{ADALIB} directory, and
26142 the default search path is set up to find @code{DECLIB} units in preference
26143 to @code{ADALIB} units with the same name (@code{TEXT_IO},
26144 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
26145
26146 @menu
26147 * Changes to DECLIB::
26148 @end menu
26149
26150 @node Changes to DECLIB
26151 @subsection Changes to @code{DECLIB}
26152
26153 @noindent
26154 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
26155 compatibility are minor and include the following:
26156
26157 @itemize @bullet
26158 @item  Adjusting the location of pragmas and record representation
26159 clauses to obey Ada 95 (and thus Ada 2005) rules
26160
26161 @item  Adding the proper notation to generic formal parameters
26162 that take unconstrained types in instantiation
26163
26164 @item  Adding pragma @code{ELABORATE_BODY} to package specs
26165 that have package bodies not otherwise allowed
26166
26167 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
26168 ``@code{PROTECTD}''.
26169 Currently these are found only in the @code{STARLET} package spec.
26170
26171 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
26172 where the address size is constrained to 32 bits.
26173 @end itemize
26174
26175 @noindent
26176 None of the above changes is visible to users.
26177
26178 @node Bindings
26179 @section Bindings
26180
26181 @noindent
26182 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
26183 @itemize @bullet
26184
26185 @item  Command Language Interpreter (CLI interface)
26186
26187 @item  DECtalk Run-Time Library (DTK interface)
26188
26189 @item  Librarian utility routines (LBR interface)
26190
26191 @item  General Purpose Run-Time Library (LIB interface)
26192
26193 @item  Math Run-Time Library (MTH interface)
26194
26195 @item  National Character Set Run-Time Library (NCS interface)
26196
26197 @item  Compiled Code Support Run-Time Library (OTS interface)
26198
26199 @item  Parallel Processing Run-Time Library (PPL interface)
26200
26201 @item  Screen Management Run-Time Library (SMG interface)
26202
26203 @item  Sort Run-Time Library (SOR interface)
26204
26205 @item  String Run-Time Library (STR interface)
26206
26207 @item STARLET System Library
26208 @findex Starlet
26209
26210 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
26211
26212 @item  X Windows Toolkit (XT interface)
26213
26214 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
26215 @end itemize
26216
26217 @noindent
26218 GNAT provides implementations of these HP bindings in the @code{DECLIB}
26219 directory, on both the Alpha and I64 OpenVMS platforms.
26220
26221 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
26222 in the
26223 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
26224 A pragma @code{Linker_Options} has been added to packages @code{Xm},
26225 @code{Xt}, and @code{X_Lib}
26226 causing the default X/Motif sharable image libraries to be linked in. This
26227 is done via options files named @file{xm.opt}, @file{xt.opt}, and
26228 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
26229
26230 It may be necessary to edit these options files to update or correct the
26231 library names if, for example, the newer X/Motif bindings from
26232 @file{ADA$EXAMPLES}
26233 had been (previous to installing GNAT) copied and renamed to supersede the
26234 default @file{ADA$PREDEFINED} versions.
26235
26236 @menu
26237 * Shared Libraries and Options Files::
26238 * Interfaces to C::
26239 @end menu
26240
26241 @node Shared Libraries and Options Files
26242 @subsection Shared Libraries and Options Files
26243
26244 @noindent
26245 When using the HP Ada
26246 predefined X and Motif bindings, the linking with their sharable images is
26247 done automatically by @command{GNAT LINK}.
26248 When using other X and Motif bindings, you need
26249 to add the corresponding sharable images to the command line for
26250 @code{GNAT LINK}. When linking with shared libraries, or with
26251 @file{.OPT} files, you must
26252 also add them to the command line for @command{GNAT LINK}.
26253
26254 A shared library to be used with GNAT is built in the same way as other
26255 libraries under VMS. The VMS Link command can be used in standard fashion.
26256
26257 @node Interfaces to C
26258 @subsection Interfaces to C
26259
26260 @noindent
26261 HP Ada
26262 provides the following Ada types and operations:
26263
26264 @itemize @bullet
26265 @item C types package (@code{C_TYPES})
26266
26267 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26268
26269 @item Other_types (@code{SHORT_INT})
26270 @end itemize
26271
26272 @noindent
26273 Interfacing to C with GNAT, you can use the above approach
26274 described for HP Ada or the facilities of Annex B of
26275 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26276 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26277 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26278
26279 The @option{-gnatF} qualifier forces default and explicit
26280 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26281 to be uppercased for compatibility with the default behavior
26282 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26283
26284 @node Main Program Definition
26285 @section Main Program Definition
26286
26287 @noindent
26288 The following section discusses differences in the
26289 definition of main programs on HP Ada and GNAT.
26290 On HP Ada, main programs are defined to meet the
26291 following conditions:
26292 @itemize @bullet
26293 @item  Procedure with no formal parameters (returns @code{0} upon
26294 normal completion)
26295
26296 @item  Procedure with no formal parameters (returns @code{42} when
26297 an unhandled exception is raised)
26298
26299 @item  Function with no formal parameters whose returned value
26300 is of a discrete type
26301
26302 @item  Procedure with one @code{out} formal of a discrete type for
26303 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26304
26305 @end itemize
26306
26307 @noindent
26308 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26309 a main function or main procedure returns a discrete
26310 value whose size is less than 64 bits (32 on VAX systems),
26311 the value is zero- or sign-extended as appropriate.
26312 On GNAT, main programs are defined as follows:
26313 @itemize @bullet
26314 @item  Must be a non-generic, parameterless subprogram that
26315 is either a procedure or function returning an Ada
26316 @code{STANDARD.INTEGER} (the predefined type)
26317
26318 @item  Cannot be a generic subprogram or an instantiation of a
26319 generic subprogram
26320 @end itemize
26321
26322 @node Implementation-Defined Attributes
26323 @section Implementation-Defined Attributes
26324
26325 @noindent
26326 GNAT provides all HP Ada implementation-defined
26327 attributes.
26328
26329 @node Compiler and Run-Time Interfacing
26330 @section Compiler and Run-Time Interfacing
26331
26332 @noindent
26333 HP Ada provides the following qualifiers to pass options to the linker
26334 (ACS LINK):
26335 @itemize @bullet
26336 @item  @option{/WAIT} and @option{/SUBMIT}
26337
26338 @item  @option{/COMMAND}
26339
26340 @item  @option{/@r{[}NO@r{]}MAP}
26341
26342 @item  @option{/OUTPUT=@var{file-spec}}
26343
26344 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26345 @end itemize
26346
26347 @noindent
26348 To pass options to the linker, GNAT provides the following
26349 switches:
26350
26351 @itemize @bullet
26352 @item   @option{/EXECUTABLE=@var{exec-name}}
26353
26354 @item   @option{/VERBOSE}
26355
26356 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26357 @end itemize
26358
26359 @noindent
26360 For more information on these switches, see
26361 @ref{Switches for gnatlink}.
26362 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26363 to control optimization. HP Ada also supplies the
26364 following pragmas:
26365 @itemize @bullet
26366 @item  @code{OPTIMIZE}
26367
26368 @item  @code{INLINE}
26369
26370 @item  @code{INLINE_GENERIC}
26371
26372 @item  @code{SUPPRESS_ALL}
26373
26374 @item  @code{PASSIVE}
26375 @end itemize
26376
26377 @noindent
26378 In GNAT, optimization is controlled strictly by command
26379 line parameters, as described in the corresponding section of this guide.
26380 The HP pragmas for control of optimization are
26381 recognized but ignored.
26382
26383 Note that in GNAT, the default is optimization off, whereas in HP Ada
26384 the default is that optimization is turned on.
26385
26386 @node Program Compilation and Library Management
26387 @section Program Compilation and Library Management
26388
26389 @noindent
26390 HP Ada and GNAT provide a comparable set of commands to
26391 build programs. HP Ada also provides a program library,
26392 which is a concept that does not exist on GNAT. Instead,
26393 GNAT provides directories of sources that are compiled as
26394 needed.
26395
26396 The following table summarizes
26397 the HP Ada commands and provides
26398 equivalent GNAT commands. In this table, some GNAT
26399 equivalents reflect the fact that GNAT does not use the
26400 concept of a program library. Instead, it uses a model
26401 in which collections of source and object files are used
26402 in a manner consistent with other languages like C and
26403 Fortran. Therefore, standard system file commands are used
26404 to manipulate these elements. Those GNAT commands are marked with
26405 an asterisk.
26406 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26407
26408 @need 1500
26409 @multitable @columnfractions .35 .65
26410
26411 @item @emph{HP Ada Command}
26412 @tab @emph{GNAT Equivalent / Description}
26413
26414 @item @command{ADA}
26415 @tab @command{GNAT COMPILE}@*
26416 Invokes the compiler to compile one or more Ada source files.
26417
26418 @item @command{ACS ATTACH}@*
26419 @tab [No equivalent]@*
26420 Switches control of terminal from current process running the program
26421 library manager.
26422
26423 @item @command{ACS CHECK}
26424 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26425 Forms the execution closure of one
26426 or more compiled units and checks completeness and currency.
26427
26428 @item @command{ACS COMPILE}
26429 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26430 Forms the execution closure of one or
26431 more specified units, checks completeness and currency,
26432 identifies units that have revised source files, compiles same,
26433 and recompiles units that are or will become obsolete.
26434 Also completes incomplete generic instantiations.
26435
26436 @item @command{ACS COPY FOREIGN}
26437 @tab Copy (*)@*
26438 Copies a foreign object file into the program library as a
26439 library unit body.
26440
26441 @item @command{ACS COPY UNIT}
26442 @tab Copy (*)@*
26443 Copies a compiled unit from one program library to another.
26444
26445 @item @command{ACS CREATE LIBRARY}
26446 @tab Create /directory (*)@*
26447 Creates a program library.
26448
26449 @item @command{ACS CREATE SUBLIBRARY}
26450 @tab Create /directory (*)@*
26451 Creates a program sublibrary.
26452
26453 @item @command{ACS DELETE LIBRARY}
26454 @tab @*
26455 Deletes a program library and its contents.
26456
26457 @item @command{ACS DELETE SUBLIBRARY}
26458 @tab @*
26459 Deletes a program sublibrary and its contents.
26460
26461 @item @command{ACS DELETE UNIT}
26462 @tab Delete file (*)@*
26463 On OpenVMS systems, deletes one or more compiled units from
26464 the current program library.
26465
26466 @item @command{ACS DIRECTORY}
26467 @tab Directory (*)@*
26468 On OpenVMS systems, lists units contained in the current
26469 program library.
26470
26471 @item @command{ACS ENTER FOREIGN}
26472 @tab Copy (*)@*
26473 Allows the import of a foreign body as an Ada library
26474 spec and enters a reference to a pointer.
26475
26476 @item @command{ACS ENTER UNIT}
26477 @tab Copy (*)@*
26478 Enters a reference (pointer) from the current program library to
26479 a unit compiled into another program library.
26480
26481 @item @command{ACS EXIT}
26482 @tab [No equivalent]@*
26483 Exits from the program library manager.
26484
26485 @item @command{ACS EXPORT}
26486 @tab Copy (*)@*
26487 Creates an object file that contains system-specific object code
26488 for one or more units. With GNAT, object files can simply be copied
26489 into the desired directory.
26490
26491 @item @command{ACS EXTRACT SOURCE}
26492 @tab Copy (*)@*
26493 Allows access to the copied source file for each Ada compilation unit
26494
26495 @item @command{ACS HELP}
26496 @tab @command{HELP GNAT}@*
26497 Provides online help.
26498
26499 @item @command{ACS LINK}
26500 @tab @command{GNAT LINK}@*
26501 Links an object file containing Ada units into an executable file.
26502
26503 @item @command{ACS LOAD}
26504 @tab Copy (*)@*
26505 Loads (partially compiles) Ada units into the program library.
26506 Allows loading a program from a collection of files into a library
26507 without knowing the relationship among units.
26508
26509 @item @command{ACS MERGE}
26510 @tab Copy (*)@*
26511 Merges into the current program library, one or more units from
26512 another library where they were modified.
26513
26514 @item @command{ACS RECOMPILE}
26515 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26516 Recompiles from   external or copied source files any obsolete
26517 unit in the closure. Also, completes any incomplete generic
26518 instantiations.
26519
26520 @item @command{ACS REENTER}
26521 @tab @command{GNAT MAKE}@*
26522 Reenters current references to units compiled after last entered
26523 with the @command{ACS ENTER UNIT} command.
26524
26525 @item @command{ACS SET LIBRARY}
26526 @tab Set default (*)@*
26527 Defines a program library to be the compilation context as well
26528 as the target library for compiler output and commands in general.
26529
26530 @item @command{ACS SET PRAGMA}
26531 @tab Edit @file{gnat.adc} (*)@*
26532 Redefines specified  values of the library characteristics
26533 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26534 and @code{Float_Representation}.
26535
26536 @item @command{ACS SET SOURCE}
26537 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26538 Defines the source file search list for the @command{ACS COMPILE} command.
26539
26540 @item @command{ACS SHOW LIBRARY}
26541 @tab Directory (*)@*
26542 Lists information about one or more program libraries.
26543
26544 @item @command{ACS SHOW PROGRAM}
26545 @tab [No equivalent]@*
26546 Lists information about the execution closure of one or
26547 more units in the program library.
26548
26549 @item @command{ACS SHOW SOURCE}
26550 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26551 Shows the source file search used when compiling units.
26552
26553 @item @command{ACS SHOW VERSION}
26554 @tab Compile with @option{VERBOSE} option
26555 Displays the version number of the compiler and program library
26556 manager used.
26557
26558 @item @command{ACS SPAWN}
26559 @tab [No equivalent]@*
26560 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26561 command).
26562
26563 @item @command{ACS VERIFY}
26564 @tab [No equivalent]@*
26565 Performs a series of consistency checks on a program library to
26566 determine whether the library structure and library files are in
26567 valid form.
26568 @end multitable
26569
26570 @noindent
26571
26572 @node Input-Output
26573 @section Input-Output
26574
26575 @noindent
26576 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26577 Management Services (RMS) to perform operations on
26578 external files.
26579
26580 @noindent
26581 HP Ada and GNAT predefine an identical set of input-
26582 output packages. To make the use of the
26583 generic @code{TEXT_IO} operations more convenient, HP Ada
26584 provides predefined library packages that instantiate the
26585 integer and floating-point operations for the predefined
26586 integer and floating-point types as shown in the following table.
26587
26588 @multitable @columnfractions .45 .55
26589 @item @emph{Package Name} @tab Instantiation
26590
26591 @item @code{INTEGER_TEXT_IO}
26592 @tab @code{INTEGER_IO(INTEGER)}
26593
26594 @item @code{SHORT_INTEGER_TEXT_IO}
26595 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26596
26597 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26598 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26599
26600 @item @code{FLOAT_TEXT_IO}
26601 @tab @code{FLOAT_IO(FLOAT)}
26602
26603 @item @code{LONG_FLOAT_TEXT_IO}
26604 @tab @code{FLOAT_IO(LONG_FLOAT)}
26605 @end multitable
26606
26607 @noindent
26608 The HP Ada predefined packages and their operations
26609 are implemented using OpenVMS Alpha files and input-output
26610 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26611 Familiarity with the following is recommended:
26612 @itemize @bullet
26613 @item  RMS file organizations and access methods
26614
26615 @item  OpenVMS file specifications and directories
26616
26617 @item  OpenVMS File Definition Language (FDL)
26618 @end itemize
26619
26620 @noindent
26621 GNAT provides I/O facilities that are completely
26622 compatible with HP Ada. The distribution includes the
26623 standard HP Ada versions of all I/O packages, operating
26624 in a manner compatible with HP Ada. In particular, the
26625 following packages are by default the HP Ada (Ada 83)
26626 versions of these packages rather than the renamings
26627 suggested in Annex J of the Ada Reference Manual:
26628 @itemize @bullet
26629 @item  @code{TEXT_IO}
26630
26631 @item  @code{SEQUENTIAL_IO}
26632
26633 @item  @code{DIRECT_IO}
26634 @end itemize
26635
26636 @noindent
26637 The use of the standard child package syntax (for
26638 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26639 packages.
26640 GNAT provides HP-compatible predefined instantiations
26641 of the @code{TEXT_IO} packages, and also
26642 provides the standard predefined instantiations required
26643 by the @cite{Ada Reference Manual}.
26644
26645 For further information on how GNAT interfaces to the file
26646 system or how I/O is implemented in programs written in
26647 mixed languages, see @ref{Implementation of the Standard I/O,,,
26648 gnat_rm, GNAT Reference Manual}.
26649 This chapter covers the following:
26650 @itemize @bullet
26651 @item  Standard I/O packages
26652
26653 @item  @code{FORM} strings
26654
26655 @item  @code{ADA.DIRECT_IO}
26656
26657 @item  @code{ADA.SEQUENTIAL_IO}
26658
26659 @item  @code{ADA.TEXT_IO}
26660
26661 @item  Stream pointer positioning
26662
26663 @item  Reading and writing non-regular files
26664
26665 @item  @code{GET_IMMEDIATE}
26666
26667 @item  Treating @code{TEXT_IO} files as streams
26668
26669 @item  Shared files
26670
26671 @item  Open modes
26672 @end itemize
26673
26674 @node Implementation Limits
26675 @section Implementation Limits
26676
26677 @noindent
26678 The following table lists implementation limits for HP Ada
26679 and GNAT systems.
26680 @multitable @columnfractions .60 .20 .20
26681 @sp 1
26682 @item  @emph{Compilation Parameter}
26683 @tab   @emph{HP Ada}
26684 @tab   @emph{GNAT}
26685 @sp 1
26686
26687 @item  In a subprogram or entry  declaration, maximum number of
26688 formal parameters that are of an unconstrained record type
26689 @tab   32
26690 @tab   No set limit
26691 @sp 1
26692
26693 @item  Maximum identifier length (number of characters)
26694 @tab   255
26695 @tab   32766
26696 @sp 1
26697
26698 @item  Maximum number of characters in a source line
26699 @tab   255
26700 @tab   32766
26701 @sp 1
26702
26703 @item  Maximum collection size   (number of bytes)
26704 @tab   2**31-1
26705 @tab   2**31-1
26706 @sp 1
26707
26708 @item  Maximum number of discriminants for a record type
26709 @tab   245
26710 @tab   No set limit
26711 @sp 1
26712
26713 @item  Maximum number of formal parameters in an entry or
26714 subprogram declaration
26715 @tab   246
26716 @tab    No set limit
26717 @sp 1
26718
26719 @item  Maximum number of dimensions in an array type
26720 @tab   255
26721 @tab   No set limit
26722 @sp 1
26723
26724 @item  Maximum number of library  units and subunits in a compilation.
26725 @tab   4095
26726 @tab   No set limit
26727 @sp 1
26728
26729 @item  Maximum number of library units and subunits in an execution.
26730 @tab   16383
26731 @tab   No set limit
26732 @sp 1
26733
26734 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26735 or @code{PSECT_OBJECT}
26736 @tab   32757
26737 @tab   No set limit
26738 @sp 1
26739
26740 @item  Maximum number of enumeration literals in an enumeration type
26741 definition
26742 @tab   65535
26743 @tab   No set limit
26744 @sp 1
26745
26746 @item  Maximum number of lines in a source file
26747 @tab   65534
26748 @tab   No set limit
26749 @sp 1
26750
26751 @item  Maximum number of bits in any object
26752 @tab   2**31-1
26753 @tab   2**31-1
26754 @sp 1
26755
26756 @item  Maximum size of the static portion of a stack frame (approximate)
26757 @tab   2**31-1
26758 @tab   2**31-1
26759 @end multitable
26760
26761 @node Tools and Utilities
26762 @section Tools and Utilities
26763
26764 @noindent
26765 The following table lists some of the OpenVMS development tools
26766 available for HP Ada, and the corresponding tools for
26767 use with @value{EDITION} on Alpha and I64 platforms.
26768 Aside from the debugger, all the OpenVMS tools identified are part
26769 of the DECset package.
26770
26771 @iftex
26772 @c Specify table in TeX since Texinfo does a poor job
26773 @tex
26774 \smallskip
26775 \smallskip
26776 \settabs\+Language-Sensitive Editor\quad
26777    &Product with HP Ada\quad
26778    &\cr
26779 \+\it Tool
26780    &\it Product with HP Ada
26781    & \it Product with GNAT Pro\cr
26782 \smallskip
26783 \+Code Management System
26784    &HP CMS
26785    & HP CMS\cr
26786 \smallskip
26787 \+Language-Sensitive Editor
26788    &HP LSE
26789    & emacs or HP LSE (Alpha)\cr
26790 \+
26791    &
26792    & HP LSE (I64)\cr
26793 \smallskip
26794 \+Debugger
26795    &OpenVMS Debug
26796    & gdb (Alpha),\cr
26797 \+
26798    &
26799    & OpenVMS Debug (I64)\cr
26800 \smallskip
26801 \+Source Code Analyzer /
26802    &HP SCA
26803    & GNAT XREF\cr
26804 \+Cross Referencer
26805    &
26806    &\cr
26807 \smallskip
26808 \+Test Manager
26809    &HP Digital Test
26810    & HP DTM\cr
26811 \+
26812    &Manager (DTM)
26813    &\cr
26814 \smallskip
26815 \+Performance and
26816    & HP PCA
26817    & HP PCA\cr
26818 \+Coverage Analyzer
26819    &
26820    &\cr
26821 \smallskip
26822 \+Module Management
26823    & HP MMS
26824    & Not applicable\cr
26825 \+ System
26826    &
26827    &\cr
26828 \smallskip
26829 \smallskip
26830 @end tex
26831 @end iftex
26832
26833 @ifnottex
26834 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26835 @c the TeX version above for the printed version
26836 @flushleft
26837 @c @multitable @columnfractions .3 .4 .4
26838 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26839 @item @i{Tool}
26840 @tab @i{Tool with HP Ada}
26841 @tab @i{Tool with @value{EDITION}}
26842 @item Code Management@*System
26843 @tab HP CMS
26844 @tab HP CMS
26845 @item Language-Sensitive@*Editor
26846 @tab HP LSE
26847 @tab emacs or HP LSE (Alpha)
26848 @item
26849 @tab
26850 @tab HP LSE (I64)
26851 @item Debugger
26852 @tab OpenVMS Debug
26853 @tab gdb (Alpha),
26854 @item
26855 @tab
26856 @tab OpenVMS Debug (I64)
26857 @item Source Code Analyzer /@*Cross Referencer
26858 @tab HP SCA
26859 @tab GNAT XREF
26860 @item Test Manager
26861 @tab HP Digital Test@*Manager (DTM)
26862 @tab HP DTM
26863 @item Performance and@*Coverage Analyzer
26864 @tab HP PCA
26865 @tab HP PCA
26866 @item Module Management@*System
26867 @tab HP MMS
26868 @tab Not applicable
26869 @end multitable
26870 @end flushleft
26871 @end ifnottex
26872
26873 @end ifset
26874
26875 @c **************************************
26876 @node Platform-Specific Information for the Run-Time Libraries
26877 @appendix Platform-Specific Information for the Run-Time Libraries
26878 @cindex Tasking and threads libraries
26879 @cindex Threads libraries and tasking
26880 @cindex Run-time libraries (platform-specific information)
26881
26882 @noindent
26883 The GNAT run-time implementation may vary with respect to both the
26884 underlying threads library and the exception handling scheme.
26885 For threads support, one or more of the following are supplied:
26886 @itemize @bullet
26887 @item @b{native threads library}, a binding to the thread package from
26888 the underlying operating system
26889
26890 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26891 POSIX thread package
26892 @end itemize
26893
26894 @noindent
26895 For exception handling, either or both of two models are supplied:
26896 @itemize @bullet
26897 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26898 Most programs should experience a substantial speed improvement by
26899 being compiled with a ZCX run-time.
26900 This is especially true for
26901 tasking applications or applications with many exception handlers.}
26902 @cindex Zero-Cost Exceptions
26903 @cindex ZCX (Zero-Cost Exceptions)
26904 which uses binder-generated tables that
26905 are interrogated at run time to locate a handler
26906
26907 @item @b{setjmp / longjmp} (``SJLJ''),
26908 @cindex setjmp/longjmp Exception Model
26909 @cindex SJLJ (setjmp/longjmp Exception Model)
26910 which uses dynamically-set data to establish
26911 the set of handlers
26912 @end itemize
26913
26914 @noindent
26915 This appendix summarizes which combinations of threads and exception support
26916 are supplied on various GNAT platforms.
26917 It then shows how to select a particular library either
26918 permanently or temporarily,
26919 explains the properties of (and tradeoffs among) the various threads
26920 libraries, and provides some additional
26921 information about several specific platforms.
26922
26923 @menu
26924 * Summary of Run-Time Configurations::
26925 * Specifying a Run-Time Library::
26926 * Choosing the Scheduling Policy::
26927 * Solaris-Specific Considerations::
26928 * Linux-Specific Considerations::
26929 * AIX-Specific Considerations::
26930 * Irix-Specific Considerations::
26931 * RTX-Specific Considerations::
26932 * HP-UX-Specific Considerations::
26933 @end menu
26934
26935 @node Summary of Run-Time Configurations
26936 @section Summary of Run-Time Configurations
26937
26938 @multitable @columnfractions .30 .70
26939 @item @b{alpha-openvms}
26940 @item @code{@ @ }@i{rts-native (default)}
26941 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26942 @item @code{@ @ @ @ }Exceptions @tab ZCX
26943 @*
26944 @item @b{alpha-tru64}
26945 @item @code{@ @ }@i{rts-native (default)}
26946 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26947 @item @code{@ @ @ @ }Exceptions @tab ZCX
26948 @*
26949 @item @code{@ @ }@i{rts-sjlj}
26950 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26951 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26952 @*
26953 @item @b{ia64-hp_linux}
26954 @item @code{@ @ }@i{rts-native (default)}
26955 @item @code{@ @ @ @ }Tasking    @tab pthread library
26956 @item @code{@ @ @ @ }Exceptions @tab ZCX
26957 @*
26958 @item @b{ia64-hpux}
26959 @item @code{@ @ }@i{rts-native (default)}
26960 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26961 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26962 @*
26963 @item @b{ia64-openvms}
26964 @item @code{@ @ }@i{rts-native (default)}
26965 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26966 @item @code{@ @ @ @ }Exceptions @tab ZCX
26967 @*
26968 @item @b{ia64-sgi_linux}
26969 @item @code{@ @ }@i{rts-native (default)}
26970 @item @code{@ @ @ @ }Tasking    @tab pthread library
26971 @item @code{@ @ @ @ }Exceptions @tab ZCX
26972 @*
26973 @item @b{mips-irix}
26974 @item @code{@ @ }@i{rts-native (default)}
26975 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26976 @item @code{@ @ @ @ }Exceptions @tab ZCX
26977 @*
26978 @item @b{pa-hpux}
26979 @item @code{@ @ }@i{rts-native (default)}
26980 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26981 @item @code{@ @ @ @ }Exceptions @tab ZCX
26982 @*
26983 @item @code{@ @ }@i{rts-sjlj}
26984 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26985 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26986 @*
26987 @item @b{ppc-aix}
26988 @item @code{@ @ }@i{rts-native (default)}
26989 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26990 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26991 @*
26992 @item @b{ppc-darwin}
26993 @item @code{@ @ }@i{rts-native (default)}
26994 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26995 @item @code{@ @ @ @ }Exceptions @tab ZCX
26996 @*
26997 @item @b{sparc-solaris}  @tab
26998 @item @code{@ @ }@i{rts-native (default)}
26999 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27000 @item @code{@ @ @ @ }Exceptions @tab ZCX
27001 @*
27002 @item @code{@ @ }@i{rts-pthread}
27003 @item @code{@ @ @ @ }Tasking    @tab pthread library
27004 @item @code{@ @ @ @ }Exceptions @tab ZCX
27005 @*
27006 @item @code{@ @ }@i{rts-sjlj}
27007 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27008 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27009 @*
27010 @item @b{sparc64-solaris}  @tab
27011 @item @code{@ @ }@i{rts-native (default)}
27012 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27013 @item @code{@ @ @ @ }Exceptions @tab ZCX
27014 @*
27015 @item @b{x86-linux}
27016 @item @code{@ @ }@i{rts-native (default)}
27017 @item @code{@ @ @ @ }Tasking    @tab pthread library
27018 @item @code{@ @ @ @ }Exceptions @tab ZCX
27019 @*
27020 @item @code{@ @ }@i{rts-sjlj}
27021 @item @code{@ @ @ @ }Tasking    @tab pthread library
27022 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27023 @*
27024 @item @b{x86-lynx}
27025 @item @code{@ @ }@i{rts-native (default)}
27026 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
27027 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27028 @*
27029 @item @b{x86-solaris}
27030 @item @code{@ @ }@i{rts-native (default)}
27031 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
27032 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27033 @*
27034 @item @b{x86-windows}
27035 @item @code{@ @ }@i{rts-native (default)}
27036 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27037 @item @code{@ @ @ @ }Exceptions @tab ZCX
27038 @*
27039 @item @code{@ @ }@i{rts-sjlj (default)}
27040 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27041 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27042 @*
27043 @item @b{x86-windows-rtx}
27044 @item @code{@ @ }@i{rts-rtx-rtss (default)}
27045 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
27046 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27047 @*
27048 @item @code{@ @ }@i{rts-rtx-w32}
27049 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
27050 @item @code{@ @ @ @ }Exceptions @tab ZCX
27051 @*
27052 @item @b{x86_64-linux}
27053 @item @code{@ @ }@i{rts-native (default)}
27054 @item @code{@ @ @ @ }Tasking    @tab pthread library
27055 @item @code{@ @ @ @ }Exceptions @tab ZCX
27056 @*
27057 @item @code{@ @ }@i{rts-sjlj}
27058 @item @code{@ @ @ @ }Tasking    @tab pthread library
27059 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27060 @*
27061 @end multitable
27062
27063 @node Specifying a Run-Time Library
27064 @section Specifying a Run-Time Library
27065
27066 @noindent
27067 The @file{adainclude} subdirectory containing the sources of the GNAT
27068 run-time library, and the @file{adalib} subdirectory containing the
27069 @file{ALI} files and the static and/or shared GNAT library, are located
27070 in the gcc target-dependent area:
27071
27072 @smallexample
27073 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
27074 @end smallexample
27075
27076 @noindent
27077 As indicated above, on some platforms several run-time libraries are supplied.
27078 These libraries are installed in the target dependent area and
27079 contain a complete source and binary subdirectory. The detailed description
27080 below explains the differences between the different libraries in terms of
27081 their thread support.
27082
27083 The default run-time library (when GNAT is installed) is @emph{rts-native}.
27084 This default run time is selected by the means of soft links.
27085 For example on x86-linux:
27086
27087 @smallexample
27088 @group
27089  $(target-dir)
27090      |
27091      +--- adainclude----------+
27092      |                        |
27093      +--- adalib-----------+  |
27094      |                     |  |
27095      +--- rts-native       |  |
27096      |    |                |  |
27097      |    +--- adainclude <---+
27098      |    |                |
27099      |    +--- adalib <----+
27100      |
27101      +--- rts-sjlj
27102           |
27103           +--- adainclude
27104           |
27105           +--- adalib
27106 @end group
27107 @end smallexample
27108
27109 @noindent
27110 If the @i{rts-sjlj} library is to be selected on a permanent basis,
27111 these soft links can be modified with the following commands:
27112
27113 @smallexample
27114 $ cd $target
27115 $ rm -f adainclude adalib
27116 $ ln -s rts-sjlj/adainclude adainclude
27117 $ ln -s rts-sjlj/adalib adalib
27118 @end smallexample
27119
27120 @noindent
27121 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
27122 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
27123 @file{$target/ada_object_path}.
27124
27125 Selecting another run-time library temporarily can be
27126 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
27127 @cindex @option{--RTS} option
27128
27129 @node Choosing the Scheduling Policy
27130 @section Choosing the Scheduling Policy
27131
27132 @noindent
27133 When using a POSIX threads implementation, you have a choice of several
27134 scheduling policies: @code{SCHED_FIFO},
27135 @cindex @code{SCHED_FIFO} scheduling policy
27136 @code{SCHED_RR}
27137 @cindex @code{SCHED_RR} scheduling policy
27138 and @code{SCHED_OTHER}.
27139 @cindex @code{SCHED_OTHER} scheduling policy
27140 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
27141 or @code{SCHED_RR} requires special (e.g., root) privileges.
27142
27143 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
27144 @code{SCHED_FIFO},
27145 @cindex @code{SCHED_FIFO} scheduling policy
27146 you can use one of the following:
27147
27148 @itemize @bullet
27149 @item
27150 @code{pragma Time_Slice (0.0)}
27151 @cindex pragma Time_Slice
27152 @item
27153 the corresponding binder option @option{-T0}
27154 @cindex @option{-T0} option
27155 @item
27156 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27157 @cindex pragma Task_Dispatching_Policy
27158 @end itemize
27159
27160 @noindent
27161 To specify @code{SCHED_RR},
27162 @cindex @code{SCHED_RR} scheduling policy
27163 you should use @code{pragma Time_Slice} with a
27164 value greater than @code{0.0}, or else use the corresponding @option{-T}
27165 binder option.
27166
27167 @node Solaris-Specific Considerations
27168 @section Solaris-Specific Considerations
27169 @cindex Solaris Sparc threads libraries
27170
27171 @noindent
27172 This section addresses some topics related to the various threads libraries
27173 on Sparc Solaris.
27174
27175 @menu
27176 * Solaris Threads Issues::
27177 @end menu
27178
27179 @node Solaris Threads Issues
27180 @subsection Solaris Threads Issues
27181
27182 @noindent
27183 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
27184 library based on POSIX threads --- @emph{rts-pthread}.
27185 @cindex rts-pthread threads library
27186 This run-time library has the advantage of being mostly shared across all
27187 POSIX-compliant thread implementations, and it also provides under
27188 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
27189 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
27190 and @code{PTHREAD_PRIO_PROTECT}
27191 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
27192 semantics that can be selected using the predefined pragma
27193 @code{Locking_Policy}
27194 @cindex pragma Locking_Policy (under rts-pthread)
27195 with respectively
27196 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
27197 @cindex @code{Inheritance_Locking} (under rts-pthread)
27198 @cindex @code{Ceiling_Locking} (under rts-pthread)
27199
27200 As explained above, the native run-time library is based on the Solaris thread
27201 library (@code{libthread}) and is the default library.
27202
27203 When the Solaris threads library is used (this is the default), programs
27204 compiled with GNAT can automatically take advantage of
27205 and can thus execute on multiple processors.
27206 The user can alternatively specify a processor on which the program should run
27207 to emulate a single-processor system. The multiprocessor / uniprocessor choice
27208 is made by
27209 setting the environment variable @env{GNAT_PROCESSOR}
27210 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
27211 to one of the following:
27212
27213 @table @code
27214 @item -2
27215 Use the default configuration (run the program on all
27216 available processors) - this is the same as having @code{GNAT_PROCESSOR}
27217 unset
27218
27219 @item -1
27220 Let the run-time implementation choose one processor and run the program on
27221 that processor
27222
27223 @item 0 .. Last_Proc
27224 Run the program on the specified processor.
27225 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
27226 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
27227 @end table
27228
27229 @node Linux-Specific Considerations
27230 @section Linux-Specific Considerations
27231 @cindex Linux threads libraries
27232
27233 @noindent
27234 On GNU/Linux without NPTL support (usually system with GNU C Library
27235 older than 2.3), the signal model is not POSIX compliant, which means
27236 that to send a signal to the process, you need to send the signal to all
27237 threads, e.g.@: by using @code{killpg()}.
27238
27239 @node AIX-Specific Considerations
27240 @section AIX-Specific Considerations
27241 @cindex AIX resolver library
27242
27243 @noindent
27244 On AIX, the resolver library initializes some internal structure on
27245 the first call to @code{get*by*} functions, which are used to implement
27246 @code{GNAT.Sockets.Get_Host_By_Name} and
27247 @code{GNAT.Sockets.Get_Host_By_Address}.
27248 If such initialization occurs within an Ada task, and the stack size for
27249 the task is the default size, a stack overflow may occur.
27250
27251 To avoid this overflow, the user should either ensure that the first call
27252 to @code{GNAT.Sockets.Get_Host_By_Name} or
27253 @code{GNAT.Sockets.Get_Host_By_Addrss}
27254 occurs in the environment task, or use @code{pragma Storage_Size} to
27255 specify a sufficiently large size for the stack of the task that contains
27256 this call.
27257
27258 @node Irix-Specific Considerations
27259 @section Irix-Specific Considerations
27260 @cindex Irix libraries
27261
27262 @noindent
27263 The GCC support libraries coming with the Irix compiler have moved to
27264 their canonical place with respect to the general Irix ABI related
27265 conventions. Running applications built with the default shared GNAT
27266 run-time now requires the LD_LIBRARY_PATH environment variable to
27267 include this location. A possible way to achieve this is to issue the
27268 following command line on a bash prompt:
27269
27270 @smallexample
27271 @group
27272 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27273 @end group
27274 @end smallexample
27275
27276 @node RTX-Specific Considerations
27277 @section RTX-Specific Considerations
27278 @cindex RTX libraries
27279
27280 @noindent
27281 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27282 API. Applications can be built to work in two different modes:
27283
27284 @itemize @bullet
27285 @item
27286 Windows executables that run in Ring 3 to utilize memory protection
27287 (@emph{rts-rtx-w32}).
27288
27289 @item
27290 Real-time subsystem (RTSS) executables that run in Ring 0, where
27291 performance can be optimized with RTSS applications taking precedent
27292 over all Windows applications (@emph{rts-rtx-rtss}).
27293
27294 @end itemize
27295
27296 @node HP-UX-Specific Considerations
27297 @section HP-UX-Specific Considerations
27298 @cindex HP-UX Scheduling
27299
27300 @noindent
27301 On HP-UX, appropriate privileges are required to change the scheduling
27302 parameters of a task. The calling process must have appropriate
27303 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
27304 successfully change the scheduling parameters.
27305
27306 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
27307 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
27308 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
27309
27310 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
27311 one of the following:
27312
27313 @itemize @bullet
27314 @item
27315 @code{pragma Time_Slice (0.0)}
27316 @cindex pragma Time_Slice
27317 @item
27318 the corresponding binder option @option{-T0}
27319 @cindex @option{-T0} option
27320 @item
27321 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27322 @cindex pragma Task_Dispatching_Policy
27323 @end itemize
27324
27325 @noindent
27326 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
27327 you should use @code{pragma Time_Slice} with a
27328 value greater than @code{0.0}, or use the corresponding @option{-T}
27329 binder option, or set the @code{pragma Task_Dispatching_Policy
27330 (Round_Robin_Within_Priorities)}.
27331
27332 @c *******************************
27333 @node Example of Binder Output File
27334 @appendix Example of Binder Output File
27335
27336 @noindent
27337 This Appendix displays the source code for @command{gnatbind}'s output
27338 file generated for a simple ``Hello World'' program.
27339 Comments have been added for clarification purposes.
27340
27341 @smallexample @c adanocomment
27342 @iftex
27343 @leftskip=0cm
27344 @end iftex
27345 --  The package is called Ada_Main unless this name is actually used
27346 --  as a unit name in the partition, in which case some other unique
27347 --  name is used.
27348
27349 with System;
27350 package ada_main is
27351
27352    Elab_Final_Code : Integer;
27353    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27354
27355    --  The main program saves the parameters (argument count,
27356    --  argument values, environment pointer) in global variables
27357    --  for later access by other units including
27358    --  Ada.Command_Line.
27359
27360    gnat_argc : Integer;
27361    gnat_argv : System.Address;
27362    gnat_envp : System.Address;
27363
27364    --  The actual variables are stored in a library routine. This
27365    --  is useful for some shared library situations, where there
27366    --  are problems if variables are not in the library.
27367
27368    pragma Import (C, gnat_argc);
27369    pragma Import (C, gnat_argv);
27370    pragma Import (C, gnat_envp);
27371
27372    --  The exit status is similarly an external location
27373
27374    gnat_exit_status : Integer;
27375    pragma Import (C, gnat_exit_status);
27376
27377    GNAT_Version : constant String :=
27378                     "GNAT Version: 6.0.0w (20061115)";
27379    pragma Export (C, GNAT_Version, "__gnat_version");
27380
27381    --  This is the generated adafinal routine that performs
27382    --  finalization at the end of execution. In the case where
27383    --  Ada is the main program, this main program makes a call
27384    --  to adafinal at program termination.
27385
27386    procedure adafinal;
27387    pragma Export (C, adafinal, "adafinal");
27388
27389    --  This is the generated adainit routine that performs
27390    --  initialization at the start of execution. In the case
27391    --  where Ada is the main program, this main program makes
27392    --  a call to adainit at program startup.
27393
27394    procedure adainit;
27395    pragma Export (C, adainit, "adainit");
27396
27397    --  This routine is called at the start of execution. It is
27398    --  a dummy routine that is used by the debugger to breakpoint
27399    --  at the start of execution.
27400
27401    procedure Break_Start;
27402    pragma Import (C, Break_Start, "__gnat_break_start");
27403
27404    --  This is the actual generated main program (it would be
27405    --  suppressed if the no main program switch were used). As
27406    --  required by standard system conventions, this program has
27407    --  the external name main.
27408
27409    function main
27410      (argc : Integer;
27411       argv : System.Address;
27412       envp : System.Address)
27413       return Integer;
27414    pragma Export (C, main, "main");
27415
27416    --  The following set of constants give the version
27417    --  identification values for every unit in the bound
27418    --  partition. This identification is computed from all
27419    --  dependent semantic units, and corresponds to the
27420    --  string that would be returned by use of the
27421    --  Body_Version or Version attributes.
27422
27423    type Version_32 is mod 2 ** 32;
27424    u00001 : constant Version_32 := 16#7880BEB3#;
27425    u00002 : constant Version_32 := 16#0D24CBD0#;
27426    u00003 : constant Version_32 := 16#3283DBEB#;
27427    u00004 : constant Version_32 := 16#2359F9ED#;
27428    u00005 : constant Version_32 := 16#664FB847#;
27429    u00006 : constant Version_32 := 16#68E803DF#;
27430    u00007 : constant Version_32 := 16#5572E604#;
27431    u00008 : constant Version_32 := 16#46B173D8#;
27432    u00009 : constant Version_32 := 16#156A40CF#;
27433    u00010 : constant Version_32 := 16#033DABE0#;
27434    u00011 : constant Version_32 := 16#6AB38FEA#;
27435    u00012 : constant Version_32 := 16#22B6217D#;
27436    u00013 : constant Version_32 := 16#68A22947#;
27437    u00014 : constant Version_32 := 16#18CC4A56#;
27438    u00015 : constant Version_32 := 16#08258E1B#;
27439    u00016 : constant Version_32 := 16#367D5222#;
27440    u00017 : constant Version_32 := 16#20C9ECA4#;
27441    u00018 : constant Version_32 := 16#50D32CB6#;
27442    u00019 : constant Version_32 := 16#39A8BB77#;
27443    u00020 : constant Version_32 := 16#5CF8FA2B#;
27444    u00021 : constant Version_32 := 16#2F1EB794#;
27445    u00022 : constant Version_32 := 16#31AB6444#;
27446    u00023 : constant Version_32 := 16#1574B6E9#;
27447    u00024 : constant Version_32 := 16#5109C189#;
27448    u00025 : constant Version_32 := 16#56D770CD#;
27449    u00026 : constant Version_32 := 16#02F9DE3D#;
27450    u00027 : constant Version_32 := 16#08AB6B2C#;
27451    u00028 : constant Version_32 := 16#3FA37670#;
27452    u00029 : constant Version_32 := 16#476457A0#;
27453    u00030 : constant Version_32 := 16#731E1B6E#;
27454    u00031 : constant Version_32 := 16#23C2E789#;
27455    u00032 : constant Version_32 := 16#0F1BD6A1#;
27456    u00033 : constant Version_32 := 16#7C25DE96#;
27457    u00034 : constant Version_32 := 16#39ADFFA2#;
27458    u00035 : constant Version_32 := 16#571DE3E7#;
27459    u00036 : constant Version_32 := 16#5EB646AB#;
27460    u00037 : constant Version_32 := 16#4249379B#;
27461    u00038 : constant Version_32 := 16#0357E00A#;
27462    u00039 : constant Version_32 := 16#3784FB72#;
27463    u00040 : constant Version_32 := 16#2E723019#;
27464    u00041 : constant Version_32 := 16#623358EA#;
27465    u00042 : constant Version_32 := 16#107F9465#;
27466    u00043 : constant Version_32 := 16#6843F68A#;
27467    u00044 : constant Version_32 := 16#63305874#;
27468    u00045 : constant Version_32 := 16#31E56CE1#;
27469    u00046 : constant Version_32 := 16#02917970#;
27470    u00047 : constant Version_32 := 16#6CCBA70E#;
27471    u00048 : constant Version_32 := 16#41CD4204#;
27472    u00049 : constant Version_32 := 16#572E3F58#;
27473    u00050 : constant Version_32 := 16#20729FF5#;
27474    u00051 : constant Version_32 := 16#1D4F93E8#;
27475    u00052 : constant Version_32 := 16#30B2EC3D#;
27476    u00053 : constant Version_32 := 16#34054F96#;
27477    u00054 : constant Version_32 := 16#5A199860#;
27478    u00055 : constant Version_32 := 16#0E7F912B#;
27479    u00056 : constant Version_32 := 16#5760634A#;
27480    u00057 : constant Version_32 := 16#5D851835#;
27481
27482    --  The following Export pragmas export the version numbers
27483    --  with symbolic names ending in B (for body) or S
27484    --  (for spec) so that they can be located in a link. The
27485    --  information provided here is sufficient to track down
27486    --  the exact versions of units used in a given build.
27487
27488    pragma Export (C, u00001, "helloB");
27489    pragma Export (C, u00002, "system__standard_libraryB");
27490    pragma Export (C, u00003, "system__standard_libraryS");
27491    pragma Export (C, u00004, "adaS");
27492    pragma Export (C, u00005, "ada__text_ioB");
27493    pragma Export (C, u00006, "ada__text_ioS");
27494    pragma Export (C, u00007, "ada__exceptionsB");
27495    pragma Export (C, u00008, "ada__exceptionsS");
27496    pragma Export (C, u00009, "gnatS");
27497    pragma Export (C, u00010, "gnat__heap_sort_aB");
27498    pragma Export (C, u00011, "gnat__heap_sort_aS");
27499    pragma Export (C, u00012, "systemS");
27500    pragma Export (C, u00013, "system__exception_tableB");
27501    pragma Export (C, u00014, "system__exception_tableS");
27502    pragma Export (C, u00015, "gnat__htableB");
27503    pragma Export (C, u00016, "gnat__htableS");
27504    pragma Export (C, u00017, "system__exceptionsS");
27505    pragma Export (C, u00018, "system__machine_state_operationsB");
27506    pragma Export (C, u00019, "system__machine_state_operationsS");
27507    pragma Export (C, u00020, "system__machine_codeS");
27508    pragma Export (C, u00021, "system__storage_elementsB");
27509    pragma Export (C, u00022, "system__storage_elementsS");
27510    pragma Export (C, u00023, "system__secondary_stackB");
27511    pragma Export (C, u00024, "system__secondary_stackS");
27512    pragma Export (C, u00025, "system__parametersB");
27513    pragma Export (C, u00026, "system__parametersS");
27514    pragma Export (C, u00027, "system__soft_linksB");
27515    pragma Export (C, u00028, "system__soft_linksS");
27516    pragma Export (C, u00029, "system__stack_checkingB");
27517    pragma Export (C, u00030, "system__stack_checkingS");
27518    pragma Export (C, u00031, "system__tracebackB");
27519    pragma Export (C, u00032, "system__tracebackS");
27520    pragma Export (C, u00033, "ada__streamsS");
27521    pragma Export (C, u00034, "ada__tagsB");
27522    pragma Export (C, u00035, "ada__tagsS");
27523    pragma Export (C, u00036, "system__string_opsB");
27524    pragma Export (C, u00037, "system__string_opsS");
27525    pragma Export (C, u00038, "interfacesS");
27526    pragma Export (C, u00039, "interfaces__c_streamsB");
27527    pragma Export (C, u00040, "interfaces__c_streamsS");
27528    pragma Export (C, u00041, "system__file_ioB");
27529    pragma Export (C, u00042, "system__file_ioS");
27530    pragma Export (C, u00043, "ada__finalizationB");
27531    pragma Export (C, u00044, "ada__finalizationS");
27532    pragma Export (C, u00045, "system__finalization_rootB");
27533    pragma Export (C, u00046, "system__finalization_rootS");
27534    pragma Export (C, u00047, "system__finalization_implementationB");
27535    pragma Export (C, u00048, "system__finalization_implementationS");
27536    pragma Export (C, u00049, "system__string_ops_concat_3B");
27537    pragma Export (C, u00050, "system__string_ops_concat_3S");
27538    pragma Export (C, u00051, "system__stream_attributesB");
27539    pragma Export (C, u00052, "system__stream_attributesS");
27540    pragma Export (C, u00053, "ada__io_exceptionsS");
27541    pragma Export (C, u00054, "system__unsigned_typesS");
27542    pragma Export (C, u00055, "system__file_control_blockS");
27543    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27544    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27545
27546    -- BEGIN ELABORATION ORDER
27547    -- ada (spec)
27548    -- gnat (spec)
27549    -- gnat.heap_sort_a (spec)
27550    -- gnat.heap_sort_a (body)
27551    -- gnat.htable (spec)
27552    -- gnat.htable (body)
27553    -- interfaces (spec)
27554    -- system (spec)
27555    -- system.machine_code (spec)
27556    -- system.parameters (spec)
27557    -- system.parameters (body)
27558    -- interfaces.c_streams (spec)
27559    -- interfaces.c_streams (body)
27560    -- system.standard_library (spec)
27561    -- ada.exceptions (spec)
27562    -- system.exception_table (spec)
27563    -- system.exception_table (body)
27564    -- ada.io_exceptions (spec)
27565    -- system.exceptions (spec)
27566    -- system.storage_elements (spec)
27567    -- system.storage_elements (body)
27568    -- system.machine_state_operations (spec)
27569    -- system.machine_state_operations (body)
27570    -- system.secondary_stack (spec)
27571    -- system.stack_checking (spec)
27572    -- system.soft_links (spec)
27573    -- system.soft_links (body)
27574    -- system.stack_checking (body)
27575    -- system.secondary_stack (body)
27576    -- system.standard_library (body)
27577    -- system.string_ops (spec)
27578    -- system.string_ops (body)
27579    -- ada.tags (spec)
27580    -- ada.tags (body)
27581    -- ada.streams (spec)
27582    -- system.finalization_root (spec)
27583    -- system.finalization_root (body)
27584    -- system.string_ops_concat_3 (spec)
27585    -- system.string_ops_concat_3 (body)
27586    -- system.traceback (spec)
27587    -- system.traceback (body)
27588    -- ada.exceptions (body)
27589    -- system.unsigned_types (spec)
27590    -- system.stream_attributes (spec)
27591    -- system.stream_attributes (body)
27592    -- system.finalization_implementation (spec)
27593    -- system.finalization_implementation (body)
27594    -- ada.finalization (spec)
27595    -- ada.finalization (body)
27596    -- ada.finalization.list_controller (spec)
27597    -- ada.finalization.list_controller (body)
27598    -- system.file_control_block (spec)
27599    -- system.file_io (spec)
27600    -- system.file_io (body)
27601    -- ada.text_io (spec)
27602    -- ada.text_io (body)
27603    -- hello (body)
27604    -- END ELABORATION ORDER
27605
27606 end ada_main;
27607
27608 --  The following source file name pragmas allow the generated file
27609 --  names to be unique for different main programs. They are needed
27610 --  since the package name will always be Ada_Main.
27611
27612 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27613 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27614
27615 --  Generated package body for Ada_Main starts here
27616
27617 package body ada_main is
27618
27619    --  The actual finalization is performed by calling the
27620    --  library routine in System.Standard_Library.Adafinal
27621
27622    procedure Do_Finalize;
27623    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27624
27625    -------------
27626    -- adainit --
27627    -------------
27628
27629 @findex adainit
27630    procedure adainit is
27631
27632       --  These booleans are set to True once the associated unit has
27633       --  been elaborated. It is also used to avoid elaborating the
27634       --  same unit twice.
27635
27636       E040 : Boolean;
27637       pragma Import (Ada, E040, "interfaces__c_streams_E");
27638
27639       E008 : Boolean;
27640       pragma Import (Ada, E008, "ada__exceptions_E");
27641
27642       E014 : Boolean;
27643       pragma Import (Ada, E014, "system__exception_table_E");
27644
27645       E053 : Boolean;
27646       pragma Import (Ada, E053, "ada__io_exceptions_E");
27647
27648       E017 : Boolean;
27649       pragma Import (Ada, E017, "system__exceptions_E");
27650
27651       E024 : Boolean;
27652       pragma Import (Ada, E024, "system__secondary_stack_E");
27653
27654       E030 : Boolean;
27655       pragma Import (Ada, E030, "system__stack_checking_E");
27656
27657       E028 : Boolean;
27658       pragma Import (Ada, E028, "system__soft_links_E");
27659
27660       E035 : Boolean;
27661       pragma Import (Ada, E035, "ada__tags_E");
27662
27663       E033 : Boolean;
27664       pragma Import (Ada, E033, "ada__streams_E");
27665
27666       E046 : Boolean;
27667       pragma Import (Ada, E046, "system__finalization_root_E");
27668
27669       E048 : Boolean;
27670       pragma Import (Ada, E048, "system__finalization_implementation_E");
27671
27672       E044 : Boolean;
27673       pragma Import (Ada, E044, "ada__finalization_E");
27674
27675       E057 : Boolean;
27676       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27677
27678       E055 : Boolean;
27679       pragma Import (Ada, E055, "system__file_control_block_E");
27680
27681       E042 : Boolean;
27682       pragma Import (Ada, E042, "system__file_io_E");
27683
27684       E006 : Boolean;
27685       pragma Import (Ada, E006, "ada__text_io_E");
27686
27687       --  Set_Globals is a library routine that stores away the
27688       --  value of the indicated set of global values in global
27689       --  variables within the library.
27690
27691       procedure Set_Globals
27692         (Main_Priority            : Integer;
27693          Time_Slice_Value         : Integer;
27694          WC_Encoding              : Character;
27695          Locking_Policy           : Character;
27696          Queuing_Policy           : Character;
27697          Task_Dispatching_Policy  : Character;
27698          Adafinal                 : System.Address;
27699          Unreserve_All_Interrupts : Integer;
27700          Exception_Tracebacks     : Integer);
27701 @findex __gnat_set_globals
27702       pragma Import (C, Set_Globals, "__gnat_set_globals");
27703
27704       --  SDP_Table_Build is a library routine used to build the
27705       --  exception tables. See unit Ada.Exceptions in files
27706       --  a-except.ads/adb for full details of how zero cost
27707       --  exception handling works. This procedure, the call to
27708       --  it, and the two following tables are all omitted if the
27709       --  build is in longjmp/setjmp exception mode.
27710
27711 @findex SDP_Table_Build
27712 @findex Zero Cost Exceptions
27713       procedure SDP_Table_Build
27714         (SDP_Addresses   : System.Address;
27715          SDP_Count       : Natural;
27716          Elab_Addresses  : System.Address;
27717          Elab_Addr_Count : Natural);
27718       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27719
27720       --  Table of Unit_Exception_Table addresses. Used for zero
27721       --  cost exception handling to build the top level table.
27722
27723       ST : aliased constant array (1 .. 23) of System.Address := (
27724         Hello'UET_Address,
27725         Ada.Text_Io'UET_Address,
27726         Ada.Exceptions'UET_Address,
27727         Gnat.Heap_Sort_A'UET_Address,
27728         System.Exception_Table'UET_Address,
27729         System.Machine_State_Operations'UET_Address,
27730         System.Secondary_Stack'UET_Address,
27731         System.Parameters'UET_Address,
27732         System.Soft_Links'UET_Address,
27733         System.Stack_Checking'UET_Address,
27734         System.Traceback'UET_Address,
27735         Ada.Streams'UET_Address,
27736         Ada.Tags'UET_Address,
27737         System.String_Ops'UET_Address,
27738         Interfaces.C_Streams'UET_Address,
27739         System.File_Io'UET_Address,
27740         Ada.Finalization'UET_Address,
27741         System.Finalization_Root'UET_Address,
27742         System.Finalization_Implementation'UET_Address,
27743         System.String_Ops_Concat_3'UET_Address,
27744         System.Stream_Attributes'UET_Address,
27745         System.File_Control_Block'UET_Address,
27746         Ada.Finalization.List_Controller'UET_Address);
27747
27748       --  Table of addresses of elaboration routines. Used for
27749       --  zero cost exception handling to make sure these
27750       --  addresses are included in the top level procedure
27751       --  address table.
27752
27753       EA : aliased constant array (1 .. 23) of System.Address := (
27754         adainit'Code_Address,
27755         Do_Finalize'Code_Address,
27756         Ada.Exceptions'Elab_Spec'Address,
27757         System.Exceptions'Elab_Spec'Address,
27758         Interfaces.C_Streams'Elab_Spec'Address,
27759         System.Exception_Table'Elab_Body'Address,
27760         Ada.Io_Exceptions'Elab_Spec'Address,
27761         System.Stack_Checking'Elab_Spec'Address,
27762         System.Soft_Links'Elab_Body'Address,
27763         System.Secondary_Stack'Elab_Body'Address,
27764         Ada.Tags'Elab_Spec'Address,
27765         Ada.Tags'Elab_Body'Address,
27766         Ada.Streams'Elab_Spec'Address,
27767         System.Finalization_Root'Elab_Spec'Address,
27768         Ada.Exceptions'Elab_Body'Address,
27769         System.Finalization_Implementation'Elab_Spec'Address,
27770         System.Finalization_Implementation'Elab_Body'Address,
27771         Ada.Finalization'Elab_Spec'Address,
27772         Ada.Finalization.List_Controller'Elab_Spec'Address,
27773         System.File_Control_Block'Elab_Spec'Address,
27774         System.File_Io'Elab_Body'Address,
27775         Ada.Text_Io'Elab_Spec'Address,
27776         Ada.Text_Io'Elab_Body'Address);
27777
27778    --  Start of processing for adainit
27779
27780    begin
27781
27782       --  Call SDP_Table_Build to build the top level procedure
27783       --  table for zero cost exception handling (omitted in
27784       --  longjmp/setjmp mode).
27785
27786       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27787
27788       --  Call Set_Globals to record various information for
27789       --  this partition.  The values are derived by the binder
27790       --  from information stored in the ali files by the compiler.
27791
27792 @findex __gnat_set_globals
27793       Set_Globals
27794         (Main_Priority            => -1,
27795          --  Priority of main program, -1 if no pragma Priority used
27796
27797          Time_Slice_Value         => -1,
27798          --  Time slice from Time_Slice pragma, -1 if none used
27799
27800          WC_Encoding              => 'b',
27801          --  Wide_Character encoding used, default is brackets
27802
27803          Locking_Policy           => ' ',
27804          --  Locking_Policy used, default of space means not
27805          --  specified, otherwise it is the first character of
27806          --  the policy name.
27807
27808          Queuing_Policy           => ' ',
27809          --  Queuing_Policy used, default of space means not
27810          --  specified, otherwise it is the first character of
27811          --  the policy name.
27812
27813          Task_Dispatching_Policy  => ' ',
27814          --  Task_Dispatching_Policy used, default of space means
27815          --  not specified, otherwise first character of the
27816          --  policy name.
27817
27818          Adafinal                 => System.Null_Address,
27819          --  Address of Adafinal routine, not used anymore
27820
27821          Unreserve_All_Interrupts => 0,
27822          --  Set true if pragma Unreserve_All_Interrupts was used
27823
27824          Exception_Tracebacks     => 0);
27825          --  Indicates if exception tracebacks are enabled
27826
27827       Elab_Final_Code := 1;
27828
27829       --  Now we have the elaboration calls for all units in the partition.
27830       --  The Elab_Spec and Elab_Body attributes generate references to the
27831       --  implicit elaboration procedures generated by the compiler for
27832       --  each unit that requires elaboration.
27833
27834       if not E040 then
27835          Interfaces.C_Streams'Elab_Spec;
27836       end if;
27837       E040 := True;
27838       if not E008 then
27839          Ada.Exceptions'Elab_Spec;
27840       end if;
27841       if not E014 then
27842          System.Exception_Table'Elab_Body;
27843          E014 := True;
27844       end if;
27845       if not E053 then
27846          Ada.Io_Exceptions'Elab_Spec;
27847          E053 := True;
27848       end if;
27849       if not E017 then
27850          System.Exceptions'Elab_Spec;
27851          E017 := True;
27852       end if;
27853       if not E030 then
27854          System.Stack_Checking'Elab_Spec;
27855       end if;
27856       if not E028 then
27857          System.Soft_Links'Elab_Body;
27858          E028 := True;
27859       end if;
27860       E030 := True;
27861       if not E024 then
27862          System.Secondary_Stack'Elab_Body;
27863          E024 := True;
27864       end if;
27865       if not E035 then
27866          Ada.Tags'Elab_Spec;
27867       end if;
27868       if not E035 then
27869          Ada.Tags'Elab_Body;
27870          E035 := True;
27871       end if;
27872       if not E033 then
27873          Ada.Streams'Elab_Spec;
27874          E033 := True;
27875       end if;
27876       if not E046 then
27877          System.Finalization_Root'Elab_Spec;
27878       end if;
27879       E046 := True;
27880       if not E008 then
27881          Ada.Exceptions'Elab_Body;
27882          E008 := True;
27883       end if;
27884       if not E048 then
27885          System.Finalization_Implementation'Elab_Spec;
27886       end if;
27887       if not E048 then
27888          System.Finalization_Implementation'Elab_Body;
27889          E048 := True;
27890       end if;
27891       if not E044 then
27892          Ada.Finalization'Elab_Spec;
27893       end if;
27894       E044 := True;
27895       if not E057 then
27896          Ada.Finalization.List_Controller'Elab_Spec;
27897       end if;
27898       E057 := True;
27899       if not E055 then
27900          System.File_Control_Block'Elab_Spec;
27901          E055 := True;
27902       end if;
27903       if not E042 then
27904          System.File_Io'Elab_Body;
27905          E042 := True;
27906       end if;
27907       if not E006 then
27908          Ada.Text_Io'Elab_Spec;
27909       end if;
27910       if not E006 then
27911          Ada.Text_Io'Elab_Body;
27912          E006 := True;
27913       end if;
27914
27915       Elab_Final_Code := 0;
27916    end adainit;
27917
27918    --------------
27919    -- adafinal --
27920    --------------
27921
27922 @findex adafinal
27923    procedure adafinal is
27924    begin
27925       Do_Finalize;
27926    end adafinal;
27927
27928    ----------
27929    -- main --
27930    ----------
27931
27932    --  main is actually a function, as in the ANSI C standard,
27933    --  defined to return the exit status. The three parameters
27934    --  are the argument count, argument values and environment
27935    --  pointer.
27936
27937 @findex Main Program
27938    function main
27939      (argc : Integer;
27940       argv : System.Address;
27941       envp : System.Address)
27942       return Integer
27943    is
27944       --  The initialize routine performs low level system
27945       --  initialization using a standard library routine which
27946       --  sets up signal handling and performs any other
27947       --  required setup. The routine can be found in file
27948       --  a-init.c.
27949
27950 @findex __gnat_initialize
27951       procedure initialize;
27952       pragma Import (C, initialize, "__gnat_initialize");
27953
27954       --  The finalize routine performs low level system
27955       --  finalization using a standard library routine. The
27956       --  routine is found in file a-final.c and in the standard
27957       --  distribution is a dummy routine that does nothing, so
27958       --  really this is a hook for special user finalization.
27959
27960 @findex __gnat_finalize
27961       procedure finalize;
27962       pragma Import (C, finalize, "__gnat_finalize");
27963
27964       --  We get to the main program of the partition by using
27965       --  pragma Import because if we try to with the unit and
27966       --  call it Ada style, then not only do we waste time
27967       --  recompiling it, but also, we don't really know the right
27968       --  switches (e.g.@: identifier character set) to be used
27969       --  to compile it.
27970
27971       procedure Ada_Main_Program;
27972       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27973
27974    --  Start of processing for main
27975
27976    begin
27977       --  Save global variables
27978
27979       gnat_argc := argc;
27980       gnat_argv := argv;
27981       gnat_envp := envp;
27982
27983       --  Call low level system initialization
27984
27985       Initialize;
27986
27987       --  Call our generated Ada initialization routine
27988
27989       adainit;
27990
27991       --  This is the point at which we want the debugger to get
27992       --  control
27993
27994       Break_Start;
27995
27996       --  Now we call the main program of the partition
27997
27998       Ada_Main_Program;
27999
28000       --  Perform Ada finalization
28001
28002       adafinal;
28003
28004       --  Perform low level system finalization
28005
28006       Finalize;
28007
28008       --  Return the proper exit status
28009       return (gnat_exit_status);
28010    end;
28011
28012 --  This section is entirely comments, so it has no effect on the
28013 --  compilation of the Ada_Main package. It provides the list of
28014 --  object files and linker options, as well as some standard
28015 --  libraries needed for the link. The gnatlink utility parses
28016 --  this b~hello.adb file to read these comment lines to generate
28017 --  the appropriate command line arguments for the call to the
28018 --  system linker. The BEGIN/END lines are used for sentinels for
28019 --  this parsing operation.
28020
28021 --  The exact file names will of course depend on the environment,
28022 --  host/target and location of files on the host system.
28023
28024 @findex Object file list
28025 -- BEGIN Object file/option list
28026    --   ./hello.o
28027    --   -L./
28028    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
28029    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
28030 -- END Object file/option list
28031
28032 end ada_main;
28033 @end smallexample
28034
28035 @noindent
28036 The Ada code in the above example is exactly what is generated by the
28037 binder. We have added comments to more clearly indicate the function
28038 of each part of the generated @code{Ada_Main} package.
28039
28040 The code is standard Ada in all respects, and can be processed by any
28041 tools that handle Ada. In particular, it is possible to use the debugger
28042 in Ada mode to debug the generated @code{Ada_Main} package. For example,
28043 suppose that for reasons that you do not understand, your program is crashing
28044 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
28045 you can place a breakpoint on the call:
28046
28047 @smallexample @c ada
28048 Ada.Text_Io'Elab_Body;
28049 @end smallexample
28050
28051 @noindent
28052 and trace the elaboration routine for this package to find out where
28053 the problem might be (more usually of course you would be debugging
28054 elaboration code in your own application).
28055
28056 @node Elaboration Order Handling in GNAT
28057 @appendix Elaboration Order Handling in GNAT
28058 @cindex Order of elaboration
28059 @cindex Elaboration control
28060
28061 @menu
28062 * Elaboration Code::
28063 * Checking the Elaboration Order::
28064 * Controlling the Elaboration Order::
28065 * Controlling Elaboration in GNAT - Internal Calls::
28066 * Controlling Elaboration in GNAT - External Calls::
28067 * Default Behavior in GNAT - Ensuring Safety::
28068 * Treatment of Pragma Elaborate::
28069 * Elaboration Issues for Library Tasks::
28070 * Mixing Elaboration Models::
28071 * What to Do If the Default Elaboration Behavior Fails::
28072 * Elaboration for Access-to-Subprogram Values::
28073 * Summary of Procedures for Elaboration Control::
28074 * Other Elaboration Order Considerations::
28075 @end menu
28076
28077 @noindent
28078 This chapter describes the handling of elaboration code in Ada and
28079 in GNAT, and discusses how the order of elaboration of program units can
28080 be controlled in GNAT, either automatically or with explicit programming
28081 features.
28082
28083 @node Elaboration Code
28084 @section Elaboration Code
28085
28086 @noindent
28087 Ada provides rather general mechanisms for executing code at elaboration
28088 time, that is to say before the main program starts executing. Such code arises
28089 in three contexts:
28090
28091 @table @asis
28092 @item Initializers for variables.
28093 Variables declared at the library level, in package specs or bodies, can
28094 require initialization that is performed at elaboration time, as in:
28095 @smallexample @c ada
28096 @cartouche
28097 Sqrt_Half : Float := Sqrt (0.5);
28098 @end cartouche
28099 @end smallexample
28100
28101 @item Package initialization code
28102 Code in a @code{BEGIN-END} section at the outer level of a package body is
28103 executed as part of the package body elaboration code.
28104
28105 @item Library level task allocators
28106 Tasks that are declared using task allocators at the library level
28107 start executing immediately and hence can execute at elaboration time.
28108 @end table
28109
28110 @noindent
28111 Subprogram calls are possible in any of these contexts, which means that
28112 any arbitrary part of the program may be executed as part of the elaboration
28113 code. It is even possible to write a program which does all its work at
28114 elaboration time, with a null main program, although stylistically this
28115 would usually be considered an inappropriate way to structure
28116 a program.
28117
28118 An important concern arises in the context of elaboration code:
28119 we have to be sure that it is executed in an appropriate order. What we
28120 have is a series of elaboration code sections, potentially one section
28121 for each unit in the program. It is important that these execute
28122 in the correct order. Correctness here means that, taking the above
28123 example of the declaration of @code{Sqrt_Half},
28124 if some other piece of
28125 elaboration code references @code{Sqrt_Half},
28126 then it must run after the
28127 section of elaboration code that contains the declaration of
28128 @code{Sqrt_Half}.
28129
28130 There would never be any order of elaboration problem if we made a rule
28131 that whenever you @code{with} a unit, you must elaborate both the spec and body
28132 of that unit before elaborating the unit doing the @code{with}'ing:
28133
28134 @smallexample @c ada
28135 @group
28136 @cartouche
28137 with Unit_1;
28138 package Unit_2 is @dots{}
28139 @end cartouche
28140 @end group
28141 @end smallexample
28142
28143 @noindent
28144 would require that both the body and spec of @code{Unit_1} be elaborated
28145 before the spec of @code{Unit_2}. However, a rule like that would be far too
28146 restrictive. In particular, it would make it impossible to have routines
28147 in separate packages that were mutually recursive.
28148
28149 You might think that a clever enough compiler could look at the actual
28150 elaboration code and determine an appropriate correct order of elaboration,
28151 but in the general case, this is not possible. Consider the following
28152 example.
28153
28154 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
28155 that references
28156 the variable @code{Sqrt_1}, which is declared in the elaboration code
28157 of the body of @code{Unit_1}:
28158
28159 @smallexample @c ada
28160 @cartouche
28161 Sqrt_1 : Float := Sqrt (0.1);
28162 @end cartouche
28163 @end smallexample
28164
28165 @noindent
28166 The elaboration code of the body of @code{Unit_1} also contains:
28167
28168 @smallexample @c ada
28169 @group
28170 @cartouche
28171 if expression_1 = 1 then
28172    Q := Unit_2.Func_2;
28173 end if;
28174 @end cartouche
28175 @end group
28176 @end smallexample
28177
28178 @noindent
28179 @code{Unit_2} is exactly parallel,
28180 it has a procedure @code{Func_2} that references
28181 the variable @code{Sqrt_2}, which is declared in the elaboration code of
28182 the body @code{Unit_2}:
28183
28184 @smallexample @c ada
28185 @cartouche
28186 Sqrt_2 : Float := Sqrt (0.1);
28187 @end cartouche
28188 @end smallexample
28189
28190 @noindent
28191 The elaboration code of the body of @code{Unit_2} also contains:
28192
28193 @smallexample @c ada
28194 @group
28195 @cartouche
28196 if expression_2 = 2 then
28197    Q := Unit_1.Func_1;
28198 end if;
28199 @end cartouche
28200 @end group
28201 @end smallexample
28202
28203 @noindent
28204 Now the question is, which of the following orders of elaboration is
28205 acceptable:
28206
28207 @smallexample
28208 @group
28209 Spec of Unit_1
28210 Spec of Unit_2
28211 Body of Unit_1
28212 Body of Unit_2
28213 @end group
28214 @end smallexample
28215
28216 @noindent
28217 or
28218
28219 @smallexample
28220 @group
28221 Spec of Unit_2
28222 Spec of Unit_1
28223 Body of Unit_2
28224 Body of Unit_1
28225 @end group
28226 @end smallexample
28227
28228 @noindent
28229 If you carefully analyze the flow here, you will see that you cannot tell
28230 at compile time the answer to this question.
28231 If @code{expression_1} is not equal to 1,
28232 and @code{expression_2} is not equal to 2,
28233 then either order is acceptable, because neither of the function calls is
28234 executed. If both tests evaluate to true, then neither order is acceptable
28235 and in fact there is no correct order.
28236
28237 If one of the two expressions is true, and the other is false, then one
28238 of the above orders is correct, and the other is incorrect. For example,
28239 if @code{expression_1} /= 1 and @code{expression_2} = 2,
28240 then the call to @code{Func_1}
28241 will occur, but not the call to @code{Func_2.}
28242 This means that it is essential
28243 to elaborate the body of @code{Unit_1} before
28244 the body of @code{Unit_2}, so the first
28245 order of elaboration is correct and the second is wrong.
28246
28247 By making @code{expression_1} and @code{expression_2}
28248 depend on input data, or perhaps
28249 the time of day, we can make it impossible for the compiler or binder
28250 to figure out which of these expressions will be true, and hence it
28251 is impossible to guarantee a safe order of elaboration at run time.
28252
28253 @node Checking the Elaboration Order
28254 @section Checking the Elaboration Order
28255
28256 @noindent
28257 In some languages that involve the same kind of elaboration problems,
28258 e.g.@: Java and C++, the programmer is expected to worry about these
28259 ordering problems himself, and it is common to
28260 write a program in which an incorrect elaboration order  gives
28261 surprising results, because it references variables before they
28262 are initialized.
28263 Ada is designed to be a safe language, and a programmer-beware approach is
28264 clearly not sufficient. Consequently, the language provides three lines
28265 of defense:
28266
28267 @table @asis
28268 @item Standard rules
28269 Some standard rules restrict the possible choice of elaboration
28270 order. In particular, if you @code{with} a unit, then its spec is always
28271 elaborated before the unit doing the @code{with}. Similarly, a parent
28272 spec is always elaborated before the child spec, and finally
28273 a spec is always elaborated before its corresponding body.
28274
28275 @item Dynamic elaboration checks
28276 @cindex Elaboration checks
28277 @cindex Checks, elaboration
28278 Dynamic checks are made at run time, so that if some entity is accessed
28279 before it is elaborated (typically  by means of a subprogram call)
28280 then the exception (@code{Program_Error}) is raised.
28281
28282 @item Elaboration control
28283 Facilities are provided for the programmer to specify the desired order
28284 of elaboration.
28285 @end table
28286
28287 Let's look at these facilities in more detail. First, the rules for
28288 dynamic checking. One possible rule would be simply to say that the
28289 exception is raised if you access a variable which has not yet been
28290 elaborated. The trouble with this approach is that it could require
28291 expensive checks on every variable reference. Instead Ada has two
28292 rules which are a little more restrictive, but easier to check, and
28293 easier to state:
28294
28295 @table @asis
28296 @item Restrictions on calls
28297 A subprogram can only be called at elaboration time if its body
28298 has been elaborated. The rules for elaboration given above guarantee
28299 that the spec of the subprogram has been elaborated before the
28300 call, but not the body. If this rule is violated, then the
28301 exception @code{Program_Error} is raised.
28302
28303 @item Restrictions on instantiations
28304 A generic unit can only be instantiated if the body of the generic
28305 unit has been elaborated. Again, the rules for elaboration given above
28306 guarantee that the spec of the generic unit has been elaborated
28307 before the instantiation, but not the body. If this rule is
28308 violated, then the exception @code{Program_Error} is raised.
28309 @end table
28310
28311 @noindent
28312 The idea is that if the body has been elaborated, then any variables
28313 it references must have been elaborated; by checking for the body being
28314 elaborated we guarantee that none of its references causes any
28315 trouble. As we noted above, this is a little too restrictive, because a
28316 subprogram that has no non-local references in its body may in fact be safe
28317 to call. However, it really would be unsafe to rely on this, because
28318 it would mean that the caller was aware of details of the implementation
28319 in the body. This goes against the basic tenets of Ada.
28320
28321 A plausible implementation can be described as follows.
28322 A Boolean variable is associated with each subprogram
28323 and each generic unit. This variable is initialized to False, and is set to
28324 True at the point body is elaborated. Every call or instantiation checks the
28325 variable, and raises @code{Program_Error} if the variable is False.
28326
28327 Note that one might think that it would be good enough to have one Boolean
28328 variable for each package, but that would not deal with cases of trying
28329 to call a body in the same package as the call
28330 that has not been elaborated yet.
28331 Of course a compiler may be able to do enough analysis to optimize away
28332 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28333 does such optimizations, but still the easiest conceptual model is to
28334 think of there being one variable per subprogram.
28335
28336 @node Controlling the Elaboration Order
28337 @section Controlling the Elaboration Order
28338
28339 @noindent
28340 In the previous section we discussed the rules in Ada which ensure
28341 that @code{Program_Error} is raised if an incorrect elaboration order is
28342 chosen. This prevents erroneous executions, but we need mechanisms to
28343 specify a correct execution and avoid the exception altogether.
28344 To achieve this, Ada provides a number of features for controlling
28345 the order of elaboration. We discuss these features in this section.
28346
28347 First, there are several ways of indicating to the compiler that a given
28348 unit has no elaboration problems:
28349
28350 @table @asis
28351 @item packages that do not require a body
28352 A library package that does not require a body does not permit
28353 a body (this rule was introduced in Ada 95).
28354 Thus if we have a such a package, as in:
28355
28356 @smallexample @c ada
28357 @group
28358 @cartouche
28359 package Definitions is
28360    generic
28361       type m is new integer;
28362    package Subp is
28363       type a is array (1 .. 10) of m;
28364       type b is array (1 .. 20) of m;
28365    end Subp;
28366 end Definitions;
28367 @end cartouche
28368 @end group
28369 @end smallexample
28370
28371 @noindent
28372 A package that @code{with}'s @code{Definitions} may safely instantiate
28373 @code{Definitions.Subp} because the compiler can determine that there
28374 definitely is no package body to worry about in this case
28375
28376 @item pragma Pure
28377 @cindex pragma Pure
28378 @findex Pure
28379 Places sufficient restrictions on a unit to guarantee that
28380 no call to any subprogram in the unit can result in an
28381 elaboration problem. This means that the compiler does not need
28382 to worry about the point of elaboration of such units, and in
28383 particular, does not need to check any calls to any subprograms
28384 in this unit.
28385
28386 @item pragma Preelaborate
28387 @findex Preelaborate
28388 @cindex pragma Preelaborate
28389 This pragma places slightly less stringent restrictions on a unit than
28390 does pragma Pure,
28391 but these restrictions are still sufficient to ensure that there
28392 are no elaboration problems with any calls to the unit.
28393
28394 @item pragma Elaborate_Body
28395 @findex Elaborate_Body
28396 @cindex pragma Elaborate_Body
28397 This pragma requires that the body of a unit be elaborated immediately
28398 after its spec. Suppose a unit @code{A} has such a pragma,
28399 and unit @code{B} does
28400 a @code{with} of unit @code{A}. Recall that the standard rules require
28401 the spec of unit @code{A}
28402 to be elaborated before the @code{with}'ing unit; given the pragma in
28403 @code{A}, we also know that the body of @code{A}
28404 will be elaborated before @code{B}, so
28405 that calls to @code{A} are safe and do not need a check.
28406 @end table
28407
28408 @noindent
28409 Note that,
28410 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28411 the use of
28412 @code{Elaborate_Body} does not guarantee that the program is
28413 free of elaboration problems, because it may not be possible
28414 to satisfy the requested elaboration order.
28415 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28416 If a programmer
28417 marks @code{Unit_1} as @code{Elaborate_Body},
28418 and not @code{Unit_2,} then the order of
28419 elaboration will be:
28420
28421 @smallexample
28422 @group
28423 Spec of Unit_2
28424 Spec of Unit_1
28425 Body of Unit_1
28426 Body of Unit_2
28427 @end group
28428 @end smallexample
28429
28430 @noindent
28431 Now that means that the call to @code{Func_1} in @code{Unit_2}
28432 need not be checked,
28433 it must be safe. But the call to @code{Func_2} in
28434 @code{Unit_1} may still fail if
28435 @code{Expression_1} is equal to 1,
28436 and the programmer must still take
28437 responsibility for this not being the case.
28438
28439 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28440 eliminated, except for calls entirely within a body, which are
28441 in any case fully under programmer control. However, using the pragma
28442 everywhere is not always possible.
28443 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28444 we marked both of them as having pragma @code{Elaborate_Body}, then
28445 clearly there would be no possible elaboration order.
28446
28447 The above pragmas allow a server to guarantee safe use by clients, and
28448 clearly this is the preferable approach. Consequently a good rule
28449 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28450 and if this is not possible,
28451 mark them as @code{Elaborate_Body} if possible.
28452 As we have seen, there are situations where neither of these
28453 three pragmas can be used.
28454 So we also provide methods for clients to control the
28455 order of elaboration of the servers on which they depend:
28456
28457 @table @asis
28458 @item pragma Elaborate (unit)
28459 @findex Elaborate
28460 @cindex pragma Elaborate
28461 This pragma is placed in the context clause, after a @code{with} clause,
28462 and it requires that the body of the named unit be elaborated before
28463 the unit in which the pragma occurs. The idea is to use this pragma
28464 if the current unit calls at elaboration time, directly or indirectly,
28465 some subprogram in the named unit.
28466
28467 @item pragma Elaborate_All (unit)
28468 @findex Elaborate_All
28469 @cindex pragma Elaborate_All
28470 This is a stronger version of the Elaborate pragma. Consider the
28471 following example:
28472
28473 @smallexample
28474 Unit A @code{with}'s unit B and calls B.Func in elab code
28475 Unit B @code{with}'s unit C, and B.Func calls C.Func
28476 @end smallexample
28477
28478 @noindent
28479 Now if we put a pragma @code{Elaborate (B)}
28480 in unit @code{A}, this ensures that the
28481 body of @code{B} is elaborated before the call, but not the
28482 body of @code{C}, so
28483 the call to @code{C.Func} could still cause @code{Program_Error} to
28484 be raised.
28485
28486 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28487 not only that the body of the named unit be elaborated before the
28488 unit doing the @code{with}, but also the bodies of all units that the
28489 named unit uses, following @code{with} links transitively. For example,
28490 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28491 then it requires
28492 not only that the body of @code{B} be elaborated before @code{A},
28493 but also the
28494 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28495 @end table
28496
28497 @noindent
28498 We are now in a position to give a usage rule in Ada for avoiding
28499 elaboration problems, at least if dynamic dispatching and access to
28500 subprogram values are not used. We will handle these cases separately
28501 later.
28502
28503 The rule is simple. If a unit has elaboration code that can directly or
28504 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28505 a generic package in a @code{with}'ed unit,
28506 then if the @code{with}'ed unit does not have
28507 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28508 a pragma @code{Elaborate_All}
28509 for the @code{with}'ed unit. By following this rule a client is
28510 assured that calls can be made without risk of an exception.
28511
28512 For generic subprogram instantiations, the rule can be relaxed to
28513 require only a pragma @code{Elaborate} since elaborating the body
28514 of a subprogram cannot cause any transitive elaboration (we are
28515 not calling the subprogram in this case, just elaborating its
28516 declaration).
28517
28518 If this rule is not followed, then a program may be in one of four
28519 states:
28520
28521 @table @asis
28522 @item No order exists
28523 No order of elaboration exists which follows the rules, taking into
28524 account any @code{Elaborate}, @code{Elaborate_All},
28525 or @code{Elaborate_Body} pragmas. In
28526 this case, an Ada compiler must diagnose the situation at bind
28527 time, and refuse to build an executable program.
28528
28529 @item One or more orders exist, all incorrect
28530 One or more acceptable elaboration orders exist, and all of them
28531 generate an elaboration order problem. In this case, the binder
28532 can build an executable program, but @code{Program_Error} will be raised
28533 when the program is run.
28534
28535 @item Several orders exist, some right, some incorrect
28536 One or more acceptable elaboration orders exists, and some of them
28537 work, and some do not. The programmer has not controlled
28538 the order of elaboration, so the binder may or may not pick one of
28539 the correct orders, and the program may or may not raise an
28540 exception when it is run. This is the worst case, because it means
28541 that the program may fail when moved to another compiler, or even
28542 another version of the same compiler.
28543
28544 @item One or more orders exists, all correct
28545 One ore more acceptable elaboration orders exist, and all of them
28546 work. In this case the program runs successfully. This state of
28547 affairs can be guaranteed by following the rule we gave above, but
28548 may be true even if the rule is not followed.
28549 @end table
28550
28551 @noindent
28552 Note that one additional advantage of following our rules on the use
28553 of @code{Elaborate} and @code{Elaborate_All}
28554 is that the program continues to stay in the ideal (all orders OK) state
28555 even if maintenance
28556 changes some bodies of some units. Conversely, if a program that does
28557 not follow this rule happens to be safe at some point, this state of affairs
28558 may deteriorate silently as a result of maintenance changes.
28559
28560 You may have noticed that the above discussion did not mention
28561 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28562 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28563 code in the body makes calls to some other unit, so it is still necessary
28564 to use @code{Elaborate_All} on such units.
28565
28566 @node Controlling Elaboration in GNAT - Internal Calls
28567 @section Controlling Elaboration in GNAT - Internal Calls
28568
28569 @noindent
28570 In the case of internal calls, i.e., calls within a single package, the
28571 programmer has full control over the order of elaboration, and it is up
28572 to the programmer to elaborate declarations in an appropriate order. For
28573 example writing:
28574
28575 @smallexample @c ada
28576 @group
28577 @cartouche
28578 function One return Float;
28579
28580 Q : Float := One;
28581
28582 function One return Float is
28583 begin
28584      return 1.0;
28585 end One;
28586 @end cartouche
28587 @end group
28588 @end smallexample
28589
28590 @noindent
28591 will obviously raise @code{Program_Error} at run time, because function
28592 One will be called before its body is elaborated. In this case GNAT will
28593 generate a warning that the call will raise @code{Program_Error}:
28594
28595 @smallexample
28596 @group
28597 @cartouche
28598  1. procedure y is
28599  2.    function One return Float;
28600  3.
28601  4.    Q : Float := One;
28602                     |
28603     >>> warning: cannot call "One" before body is elaborated
28604     >>> warning: Program_Error will be raised at run time
28605
28606  5.
28607  6.    function One return Float is
28608  7.    begin
28609  8.         return 1.0;
28610  9.    end One;
28611 10.
28612 11. begin
28613 12.    null;
28614 13. end;
28615 @end cartouche
28616 @end group
28617 @end smallexample
28618
28619 @noindent
28620 Note that in this particular case, it is likely that the call is safe, because
28621 the function @code{One} does not access any global variables.
28622 Nevertheless in Ada, we do not want the validity of the check to depend on
28623 the contents of the body (think about the separate compilation case), so this
28624 is still wrong, as we discussed in the previous sections.
28625
28626 The error is easily corrected by rearranging the declarations so that the
28627 body of @code{One} appears before the declaration containing the call
28628 (note that in Ada 95 and Ada 2005,
28629 declarations can appear in any order, so there is no restriction that
28630 would prevent this reordering, and if we write:
28631
28632 @smallexample @c ada
28633 @group
28634 @cartouche
28635 function One return Float;
28636
28637 function One return Float is
28638 begin
28639      return 1.0;
28640 end One;
28641
28642 Q : Float := One;
28643 @end cartouche
28644 @end group
28645 @end smallexample
28646
28647 @noindent
28648 then all is well, no warning is generated, and no
28649 @code{Program_Error} exception
28650 will be raised.
28651 Things are more complicated when a chain of subprograms is executed:
28652
28653 @smallexample @c ada
28654 @group
28655 @cartouche
28656 function A return Integer;
28657 function B return Integer;
28658 function C return Integer;
28659
28660 function B return Integer is begin return A; end;
28661 function C return Integer is begin return B; end;
28662
28663 X : Integer := C;
28664
28665 function A return Integer is begin return 1; end;
28666 @end cartouche
28667 @end group
28668 @end smallexample
28669
28670 @noindent
28671 Now the call to @code{C}
28672 at elaboration time in the declaration of @code{X} is correct, because
28673 the body of @code{C} is already elaborated,
28674 and the call to @code{B} within the body of
28675 @code{C} is correct, but the call
28676 to @code{A} within the body of @code{B} is incorrect, because the body
28677 of @code{A} has not been elaborated, so @code{Program_Error}
28678 will be raised on the call to @code{A}.
28679 In this case GNAT will generate a
28680 warning that @code{Program_Error} may be
28681 raised at the point of the call. Let's look at the warning:
28682
28683 @smallexample
28684 @group
28685 @cartouche
28686  1. procedure x is
28687  2.    function A return Integer;
28688  3.    function B return Integer;
28689  4.    function C return Integer;
28690  5.
28691  6.    function B return Integer is begin return A; end;
28692                                                     |
28693     >>> warning: call to "A" before body is elaborated may
28694                  raise Program_Error
28695     >>> warning: "B" called at line 7
28696     >>> warning: "C" called at line 9
28697
28698  7.    function C return Integer is begin return B; end;
28699  8.
28700  9.    X : Integer := C;
28701 10.
28702 11.    function A return Integer is begin return 1; end;
28703 12.
28704 13. begin
28705 14.    null;
28706 15. end;
28707 @end cartouche
28708 @end group
28709 @end smallexample
28710
28711 @noindent
28712 Note that the message here says ``may raise'', instead of the direct case,
28713 where the message says ``will be raised''. That's because whether
28714 @code{A} is
28715 actually called depends in general on run-time flow of control.
28716 For example, if the body of @code{B} said
28717
28718 @smallexample @c ada
28719 @group
28720 @cartouche
28721 function B return Integer is
28722 begin
28723    if some-condition-depending-on-input-data then
28724       return A;
28725    else
28726       return 1;
28727    end if;
28728 end B;
28729 @end cartouche
28730 @end group
28731 @end smallexample
28732
28733 @noindent
28734 then we could not know until run time whether the incorrect call to A would
28735 actually occur, so @code{Program_Error} might
28736 or might not be raised. It is possible for a compiler to
28737 do a better job of analyzing bodies, to
28738 determine whether or not @code{Program_Error}
28739 might be raised, but it certainly
28740 couldn't do a perfect job (that would require solving the halting problem
28741 and is provably impossible), and because this is a warning anyway, it does
28742 not seem worth the effort to do the analysis. Cases in which it
28743 would be relevant are rare.
28744
28745 In practice, warnings of either of the forms given
28746 above will usually correspond to
28747 real errors, and should be examined carefully and eliminated.
28748 In the rare case where a warning is bogus, it can be suppressed by any of
28749 the following methods:
28750
28751 @itemize @bullet
28752 @item
28753 Compile with the @option{-gnatws} switch set
28754
28755 @item
28756 Suppress @code{Elaboration_Check} for the called subprogram
28757
28758 @item
28759 Use pragma @code{Warnings_Off} to turn warnings off for the call
28760 @end itemize
28761
28762 @noindent
28763 For the internal elaboration check case,
28764 GNAT by default generates the
28765 necessary run-time checks to ensure
28766 that @code{Program_Error} is raised if any
28767 call fails an elaboration check. Of course this can only happen if a
28768 warning has been issued as described above. The use of pragma
28769 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28770 some of these checks, meaning that it may be possible (but is not
28771 guaranteed) for a program to be able to call a subprogram whose body
28772 is not yet elaborated, without raising a @code{Program_Error} exception.
28773
28774 @node Controlling Elaboration in GNAT - External Calls
28775 @section Controlling Elaboration in GNAT - External Calls
28776
28777 @noindent
28778 The previous section discussed the case in which the execution of a
28779 particular thread of elaboration code occurred entirely within a
28780 single unit. This is the easy case to handle, because a programmer
28781 has direct and total control over the order of elaboration, and
28782 furthermore, checks need only be generated in cases which are rare
28783 and which the compiler can easily detect.
28784 The situation is more complex when separate compilation is taken into account.
28785 Consider the following:
28786
28787 @smallexample @c ada
28788 @cartouche
28789 @group
28790 package Math is
28791    function Sqrt (Arg : Float) return Float;
28792 end Math;
28793
28794 package body Math is
28795    function Sqrt (Arg : Float) return Float is
28796    begin
28797          @dots{}
28798    end Sqrt;
28799 end Math;
28800 @end group
28801 @group
28802 with Math;
28803 package Stuff is
28804    X : Float := Math.Sqrt (0.5);
28805 end Stuff;
28806
28807 with Stuff;
28808 procedure Main is
28809 begin
28810    @dots{}
28811 end Main;
28812 @end group
28813 @end cartouche
28814 @end smallexample
28815
28816 @noindent
28817 where @code{Main} is the main program. When this program is executed, the
28818 elaboration code must first be executed, and one of the jobs of the
28819 binder is to determine the order in which the units of a program are
28820 to be elaborated. In this case we have four units: the spec and body
28821 of @code{Math},
28822 the spec of @code{Stuff} and the body of @code{Main}).
28823 In what order should the four separate sections of elaboration code
28824 be executed?
28825
28826 There are some restrictions in the order of elaboration that the binder
28827 can choose. In particular, if unit U has a @code{with}
28828 for a package @code{X}, then you
28829 are assured that the spec of @code{X}
28830 is elaborated before U , but you are
28831 not assured that the body of @code{X}
28832 is elaborated before U.
28833 This means that in the above case, the binder is allowed to choose the
28834 order:
28835
28836 @smallexample
28837 spec of Math
28838 spec of Stuff
28839 body of Math
28840 body of Main
28841 @end smallexample
28842
28843 @noindent
28844 but that's not good, because now the call to @code{Math.Sqrt}
28845 that happens during
28846 the elaboration of the @code{Stuff}
28847 spec happens before the body of @code{Math.Sqrt} is
28848 elaborated, and hence causes @code{Program_Error} exception to be raised.
28849 At first glance, one might say that the binder is misbehaving, because
28850 obviously you want to elaborate the body of something you @code{with}
28851 first, but
28852 that is not a general rule that can be followed in all cases. Consider
28853
28854 @smallexample @c ada
28855 @group
28856 @cartouche
28857 package X is @dots{}
28858
28859 package Y is @dots{}
28860
28861 with X;
28862 package body Y is @dots{}
28863
28864 with Y;
28865 package body X is @dots{}
28866 @end cartouche
28867 @end group
28868 @end smallexample
28869
28870 @noindent
28871 This is a common arrangement, and, apart from the order of elaboration
28872 problems that might arise in connection with elaboration code, this works fine.
28873 A rule that says that you must first elaborate the body of anything you
28874 @code{with} cannot work in this case:
28875 the body of @code{X} @code{with}'s @code{Y},
28876 which means you would have to
28877 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28878 which means
28879 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28880 loop that cannot be broken.
28881
28882 It is true that the binder can in many cases guess an order of elaboration
28883 that is unlikely to cause a @code{Program_Error}
28884 exception to be raised, and it tries to do so (in the
28885 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28886 by default
28887 elaborate the body of @code{Math} right after its spec, so all will be well).
28888
28889 However, a program that blindly relies on the binder to be helpful can
28890 get into trouble, as we discussed in the previous sections, so
28891 GNAT
28892 provides a number of facilities for assisting the programmer in
28893 developing programs that are robust with respect to elaboration order.
28894
28895 @node Default Behavior in GNAT - Ensuring Safety
28896 @section Default Behavior in GNAT - Ensuring Safety
28897
28898 @noindent
28899 The default behavior in GNAT ensures elaboration safety. In its
28900 default mode GNAT implements the
28901 rule we previously described as the right approach. Let's restate it:
28902
28903 @itemize
28904 @item
28905 @emph{If a unit has elaboration code that can directly or indirectly make a
28906 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28907 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28908 does not have pragma @code{Pure} or
28909 @code{Preelaborate}, then the client should have an
28910 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28911
28912 @emph{In the case of instantiating a generic subprogram, it is always
28913 sufficient to have only an @code{Elaborate} pragma for the
28914 @code{with}'ed unit.}
28915 @end itemize
28916
28917 @noindent
28918 By following this rule a client is assured that calls and instantiations
28919 can be made without risk of an exception.
28920
28921 In this mode GNAT traces all calls that are potentially made from
28922 elaboration code, and puts in any missing implicit @code{Elaborate}
28923 and @code{Elaborate_All} pragmas.
28924 The advantage of this approach is that no elaboration problems
28925 are possible if the binder can find an elaboration order that is
28926 consistent with these implicit @code{Elaborate} and
28927 @code{Elaborate_All} pragmas. The
28928 disadvantage of this approach is that no such order may exist.
28929
28930 If the binder does not generate any diagnostics, then it means that it has
28931 found an elaboration order that is guaranteed to be safe. However, the binder
28932 may still be relying on implicitly generated @code{Elaborate} and
28933 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28934 guaranteed.
28935
28936 If it is important to guarantee portability, then the compilations should
28937 use the
28938 @option{-gnatwl}
28939 (warn on elaboration problems) switch. This will cause warning messages
28940 to be generated indicating the missing @code{Elaborate} and
28941 @code{Elaborate_All} pragmas.
28942 Consider the following source program:
28943
28944 @smallexample @c ada
28945 @group
28946 @cartouche
28947 with k;
28948 package j is
28949   m : integer := k.r;
28950 end;
28951 @end cartouche
28952 @end group
28953 @end smallexample
28954
28955 @noindent
28956 where it is clear that there
28957 should be a pragma @code{Elaborate_All}
28958 for unit @code{k}. An implicit pragma will be generated, and it is
28959 likely that the binder will be able to honor it. However, if you want
28960 to port this program to some other Ada compiler than GNAT.
28961 it is safer to include the pragma explicitly in the source. If this
28962 unit is compiled with the
28963 @option{-gnatwl}
28964 switch, then the compiler outputs a warning:
28965
28966 @smallexample
28967 @group
28968 @cartouche
28969 1. with k;
28970 2. package j is
28971 3.   m : integer := k.r;
28972                      |
28973    >>> warning: call to "r" may raise Program_Error
28974    >>> warning: missing pragma Elaborate_All for "k"
28975
28976 4. end;
28977 @end cartouche
28978 @end group
28979 @end smallexample
28980
28981 @noindent
28982 and these warnings can be used as a guide for supplying manually
28983 the missing pragmas. It is usually a bad idea to use this warning
28984 option during development. That's because it will warn you when
28985 you need to put in a pragma, but cannot warn you when it is time
28986 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28987 unnecessary dependencies and even false circularities.
28988
28989 This default mode is more restrictive than the Ada Reference
28990 Manual, and it is possible to construct programs which will compile
28991 using the dynamic model described there, but will run into a
28992 circularity using the safer static model we have described.
28993
28994 Of course any Ada compiler must be able to operate in a mode
28995 consistent with the requirements of the Ada Reference Manual,
28996 and in particular must have the capability of implementing the
28997 standard dynamic model of elaboration with run-time checks.
28998
28999 In GNAT, this standard mode can be achieved either by the use of
29000 the @option{-gnatE} switch on the compiler (@command{gcc} or
29001 @command{gnatmake}) command, or by the use of the configuration pragma:
29002
29003 @smallexample @c ada
29004 pragma Elaboration_Checks (DYNAMIC);
29005 @end smallexample
29006
29007 @noindent
29008 Either approach will cause the unit affected to be compiled using the
29009 standard dynamic run-time elaboration checks described in the Ada
29010 Reference Manual. The static model is generally preferable, since it
29011 is clearly safer to rely on compile and link time checks rather than
29012 run-time checks. However, in the case of legacy code, it may be
29013 difficult to meet the requirements of the static model. This
29014 issue is further discussed in
29015 @ref{What to Do If the Default Elaboration Behavior Fails}.
29016
29017 Note that the static model provides a strict subset of the allowed
29018 behavior and programs of the Ada Reference Manual, so if you do
29019 adhere to the static model and no circularities exist,
29020 then you are assured that your program will
29021 work using the dynamic model, providing that you remove any
29022 pragma Elaborate statements from the source.
29023
29024 @node Treatment of Pragma Elaborate
29025 @section Treatment of Pragma Elaborate
29026 @cindex Pragma Elaborate
29027
29028 @noindent
29029 The use of @code{pragma Elaborate}
29030 should generally be avoided in Ada 95 and Ada 2005 programs,
29031 since there is no guarantee that transitive calls
29032 will be properly handled. Indeed at one point, this pragma was placed
29033 in Annex J (Obsolescent Features), on the grounds that it is never useful.
29034
29035 Now that's a bit restrictive. In practice, the case in which
29036 @code{pragma Elaborate} is useful is when the caller knows that there
29037 are no transitive calls, or that the called unit contains all necessary
29038 transitive @code{pragma Elaborate} statements, and legacy code often
29039 contains such uses.
29040
29041 Strictly speaking the static mode in GNAT should ignore such pragmas,
29042 since there is no assurance at compile time that the necessary safety
29043 conditions are met. In practice, this would cause GNAT to be incompatible
29044 with correctly written Ada 83 code that had all necessary
29045 @code{pragma Elaborate} statements in place. Consequently, we made the
29046 decision that GNAT in its default mode will believe that if it encounters
29047 a @code{pragma Elaborate} then the programmer knows what they are doing,
29048 and it will trust that no elaboration errors can occur.
29049
29050 The result of this decision is two-fold. First to be safe using the
29051 static mode, you should remove all @code{pragma Elaborate} statements.
29052 Second, when fixing circularities in existing code, you can selectively
29053 use @code{pragma Elaborate} statements to convince the static mode of
29054 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
29055 statement.
29056
29057 When using the static mode with @option{-gnatwl}, any use of
29058 @code{pragma Elaborate} will generate a warning about possible
29059 problems.
29060
29061 @node Elaboration Issues for Library Tasks
29062 @section Elaboration Issues for Library Tasks
29063 @cindex Library tasks, elaboration issues
29064 @cindex Elaboration of library tasks
29065
29066 @noindent
29067 In this section we examine special elaboration issues that arise for
29068 programs that declare library level tasks.
29069
29070 Generally the model of execution of an Ada program is that all units are
29071 elaborated, and then execution of the program starts. However, the
29072 declaration of library tasks definitely does not fit this model. The
29073 reason for this is that library tasks start as soon as they are declared
29074 (more precisely, as soon as the statement part of the enclosing package
29075 body is reached), that is to say before elaboration
29076 of the program is complete. This means that if such a task calls a
29077 subprogram, or an entry in another task, the callee may or may not be
29078 elaborated yet, and in the standard
29079 Reference Manual model of dynamic elaboration checks, you can even
29080 get timing dependent Program_Error exceptions, since there can be
29081 a race between the elaboration code and the task code.
29082
29083 The static model of elaboration in GNAT seeks to avoid all such
29084 dynamic behavior, by being conservative, and the conservative
29085 approach in this particular case is to assume that all the code
29086 in a task body is potentially executed at elaboration time if
29087 a task is declared at the library level.
29088
29089 This can definitely result in unexpected circularities. Consider
29090 the following example
29091
29092 @smallexample @c ada
29093 package Decls is
29094   task Lib_Task is
29095      entry Start;
29096   end Lib_Task;
29097
29098   type My_Int is new Integer;
29099
29100   function Ident (M : My_Int) return My_Int;
29101 end Decls;
29102
29103 with Utils;
29104 package body Decls is
29105   task body Lib_Task is
29106   begin
29107      accept Start;
29108      Utils.Put_Val (2);
29109   end Lib_Task;
29110
29111   function Ident (M : My_Int) return My_Int is
29112   begin
29113      return M;
29114   end Ident;
29115 end Decls;
29116
29117 with Decls;
29118 package Utils is
29119   procedure Put_Val (Arg : Decls.My_Int);
29120 end Utils;
29121
29122 with Text_IO;
29123 package body Utils is
29124   procedure Put_Val (Arg : Decls.My_Int) is
29125   begin
29126      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29127   end Put_Val;
29128 end Utils;
29129
29130 with Decls;
29131 procedure Main is
29132 begin
29133    Decls.Lib_Task.Start;
29134 end;
29135 @end smallexample
29136
29137 @noindent
29138 If the above example is compiled in the default static elaboration
29139 mode, then a circularity occurs. The circularity comes from the call
29140 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
29141 this call occurs in elaboration code, we need an implicit pragma
29142 @code{Elaborate_All} for @code{Utils}. This means that not only must
29143 the spec and body of @code{Utils} be elaborated before the body
29144 of @code{Decls}, but also the spec and body of any unit that is
29145 @code{with'ed} by the body of @code{Utils} must also be elaborated before
29146 the body of @code{Decls}. This is the transitive implication of
29147 pragma @code{Elaborate_All} and it makes sense, because in general
29148 the body of @code{Put_Val} might have a call to something in a
29149 @code{with'ed} unit.
29150
29151 In this case, the body of Utils (actually its spec) @code{with's}
29152 @code{Decls}. Unfortunately this means that the body of @code{Decls}
29153 must be elaborated before itself, in case there is a call from the
29154 body of @code{Utils}.
29155
29156 Here is the exact chain of events we are worrying about:
29157
29158 @enumerate
29159 @item
29160 In the body of @code{Decls} a call is made from within the body of a library
29161 task to a subprogram in the package @code{Utils}. Since this call may
29162 occur at elaboration time (given that the task is activated at elaboration
29163 time), we have to assume the worst, i.e., that the
29164 call does happen at elaboration time.
29165
29166 @item
29167 This means that the body and spec of @code{Util} must be elaborated before
29168 the body of @code{Decls} so that this call does not cause an access before
29169 elaboration.
29170
29171 @item
29172 Within the body of @code{Util}, specifically within the body of
29173 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
29174 by this package.
29175
29176 @item
29177 One such @code{with}'ed package is package @code{Decls}, so there
29178 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
29179 In fact there is such a call in this example, but we would have to
29180 assume that there was such a call even if it were not there, since
29181 we are not supposed to write the body of @code{Decls} knowing what
29182 is in the body of @code{Utils}; certainly in the case of the
29183 static elaboration model, the compiler does not know what is in
29184 other bodies and must assume the worst.
29185
29186 @item
29187 This means that the spec and body of @code{Decls} must also be
29188 elaborated before we elaborate the unit containing the call, but
29189 that unit is @code{Decls}! This means that the body of @code{Decls}
29190 must be elaborated before itself, and that's a circularity.
29191 @end enumerate
29192
29193 @noindent
29194 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
29195 the body of @code{Decls} you will get a true Ada Reference Manual
29196 circularity that makes the program illegal.
29197
29198 In practice, we have found that problems with the static model of
29199 elaboration in existing code often arise from library tasks, so
29200 we must address this particular situation.
29201
29202 Note that if we compile and run the program above, using the dynamic model of
29203 elaboration (that is to say use the @option{-gnatE} switch),
29204 then it compiles, binds,
29205 links, and runs, printing the expected result of 2. Therefore in some sense
29206 the circularity here is only apparent, and we need to capture
29207 the properties of this program that  distinguish it from other library-level
29208 tasks that have real elaboration problems.
29209
29210 We have four possible answers to this question:
29211
29212 @itemize @bullet
29213
29214 @item
29215 Use the dynamic model of elaboration.
29216
29217 If we use the @option{-gnatE} switch, then as noted above, the program works.
29218 Why is this? If we examine the task body, it is apparent that the task cannot
29219 proceed past the
29220 @code{accept} statement until after elaboration has been completed, because
29221 the corresponding entry call comes from the main program, not earlier.
29222 This is why the dynamic model works here. But that's really giving
29223 up on a precise analysis, and we prefer to take this approach only if we cannot
29224 solve the
29225 problem in any other manner. So let us examine two ways to reorganize
29226 the program to avoid the potential elaboration problem.
29227
29228 @item
29229 Split library tasks into separate packages.
29230
29231 Write separate packages, so that library tasks are isolated from
29232 other declarations as much as possible. Let us look at a variation on
29233 the above program.
29234
29235 @smallexample @c ada
29236 package Decls1 is
29237   task Lib_Task is
29238      entry Start;
29239   end Lib_Task;
29240 end Decls1;
29241
29242 with Utils;
29243 package body Decls1 is
29244   task body Lib_Task is
29245   begin
29246      accept Start;
29247      Utils.Put_Val (2);
29248   end Lib_Task;
29249 end Decls1;
29250
29251 package Decls2 is
29252   type My_Int is new Integer;
29253   function Ident (M : My_Int) return My_Int;
29254 end Decls2;
29255
29256 with Utils;
29257 package body Decls2 is
29258   function Ident (M : My_Int) return My_Int is
29259   begin
29260      return M;
29261   end Ident;
29262 end Decls2;
29263
29264 with Decls2;
29265 package Utils is
29266   procedure Put_Val (Arg : Decls2.My_Int);
29267 end Utils;
29268
29269 with Text_IO;
29270 package body Utils is
29271   procedure Put_Val (Arg : Decls2.My_Int) is
29272   begin
29273      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
29274   end Put_Val;
29275 end Utils;
29276
29277 with Decls1;
29278 procedure Main is
29279 begin
29280    Decls1.Lib_Task.Start;
29281 end;
29282 @end smallexample
29283
29284 @noindent
29285 All we have done is to split @code{Decls} into two packages, one
29286 containing the library task, and one containing everything else. Now
29287 there is no cycle, and the program compiles, binds, links and executes
29288 using the default static model of elaboration.
29289
29290 @item
29291 Declare separate task types.
29292
29293 A significant part of the problem arises because of the use of the
29294 single task declaration form. This means that the elaboration of
29295 the task type, and the elaboration of the task itself (i.e.@: the
29296 creation of the task) happen at the same time. A good rule
29297 of style in Ada is to always create explicit task types. By
29298 following the additional step of placing task objects in separate
29299 packages from the task type declaration, many elaboration problems
29300 are avoided. Here is another modified example of the example program:
29301
29302 @smallexample @c ada
29303 package Decls is
29304   task type Lib_Task_Type is
29305      entry Start;
29306   end Lib_Task_Type;
29307
29308   type My_Int is new Integer;
29309
29310   function Ident (M : My_Int) return My_Int;
29311 end Decls;
29312
29313 with Utils;
29314 package body Decls is
29315   task body Lib_Task_Type is
29316   begin
29317      accept Start;
29318      Utils.Put_Val (2);
29319   end Lib_Task_Type;
29320
29321   function Ident (M : My_Int) return My_Int is
29322   begin
29323      return M;
29324   end Ident;
29325 end Decls;
29326
29327 with Decls;
29328 package Utils is
29329   procedure Put_Val (Arg : Decls.My_Int);
29330 end Utils;
29331
29332 with Text_IO;
29333 package body Utils is
29334   procedure Put_Val (Arg : Decls.My_Int) is
29335   begin
29336      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29337   end Put_Val;
29338 end Utils;
29339
29340 with Decls;
29341 package Declst is
29342    Lib_Task : Decls.Lib_Task_Type;
29343 end Declst;
29344
29345 with Declst;
29346 procedure Main is
29347 begin
29348    Declst.Lib_Task.Start;
29349 end;
29350 @end smallexample
29351
29352 @noindent
29353 What we have done here is to replace the @code{task} declaration in
29354 package @code{Decls} with a @code{task type} declaration. Then we
29355 introduce a separate package @code{Declst} to contain the actual
29356 task object. This separates the elaboration issues for
29357 the @code{task type}
29358 declaration, which causes no trouble, from the elaboration issues
29359 of the task object, which is also unproblematic, since it is now independent
29360 of the elaboration of  @code{Utils}.
29361 This separation of concerns also corresponds to
29362 a generally sound engineering principle of separating declarations
29363 from instances. This version of the program also compiles, binds, links,
29364 and executes, generating the expected output.
29365
29366 @item
29367 Use No_Entry_Calls_In_Elaboration_Code restriction.
29368 @cindex No_Entry_Calls_In_Elaboration_Code
29369
29370 The previous two approaches described how a program can be restructured
29371 to avoid the special problems caused by library task bodies. in practice,
29372 however, such restructuring may be difficult to apply to existing legacy code,
29373 so we must consider solutions that do not require massive rewriting.
29374
29375 Let us consider more carefully why our original sample program works
29376 under the dynamic model of elaboration. The reason is that the code
29377 in the task body blocks immediately on the @code{accept}
29378 statement. Now of course there is nothing to prohibit elaboration
29379 code from making entry calls (for example from another library level task),
29380 so we cannot tell in isolation that
29381 the task will not execute the accept statement  during elaboration.
29382
29383 However, in practice it is very unusual to see elaboration code
29384 make any entry calls, and the pattern of tasks starting
29385 at elaboration time and then immediately blocking on @code{accept} or
29386 @code{select} statements is very common. What this means is that
29387 the compiler is being too pessimistic when it analyzes the
29388 whole package body as though it might be executed at elaboration
29389 time.
29390
29391 If we know that the elaboration code contains no entry calls, (a very safe
29392 assumption most of the time, that could almost be made the default
29393 behavior), then we can compile all units of the program under control
29394 of the following configuration pragma:
29395
29396 @smallexample
29397 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29398 @end smallexample
29399
29400 @noindent
29401 This pragma can be placed in the @file{gnat.adc} file in the usual
29402 manner. If we take our original unmodified program and compile it
29403 in the presence of a @file{gnat.adc} containing the above pragma,
29404 then once again, we can compile, bind, link, and execute, obtaining
29405 the expected result. In the presence of this pragma, the compiler does
29406 not trace calls in a task body, that appear after the first @code{accept}
29407 or @code{select} statement, and therefore does not report a potential
29408 circularity in the original program.
29409
29410 The compiler will check to the extent it can that the above
29411 restriction is not violated, but it is not always possible to do a
29412 complete check at compile time, so it is important to use this
29413 pragma only if the stated restriction is in fact met, that is to say
29414 no task receives an entry call before elaboration of all units is completed.
29415
29416 @end itemize
29417
29418 @node Mixing Elaboration Models
29419 @section Mixing Elaboration Models
29420 @noindent
29421 So far, we have assumed that the entire program is either compiled
29422 using the dynamic model or static model, ensuring consistency. It
29423 is possible to mix the two models, but rules have to be followed
29424 if this mixing is done to ensure that elaboration checks are not
29425 omitted.
29426
29427 The basic rule is that @emph{a unit compiled with the static model cannot
29428 be @code{with'ed} by a unit compiled with the dynamic model}. The
29429 reason for this is that in the static model, a unit assumes that
29430 its clients guarantee to use (the equivalent of) pragma
29431 @code{Elaborate_All} so that no elaboration checks are required
29432 in inner subprograms, and this assumption is violated if the
29433 client is compiled with dynamic checks.
29434
29435 The precise rule is as follows. A unit that is compiled with dynamic
29436 checks can only @code{with} a unit that meets at least one of the
29437 following criteria:
29438
29439 @itemize @bullet
29440
29441 @item
29442 The @code{with'ed} unit is itself compiled with dynamic elaboration
29443 checks (that is with the @option{-gnatE} switch.
29444
29445 @item
29446 The @code{with'ed} unit is an internal GNAT implementation unit from
29447 the System, Interfaces, Ada, or GNAT hierarchies.
29448
29449 @item
29450 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29451
29452 @item
29453 The @code{with'ing} unit (that is the client) has an explicit pragma
29454 @code{Elaborate_All} for the @code{with'ed} unit.
29455
29456 @end itemize
29457
29458 @noindent
29459 If this rule is violated, that is if a unit with dynamic elaboration
29460 checks @code{with's} a unit that does not meet one of the above four
29461 criteria, then the binder (@code{gnatbind}) will issue a warning
29462 similar to that in the following example:
29463
29464 @smallexample
29465 warning: "x.ads" has dynamic elaboration checks and with's
29466 warning:   "y.ads" which has static elaboration checks
29467 @end smallexample
29468
29469 @noindent
29470 These warnings indicate that the rule has been violated, and that as a result
29471 elaboration checks may be missed in the resulting executable file.
29472 This warning may be suppressed using the @option{-ws} binder switch
29473 in the usual manner.
29474
29475 One useful application of this mixing rule is in the case of a subsystem
29476 which does not itself @code{with} units from the remainder of the
29477 application. In this case, the entire subsystem can be compiled with
29478 dynamic checks to resolve a circularity in the subsystem, while
29479 allowing the main application that uses this subsystem to be compiled
29480 using the more reliable default static model.
29481
29482 @node What to Do If the Default Elaboration Behavior Fails
29483 @section What to Do If the Default Elaboration Behavior Fails
29484
29485 @noindent
29486 If the binder cannot find an acceptable order, it outputs detailed
29487 diagnostics. For example:
29488 @smallexample
29489 @group
29490 @iftex
29491 @leftskip=0cm
29492 @end iftex
29493 error: elaboration circularity detected
29494 info:   "proc (body)" must be elaborated before "pack (body)"
29495 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29496 info:     recompile "pack (body)" with -gnatwl
29497 info:                             for full details
29498 info:       "proc (body)"
29499 info:         is needed by its spec:
29500 info:       "proc (spec)"
29501 info:         which is withed by:
29502 info:       "pack (body)"
29503 info:  "pack (body)" must be elaborated before "proc (body)"
29504 info:     reason: pragma Elaborate in unit "proc (body)"
29505 @end group
29506
29507 @end smallexample
29508
29509 @noindent
29510 In this case we have a cycle that the binder cannot break. On the one
29511 hand, there is an explicit pragma Elaborate in @code{proc} for
29512 @code{pack}. This means that the body of @code{pack} must be elaborated
29513 before the body of @code{proc}. On the other hand, there is elaboration
29514 code in @code{pack} that calls a subprogram in @code{proc}. This means
29515 that for maximum safety, there should really be a pragma
29516 Elaborate_All in @code{pack} for @code{proc} which would require that
29517 the body of @code{proc} be elaborated before the body of
29518 @code{pack}. Clearly both requirements cannot be satisfied.
29519 Faced with a circularity of this kind, you have three different options.
29520
29521 @table @asis
29522 @item Fix the program
29523 The most desirable option from the point of view of long-term maintenance
29524 is to rearrange the program so that the elaboration problems are avoided.
29525 One useful technique is to place the elaboration code into separate
29526 child packages. Another is to move some of the initialization code to
29527 explicitly called subprograms, where the program controls the order
29528 of initialization explicitly. Although this is the most desirable option,
29529 it may be impractical and involve too much modification, especially in
29530 the case of complex legacy code.
29531
29532 @item Perform dynamic checks
29533 If the compilations are done using the
29534 @option{-gnatE}
29535 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29536 manner. Dynamic checks are generated for all calls that could possibly result
29537 in raising an exception. With this switch, the compiler does not generate
29538 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29539 exactly as specified in the @cite{Ada Reference Manual}.
29540 The binder will generate
29541 an executable program that may or may not raise @code{Program_Error}, and then
29542 it is the programmer's job to ensure that it does not raise an exception. Note
29543 that it is important to compile all units with the switch, it cannot be used
29544 selectively.
29545
29546 @item Suppress checks
29547 The drawback of dynamic checks is that they generate a
29548 significant overhead at run time, both in space and time. If you
29549 are absolutely sure that your program cannot raise any elaboration
29550 exceptions, and you still want to use the dynamic elaboration model,
29551 then you can use the configuration pragma
29552 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29553 example this pragma could be placed in the @file{gnat.adc} file.
29554
29555 @item Suppress checks selectively
29556 When you know that certain calls or instantiations in elaboration code cannot
29557 possibly lead to an elaboration error, and the binder nevertheless complains
29558 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29559 elaboration circularities, it is possible to remove those warnings locally and
29560 obtain a program that will bind. Clearly this can be unsafe, and it is the
29561 responsibility of the programmer to make sure that the resulting program has no
29562 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29563 used with different granularity to suppress warnings and break elaboration
29564 circularities:
29565
29566 @itemize @bullet
29567 @item
29568 Place the pragma that names the called subprogram in the declarative part
29569 that contains the call.
29570
29571 @item
29572 Place the pragma in the declarative part, without naming an entity. This
29573 disables warnings on all calls in the corresponding  declarative region.
29574
29575 @item
29576 Place the pragma in the package spec that declares the called subprogram,
29577 and name the subprogram. This disables warnings on all elaboration calls to
29578 that subprogram.
29579
29580 @item
29581 Place the pragma in the package spec that declares the called subprogram,
29582 without naming any entity. This disables warnings on all elaboration calls to
29583 all subprograms declared in this spec.
29584
29585 @item Use Pragma Elaborate
29586 As previously described in section @xref{Treatment of Pragma Elaborate},
29587 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29588 that no elaboration checks are required on calls to the designated unit.
29589 There may be cases in which the caller knows that no transitive calls
29590 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29591 case where @code{pragma Elaborate_All} would cause a circularity.
29592 @end itemize
29593
29594 @noindent
29595 These five cases are listed in order of decreasing safety, and therefore
29596 require increasing programmer care in their application. Consider the
29597 following program:
29598
29599 @smallexample @c adanocomment
29600 package Pack1 is
29601   function F1 return Integer;
29602   X1 : Integer;
29603 end Pack1;
29604
29605 package Pack2 is
29606   function F2 return Integer;
29607   function Pure (x : integer) return integer;
29608   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29609   --  pragma Suppress (Elaboration_Check);              -- (4)
29610 end Pack2;
29611
29612 with Pack2;
29613 package body Pack1 is
29614   function F1 return Integer is
29615   begin
29616     return 100;
29617   end F1;
29618   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29619 begin
29620   declare
29621     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29622     --  pragma Suppress(Elaboration_Check);             -- (2)
29623   begin
29624     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29625   end;
29626 end Pack1;
29627
29628 with Pack1;
29629 package body Pack2 is
29630   function F2 return Integer is
29631   begin
29632      return Pack1.F1;
29633   end F2;
29634   function Pure (x : integer) return integer is
29635   begin
29636      return x ** 3 - 3 * x;
29637   end;
29638 end Pack2;
29639
29640 with Pack1, Ada.Text_IO;
29641 procedure Proc3 is
29642 begin
29643   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29644 end Proc3;
29645 @end smallexample
29646 In the absence of any pragmas, an attempt to bind this program produces
29647 the following diagnostics:
29648 @smallexample
29649 @group
29650 @iftex
29651 @leftskip=.5cm
29652 @end iftex
29653 error: elaboration circularity detected
29654 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29655 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29656 info:       recompile "pack1 (body)" with -gnatwl for full details
29657 info:          "pack1 (body)"
29658 info:             must be elaborated along with its spec:
29659 info:          "pack1 (spec)"
29660 info:             which is withed by:
29661 info:          "pack2 (body)"
29662 info:             which must be elaborated along with its spec:
29663 info:          "pack2 (spec)"
29664 info:             which is withed by:
29665 info:          "pack1 (body)"
29666 @end group
29667 @end smallexample
29668 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29669 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29670 F2 is safe, even though F2 calls F1, because the call appears after the
29671 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29672 remove the warning on the call. It is also possible to use pragma (2)
29673 because there are no other potentially unsafe calls in the block.
29674
29675 @noindent
29676 The call to @code{Pure} is safe because this function does not depend on the
29677 state of @code{Pack2}. Therefore any call to this function is safe, and it
29678 is correct to place pragma (3) in the corresponding package spec.
29679
29680 @noindent
29681 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29682 warnings on all calls to functions declared therein. Note that this is not
29683 necessarily safe, and requires more detailed examination of the subprogram
29684 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29685 be already elaborated.
29686 @end table
29687
29688 @noindent
29689 It is hard to generalize on which of these four approaches should be
29690 taken. Obviously if it is possible to fix the program so that the default
29691 treatment works, this is preferable, but this may not always be practical.
29692 It is certainly simple enough to use
29693 @option{-gnatE}
29694 but the danger in this case is that, even if the GNAT binder
29695 finds a correct elaboration order, it may not always do so,
29696 and certainly a binder from another Ada compiler might not. A
29697 combination of testing and analysis (for which the warnings generated
29698 with the
29699 @option{-gnatwl}
29700 switch can be useful) must be used to ensure that the program is free
29701 of errors. One switch that is useful in this testing is the
29702 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29703 switch for
29704 @code{gnatbind}.
29705 Normally the binder tries to find an order that has the best chance
29706 of avoiding elaboration problems. However, if this switch is used, the binder
29707 plays a devil's advocate role, and tries to choose the order that
29708 has the best chance of failing. If your program works even with this
29709 switch, then it has a better chance of being error free, but this is still
29710 not a guarantee.
29711
29712 For an example of this approach in action, consider the C-tests (executable
29713 tests) from the ACVC suite. If these are compiled and run with the default
29714 treatment, then all but one of them succeed without generating any error
29715 diagnostics from the binder. However, there is one test that fails, and
29716 this is not surprising, because the whole point of this test is to ensure
29717 that the compiler can handle cases where it is impossible to determine
29718 a correct order statically, and it checks that an exception is indeed
29719 raised at run time.
29720
29721 This one test must be compiled and run using the
29722 @option{-gnatE}
29723 switch, and then it passes. Alternatively, the entire suite can
29724 be run using this switch. It is never wrong to run with the dynamic
29725 elaboration switch if your code is correct, and we assume that the
29726 C-tests are indeed correct (it is less efficient, but efficiency is
29727 not a factor in running the ACVC tests.)
29728
29729 @node Elaboration for Access-to-Subprogram Values
29730 @section Elaboration for Access-to-Subprogram Values
29731 @cindex Access-to-subprogram
29732
29733 @noindent
29734 Access-to-subprogram types (introduced in Ada 95) complicate
29735 the handling of elaboration. The trouble is that it becomes
29736 impossible to tell at compile time which procedure
29737 is being called. This means that it is not possible for the binder
29738 to analyze the elaboration requirements in this case.
29739
29740 If at the point at which the access value is created
29741 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29742 the body of the subprogram is
29743 known to have been elaborated, then the access value is safe, and its use
29744 does not require a check. This may be achieved by appropriate arrangement
29745 of the order of declarations if the subprogram is in the current unit,
29746 or, if the subprogram is in another unit, by using pragma
29747 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29748 on the referenced unit.
29749
29750 If the referenced body is not known to have been elaborated at the point
29751 the access value is created, then any use of the access value must do a
29752 dynamic check, and this dynamic check will fail and raise a
29753 @code{Program_Error} exception if the body has not been elaborated yet.
29754 GNAT will generate the necessary checks, and in addition, if the
29755 @option{-gnatwl}
29756 switch is set, will generate warnings that such checks are required.
29757
29758 The use of dynamic dispatching for tagged types similarly generates
29759 a requirement for dynamic checks, and premature calls to any primitive
29760 operation of a tagged type before the body of the operation has been
29761 elaborated, will result in the raising of @code{Program_Error}.
29762
29763 @node Summary of Procedures for Elaboration Control
29764 @section Summary of Procedures for Elaboration Control
29765 @cindex Elaboration control
29766
29767 @noindent
29768 First, compile your program with the default options, using none of
29769 the special elaboration control switches. If the binder successfully
29770 binds your program, then you can be confident that, apart from issues
29771 raised by the use of access-to-subprogram types and dynamic dispatching,
29772 the program is free of elaboration errors. If it is important that the
29773 program be portable, then use the
29774 @option{-gnatwl}
29775 switch to generate warnings about missing @code{Elaborate} or
29776 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29777
29778 If the program fails to bind using the default static elaboration
29779 handling, then you can fix the program to eliminate the binder
29780 message, or recompile the entire program with the
29781 @option{-gnatE} switch to generate dynamic elaboration checks,
29782 and, if you are sure there really are no elaboration problems,
29783 use a global pragma @code{Suppress (Elaboration_Check)}.
29784
29785 @node Other Elaboration Order Considerations
29786 @section Other Elaboration Order Considerations
29787 @noindent
29788 This section has been entirely concerned with the issue of finding a valid
29789 elaboration order, as defined by the Ada Reference Manual. In a case
29790 where several elaboration orders are valid, the task is to find one
29791 of the possible valid elaboration orders (and the static model in GNAT
29792 will ensure that this is achieved).
29793
29794 The purpose of the elaboration rules in the Ada Reference Manual is to
29795 make sure that no entity is accessed before it has been elaborated. For
29796 a subprogram, this means that the spec and body must have been elaborated
29797 before the subprogram is called. For an object, this means that the object
29798 must have been elaborated before its value is read or written. A violation
29799 of either of these two requirements is an access before elaboration order,
29800 and this section has been all about avoiding such errors.
29801
29802 In the case where more than one order of elaboration is possible, in the
29803 sense that access before elaboration errors are avoided, then any one of
29804 the orders is ``correct'' in the sense that it meets the requirements of
29805 the Ada Reference Manual, and no such error occurs.
29806
29807 However, it may be the case for a given program, that there are
29808 constraints on the order of elaboration that come not from consideration
29809 of avoiding elaboration errors, but rather from extra-lingual logic
29810 requirements. Consider this example:
29811
29812 @smallexample @c ada
29813 with Init_Constants;
29814 package Constants is
29815    X : Integer := 0;
29816    Y : Integer := 0;
29817 end Constants;
29818
29819 package Init_Constants is
29820    procedure P; -- require a body
29821 end Init_Constants;
29822
29823 with Constants;
29824 package body Init_Constants is
29825    procedure P is begin null; end;
29826 begin
29827    Constants.X := 3;
29828    Constants.Y := 4;
29829 end Init_Constants;
29830
29831 with Constants;
29832 package Calc is
29833    Z : Integer := Constants.X + Constants.Y;
29834 end Calc;
29835
29836 with Calc;
29837 with Text_IO; use Text_IO;
29838 procedure Main is
29839 begin
29840    Put_Line (Calc.Z'Img);
29841 end Main;
29842 @end smallexample
29843
29844 @noindent
29845 In this example, there is more than one valid order of elaboration. For
29846 example both the following are correct orders:
29847
29848 @smallexample
29849 Init_Constants spec
29850 Constants spec
29851 Calc spec
29852 Init_Constants body
29853 Main body
29854
29855   and
29856
29857 Init_Constants spec
29858 Init_Constants body
29859 Constants spec
29860 Calc spec
29861 Main body
29862 @end smallexample
29863
29864 @noindent
29865 There is no language rule to prefer one or the other, both are correct
29866 from an order of elaboration point of view. But the programmatic effects
29867 of the two orders are very different. In the first, the elaboration routine
29868 of @code{Calc} initializes @code{Z} to zero, and then the main program
29869 runs with this value of zero. But in the second order, the elaboration
29870 routine of @code{Calc} runs after the body of Init_Constants has set
29871 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29872 runs.
29873
29874 One could perhaps by applying pretty clever non-artificial intelligence
29875 to the situation guess that it is more likely that the second order of
29876 elaboration is the one desired, but there is no formal linguistic reason
29877 to prefer one over the other. In fact in this particular case, GNAT will
29878 prefer the second order, because of the rule that bodies are elaborated
29879 as soon as possible, but it's just luck that this is what was wanted
29880 (if indeed the second order was preferred).
29881
29882 If the program cares about the order of elaboration routines in a case like
29883 this, it is important to specify the order required. In this particular
29884 case, that could have been achieved by adding to the spec of Calc:
29885
29886 @smallexample @c ada
29887 pragma Elaborate_All (Constants);
29888 @end smallexample
29889
29890 @noindent
29891 which requires that the body (if any) and spec of @code{Constants},
29892 as well as the body and spec of any unit @code{with}'ed by
29893 @code{Constants} be elaborated before @code{Calc} is elaborated.
29894
29895 Clearly no automatic method can always guess which alternative you require,
29896 and if you are working with legacy code that had constraints of this kind
29897 which were not properly specified by adding @code{Elaborate} or
29898 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29899 compilers can choose different orders.
29900
29901 However, GNAT does attempt to diagnose the common situation where there
29902 are uninitialized variables in the visible part of a package spec, and the
29903 corresponding package body has an elaboration block that directly or
29904 indirectly initialized one or more of these variables. This is the situation
29905 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29906 a warning that suggests this addition if it detects this situation.
29907
29908 The @code{gnatbind}
29909 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29910 out problems. This switch causes bodies to be elaborated as late as possible
29911 instead of as early as possible. In the example above, it would have forced
29912 the choice of the first elaboration order. If you get different results
29913 when using this switch, and particularly if one set of results is right,
29914 and one is wrong as far as you are concerned, it shows that you have some
29915 missing @code{Elaborate} pragmas. For the example above, we have the
29916 following output:
29917
29918 @smallexample
29919 gnatmake -f -q main
29920 main
29921  7
29922 gnatmake -f -q main -bargs -p
29923 main
29924  0
29925 @end smallexample
29926
29927 @noindent
29928 It is of course quite unlikely that both these results are correct, so
29929 it is up to you in a case like this to investigate the source of the
29930 difference, by looking at the two elaboration orders that are chosen,
29931 and figuring out which is correct, and then adding the necessary
29932 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29933
29934
29935
29936 @c *******************************
29937 @node Conditional Compilation
29938 @appendix Conditional Compilation
29939 @c *******************************
29940 @cindex Conditional compilation
29941
29942 @noindent
29943 It is often necessary to arrange for a single source program
29944 to serve multiple purposes, where it is compiled in different
29945 ways to achieve these different goals. Some examples of the
29946 need for this feature are
29947
29948 @itemize @bullet
29949 @item  Adapting a program to a different hardware environment
29950 @item  Adapting a program to a different target architecture
29951 @item  Turning debugging features on and off
29952 @item  Arranging for a program to compile with different compilers
29953 @end itemize
29954
29955 @noindent
29956 In C, or C++, the typical approach would be to use the preprocessor
29957 that is defined as part of the language. The Ada language does not
29958 contain such a feature. This is not an oversight, but rather a very
29959 deliberate design decision, based on the experience that overuse of
29960 the preprocessing features in C and C++ can result in programs that
29961 are extremely difficult to maintain. For example, if we have ten
29962 switches that can be on or off, this means that there are a thousand
29963 separate programs, any one of which might not even be syntactically
29964 correct, and even if syntactically correct, the resulting program
29965 might not work correctly. Testing all combinations can quickly become
29966 impossible.
29967
29968 Nevertheless, the need to tailor programs certainly exists, and in
29969 this Appendix we will discuss how this can
29970 be achieved using Ada in general, and GNAT in particular.
29971
29972 @menu
29973 * Use of Boolean Constants::
29974 * Debugging - A Special Case::
29975 * Conditionalizing Declarations::
29976 * Use of Alternative Implementations::
29977 * Preprocessing::
29978 @end menu
29979
29980 @node Use of Boolean Constants
29981 @section Use of Boolean Constants
29982
29983 @noindent
29984 In the case where the difference is simply which code
29985 sequence is executed, the cleanest solution is to use Boolean
29986 constants to control which code is executed.
29987
29988 @smallexample @c ada
29989 @group
29990 FP_Initialize_Required : constant Boolean := True;
29991 @dots{}
29992 if FP_Initialize_Required then
29993 @dots{}
29994 end if;
29995 @end group
29996 @end smallexample
29997
29998 @noindent
29999 Not only will the code inside the @code{if} statement not be executed if
30000 the constant Boolean is @code{False}, but it will also be completely
30001 deleted from the program.
30002 However, the code is only deleted after the @code{if} statement
30003 has been checked for syntactic and semantic correctness.
30004 (In contrast, with preprocessors the code is deleted before the
30005 compiler ever gets to see it, so it is not checked until the switch
30006 is turned on.)
30007 @cindex Preprocessors (contrasted with conditional compilation)
30008
30009 Typically the Boolean constants will be in a separate package,
30010 something like:
30011
30012 @smallexample @c ada
30013 @group
30014 package Config is
30015    FP_Initialize_Required : constant Boolean := True;
30016    Reset_Available        : constant Boolean := False;
30017    @dots{}
30018 end Config;
30019 @end group
30020 @end smallexample
30021
30022 @noindent
30023 The @code{Config} package exists in multiple forms for the various targets,
30024 with an appropriate script selecting the version of @code{Config} needed.
30025 Then any other unit requiring conditional compilation can do a @code{with}
30026 of @code{Config} to make the constants visible.
30027
30028
30029 @node Debugging - A Special Case
30030 @section Debugging - A Special Case
30031
30032 @noindent
30033 A common use of conditional code is to execute statements (for example
30034 dynamic checks, or output of intermediate results) under control of a
30035 debug switch, so that the debugging behavior can be turned on and off.
30036 This can be done using a Boolean constant to control whether the code
30037 is active:
30038
30039 @smallexample @c ada
30040 @group
30041 if Debugging then
30042    Put_Line ("got to the first stage!");
30043 end if;
30044 @end group
30045 @end smallexample
30046
30047 @noindent
30048 or
30049
30050 @smallexample @c ada
30051 @group
30052 if Debugging and then Temperature > 999.0 then
30053    raise Temperature_Crazy;
30054 end if;
30055 @end group
30056 @end smallexample
30057
30058 @noindent
30059 Since this is a common case, there are special features to deal with
30060 this in a convenient manner. For the case of tests, Ada 2005 has added
30061 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
30062 @cindex pragma @code{Assert}
30063 on the @code{Assert} pragma that has always been available in GNAT, so this
30064 feature may be used with GNAT even if you are not using Ada 2005 features.
30065 The use of pragma @code{Assert} is described in
30066 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
30067 example, the last test could be written:
30068
30069 @smallexample @c ada
30070 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
30071 @end smallexample
30072
30073 @noindent
30074 or simply
30075
30076 @smallexample @c ada
30077 pragma Assert (Temperature <= 999.0);
30078 @end smallexample
30079
30080 @noindent
30081 In both cases, if assertions are active and the temperature is excessive,
30082 the exception @code{Assert_Failure} will be raised, with the given string in
30083 the first case or a string indicating the location of the pragma in the second
30084 case used as the exception message.
30085
30086 You can turn assertions on and off by using the @code{Assertion_Policy}
30087 pragma.
30088 @cindex pragma @code{Assertion_Policy}
30089 This is an Ada 2005 pragma which is implemented in all modes by
30090 GNAT, but only in the latest versions of GNAT which include Ada 2005
30091 capability. Alternatively, you can use the @option{-gnata} switch
30092 @cindex @option{-gnata} switch
30093 to enable assertions from the command line (this is recognized by all versions
30094 of GNAT).
30095
30096 For the example above with the @code{Put_Line}, the GNAT-specific pragma
30097 @code{Debug} can be used:
30098 @cindex pragma @code{Debug}
30099
30100 @smallexample @c ada
30101 pragma Debug (Put_Line ("got to the first stage!"));
30102 @end smallexample
30103
30104 @noindent
30105 If debug pragmas are enabled, the argument, which must be of the form of
30106 a procedure call, is executed (in this case, @code{Put_Line} will be called).
30107 Only one call can be present, but of course a special debugging procedure
30108 containing any code you like can be included in the program and then
30109 called in a pragma @code{Debug} argument as needed.
30110
30111 One advantage of pragma @code{Debug} over the @code{if Debugging then}
30112 construct is that pragma @code{Debug} can appear in declarative contexts,
30113 such as at the very beginning of a procedure, before local declarations have
30114 been elaborated.
30115
30116 Debug pragmas are enabled using either the @option{-gnata} switch that also
30117 controls assertions, or with a separate Debug_Policy pragma.
30118 @cindex pragma @code{Debug_Policy}
30119 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
30120 in Ada 95 and Ada 83 programs as well), and is analogous to
30121 pragma @code{Assertion_Policy} to control assertions.
30122
30123 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
30124 and thus they can appear in @file{gnat.adc} if you are not using a
30125 project file, or in the file designated to contain configuration pragmas
30126 in a project file.
30127 They then apply to all subsequent compilations. In practice the use of
30128 the @option{-gnata} switch is often the most convenient method of controlling
30129 the status of these pragmas.
30130
30131 Note that a pragma is not a statement, so in contexts where a statement
30132 sequence is required, you can't just write a pragma on its own. You have
30133 to add a @code{null} statement.
30134
30135 @smallexample @c ada
30136 @group
30137 if @dots{} then
30138    @dots{} -- some statements
30139 else
30140    pragma Assert (Num_Cases < 10);
30141    null;
30142 end if;
30143 @end group
30144 @end smallexample
30145
30146
30147 @node Conditionalizing Declarations
30148 @section Conditionalizing Declarations
30149
30150 @noindent
30151 In some cases, it may be necessary to conditionalize declarations to meet
30152 different requirements. For example we might want a bit string whose length
30153 is set to meet some hardware message requirement.
30154
30155 In some cases, it may be possible to do this using declare blocks controlled
30156 by conditional constants:
30157
30158 @smallexample @c ada
30159 @group
30160 if Small_Machine then
30161    declare
30162       X : Bit_String (1 .. 10);
30163    begin
30164       @dots{}
30165    end;
30166 else
30167    declare
30168       X : Large_Bit_String (1 .. 1000);
30169    begin
30170       @dots{}
30171    end;
30172 end if;
30173 @end group
30174 @end smallexample
30175
30176 @noindent
30177 Note that in this approach, both declarations are analyzed by the
30178 compiler so this can only be used where both declarations are legal,
30179 even though one of them will not be used.
30180
30181 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
30182 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
30183 that are parameterized by these constants. For example
30184
30185 @smallexample @c ada
30186 @group
30187 for Rec use
30188   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
30189 end record;
30190 @end group
30191 @end smallexample
30192
30193 @noindent
30194 If @code{Bits_Per_Word} is set to 32, this generates either
30195
30196 @smallexample @c ada
30197 @group
30198 for Rec use
30199   Field1 at 0 range 0 .. 32;
30200 end record;
30201 @end group
30202 @end smallexample
30203
30204 @noindent
30205 for the big endian case, or
30206
30207 @smallexample @c ada
30208 @group
30209 for Rec use record
30210   Field1 at 0 range 10 .. 32;
30211 end record;
30212 @end group
30213 @end smallexample
30214
30215 @noindent
30216 for the little endian case. Since a powerful subset of Ada expression
30217 notation is usable for creating static constants, clever use of this
30218 feature can often solve quite difficult problems in conditionalizing
30219 compilation (note incidentally that in Ada 95, the little endian
30220 constant was introduced as @code{System.Default_Bit_Order}, so you do not
30221 need to define this one yourself).
30222
30223
30224 @node Use of Alternative Implementations
30225 @section Use of Alternative Implementations
30226
30227 @noindent
30228 In some cases, none of the approaches described above are adequate. This
30229 can occur for example if the set of declarations required is radically
30230 different for two different configurations.
30231
30232 In this situation, the official Ada way of dealing with conditionalizing
30233 such code is to write separate units for the different cases. As long as
30234 this does not result in excessive duplication of code, this can be done
30235 without creating maintenance problems. The approach is to share common
30236 code as far as possible, and then isolate the code and declarations
30237 that are different. Subunits are often a convenient method for breaking
30238 out a piece of a unit that is to be conditionalized, with separate files
30239 for different versions of the subunit for different targets, where the
30240 build script selects the right one to give to the compiler.
30241 @cindex Subunits (and conditional compilation)
30242
30243 As an example, consider a situation where a new feature in Ada 2005
30244 allows something to be done in a really nice way. But your code must be able
30245 to compile with an Ada 95 compiler. Conceptually you want to say:
30246
30247 @smallexample @c ada
30248 @group
30249 if Ada_2005 then
30250    @dots{} neat Ada 2005 code
30251 else
30252    @dots{} not quite as neat Ada 95 code
30253 end if;
30254 @end group
30255 @end smallexample
30256
30257 @noindent
30258 where @code{Ada_2005} is a Boolean constant.
30259
30260 But this won't work when @code{Ada_2005} is set to @code{False},
30261 since the @code{then} clause will be illegal for an Ada 95 compiler.
30262 (Recall that although such unreachable code would eventually be deleted
30263 by the compiler, it still needs to be legal.  If it uses features
30264 introduced in Ada 2005, it will be illegal in Ada 95.)
30265
30266 So instead we write
30267
30268 @smallexample @c ada
30269 procedure Insert is separate;
30270 @end smallexample
30271
30272 @noindent
30273 Then we have two files for the subunit @code{Insert}, with the two sets of
30274 code.
30275 If the package containing this is called @code{File_Queries}, then we might
30276 have two files
30277
30278 @itemize @bullet
30279 @item    @file{file_queries-insert-2005.adb}
30280 @item    @file{file_queries-insert-95.adb}
30281 @end itemize
30282
30283 @noindent
30284 and the build script renames the appropriate file to
30285
30286 @smallexample
30287 file_queries-insert.adb
30288 @end smallexample
30289
30290 @noindent
30291 and then carries out the compilation.
30292
30293 This can also be done with project files' naming schemes. For example:
30294
30295 @smallexample @c project
30296 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30297 @end smallexample
30298
30299 @noindent
30300 Note also that with project files it is desirable to use a different extension
30301 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30302 conflict may arise through another commonly used feature: to declare as part
30303 of the project a set of directories containing all the sources obeying the
30304 default naming scheme.
30305
30306 The use of alternative units is certainly feasible in all situations,
30307 and for example the Ada part of the GNAT run-time is conditionalized
30308 based on the target architecture using this approach. As a specific example,
30309 consider the implementation of the AST feature in VMS. There is one
30310 spec:
30311
30312 @smallexample
30313 s-asthan.ads
30314 @end smallexample
30315
30316 @noindent
30317 which is the same for all architectures, and three bodies:
30318
30319 @table @file
30320 @item    s-asthan.adb
30321 used for all non-VMS operating systems
30322 @item    s-asthan-vms-alpha.adb
30323 used for VMS on the Alpha
30324 @item    s-asthan-vms-ia64.adb
30325 used for VMS on the ia64
30326 @end table
30327
30328 @noindent
30329 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30330 this operating system feature is not available, and the two remaining
30331 versions interface with the corresponding versions of VMS to provide
30332 VMS-compatible AST handling. The GNAT build script knows the architecture
30333 and operating system, and automatically selects the right version,
30334 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30335
30336 Another style for arranging alternative implementations is through Ada's
30337 access-to-subprogram facility.
30338 In case some functionality is to be conditionally included,
30339 you can declare an access-to-procedure variable @code{Ref} that is initialized
30340 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30341 when appropriate.
30342 In some library package, set @code{Ref} to @code{Proc'Access} for some
30343 procedure @code{Proc} that performs the relevant processing.
30344 The initialization only occurs if the library package is included in the
30345 program.
30346 The same idea can also be implemented using tagged types and dispatching
30347 calls.
30348
30349
30350 @node Preprocessing
30351 @section Preprocessing
30352 @cindex Preprocessing
30353
30354 @noindent
30355 Although it is quite possible to conditionalize code without the use of
30356 C-style preprocessing, as described earlier in this section, it is
30357 nevertheless convenient in some cases to use the C approach. Moreover,
30358 older Ada compilers have often provided some preprocessing capability,
30359 so legacy code may depend on this approach, even though it is not
30360 standard.
30361
30362 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30363 extent on the various preprocessors that have been used
30364 with legacy code on other compilers, to enable easier transition).
30365
30366 The preprocessor may be used in two separate modes. It can be used quite
30367 separately from the compiler, to generate a separate output source file
30368 that is then fed to the compiler as a separate step. This is the
30369 @code{gnatprep} utility, whose use is fully described in
30370 @ref{Preprocessing Using gnatprep}.
30371 @cindex @code{gnatprep}
30372
30373 The preprocessing language allows such constructs as
30374
30375 @smallexample
30376 @group
30377 #if DEBUG or PRIORITY > 4 then
30378    bunch of declarations
30379 #else
30380    completely different bunch of declarations
30381 #end if;
30382 @end group
30383 @end smallexample
30384
30385 @noindent
30386 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30387 defined either on the command line or in a separate file.
30388
30389 The other way of running the preprocessor is even closer to the C style and
30390 often more convenient. In this approach the preprocessing is integrated into
30391 the compilation process. The compiler is fed the preprocessor input which
30392 includes @code{#if} lines etc, and then the compiler carries out the
30393 preprocessing internally and processes the resulting output.
30394 For more details on this approach, see @ref{Integrated Preprocessing}.
30395
30396
30397 @c *******************************
30398 @node Inline Assembler
30399 @appendix Inline Assembler
30400 @c *******************************
30401
30402 @noindent
30403 If you need to write low-level software that interacts directly
30404 with the hardware, Ada provides two ways to incorporate assembly
30405 language code into your program.  First, you can import and invoke
30406 external routines written in assembly language, an Ada feature fully
30407 supported by GNAT@.  However, for small sections of code it may be simpler
30408 or more efficient to include assembly language statements directly
30409 in your Ada source program, using the facilities of the implementation-defined
30410 package @code{System.Machine_Code}, which incorporates the gcc
30411 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30412 including the following:
30413
30414 @itemize @bullet
30415 @item No need to use non-Ada tools
30416 @item Consistent interface over different targets
30417 @item Automatic usage of the proper calling conventions
30418 @item Access to Ada constants and variables
30419 @item Definition of intrinsic routines
30420 @item Possibility of inlining a subprogram comprising assembler code
30421 @item Code optimizer can take Inline Assembler code into account
30422 @end itemize
30423
30424 This chapter presents a series of examples to show you how to use
30425 the Inline Assembler.  Although it focuses on the Intel x86,
30426 the general approach applies also to other processors.
30427 It is assumed that you are familiar with Ada
30428 and with assembly language programming.
30429
30430 @menu
30431 * Basic Assembler Syntax::
30432 * A Simple Example of Inline Assembler::
30433 * Output Variables in Inline Assembler::
30434 * Input Variables in Inline Assembler::
30435 * Inlining Inline Assembler Code::
30436 * Other Asm Functionality::
30437 @end menu
30438
30439 @c ---------------------------------------------------------------------------
30440 @node Basic Assembler Syntax
30441 @section Basic Assembler Syntax
30442
30443 @noindent
30444 The assembler used by GNAT and gcc is based not on the Intel assembly
30445 language, but rather on a language that descends from the AT&T Unix
30446 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30447 The following table summarizes the main features of @emph{as} syntax
30448 and points out the differences from the Intel conventions.
30449 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30450 pre-processor) documentation for further information.
30451
30452 @table @asis
30453 @item Register names
30454 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30455 @*
30456 Intel: No extra punctuation; for example @code{eax}
30457
30458 @item Immediate operand
30459 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30460 @*
30461 Intel: No extra punctuation; for example @code{4}
30462
30463 @item Address
30464 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30465 @*
30466 Intel: No extra punctuation; for example @code{loc}
30467
30468 @item Memory contents
30469 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30470 @*
30471 Intel: Square brackets; for example @code{[loc]}
30472
30473 @item Register contents
30474 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30475 @*
30476 Intel: Square brackets; for example @code{[eax]}
30477
30478 @item Hexadecimal numbers
30479 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30480 @*
30481 Intel: Trailing ``h''; for example @code{A0h}
30482
30483 @item Operand size
30484 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30485 a 16-bit word
30486 @*
30487 Intel: Implicit, deduced by assembler; for example @code{mov}
30488
30489 @item Instruction repetition
30490 gcc / @emph{as}: Split into two lines; for example
30491 @*
30492 @code{rep}
30493 @*
30494 @code{stosl}
30495 @*
30496 Intel: Keep on one line; for example @code{rep stosl}
30497
30498 @item Order of operands
30499 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30500 @*
30501 Intel: Destination first; for example @code{mov eax, 4}
30502 @end table
30503
30504 @c ---------------------------------------------------------------------------
30505 @node A Simple Example of Inline Assembler
30506 @section A Simple Example of Inline Assembler
30507
30508 @noindent
30509 The following example will generate a single assembly language statement,
30510 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30511 the example will be useful in illustrating the basics of
30512 the Inline Assembler facility.
30513
30514 @smallexample @c ada
30515 @group
30516 with System.Machine_Code; use System.Machine_Code;
30517 procedure Nothing is
30518 begin
30519    Asm ("nop");
30520 end Nothing;
30521 @end group
30522 @end smallexample
30523
30524 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30525 here it takes one parameter, a @emph{template string} that must be a static
30526 expression and that will form the generated instruction.
30527 @code{Asm} may be regarded as a compile-time procedure that parses
30528 the template string and additional parameters (none here),
30529 from which it generates a sequence of assembly language instructions.
30530
30531 The examples in this chapter will illustrate several of the forms
30532 for invoking @code{Asm}; a complete specification of the syntax
30533 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30534 Manual}.
30535
30536 Under the standard GNAT conventions, the @code{Nothing} procedure
30537 should be in a file named @file{nothing.adb}.
30538 You can build the executable in the usual way:
30539 @smallexample
30540 gnatmake nothing
30541 @end smallexample
30542 However, the interesting aspect of this example is not its run-time behavior
30543 but rather the generated assembly code.
30544 To see this output, invoke the compiler as follows:
30545 @smallexample
30546    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30547 @end smallexample
30548 where the options are:
30549
30550 @table @code
30551 @item -c
30552 compile only (no bind or link)
30553 @item -S
30554 generate assembler listing
30555 @item -fomit-frame-pointer
30556 do not set up separate stack frames
30557 @item -gnatp
30558 do not add runtime checks
30559 @end table
30560
30561 This gives a human-readable assembler version of the code. The resulting
30562 file will have the same name as the Ada source file, but with a @code{.s}
30563 extension. In our example, the file @file{nothing.s} has the following
30564 contents:
30565
30566 @smallexample
30567 @group
30568 .file "nothing.adb"
30569 gcc2_compiled.:
30570 ___gnu_compiled_ada:
30571 .text
30572    .align 4
30573 .globl __ada_nothing
30574 __ada_nothing:
30575 #APP
30576    nop
30577 #NO_APP
30578    jmp L1
30579    .align 2,0x90
30580 L1:
30581    ret
30582 @end group
30583 @end smallexample
30584
30585 The assembly code you included is clearly indicated by
30586 the compiler, between the @code{#APP} and @code{#NO_APP}
30587 delimiters. The character before the 'APP' and 'NOAPP'
30588 can differ on different targets. For example, GNU/Linux uses '#APP' while
30589 on NT you will see '/APP'.
30590
30591 If you make a mistake in your assembler code (such as using the
30592 wrong size modifier, or using a wrong operand for the instruction) GNAT
30593 will report this error in a temporary file, which will be deleted when
30594 the compilation is finished.  Generating an assembler file will help
30595 in such cases, since you can assemble this file separately using the
30596 @emph{as} assembler that comes with gcc.
30597
30598 Assembling the file using the command
30599
30600 @smallexample
30601 as @file{nothing.s}
30602 @end smallexample
30603 @noindent
30604 will give you error messages whose lines correspond to the assembler
30605 input file, so you can easily find and correct any mistakes you made.
30606 If there are no errors, @emph{as} will generate an object file
30607 @file{nothing.out}.
30608
30609 @c ---------------------------------------------------------------------------
30610 @node Output Variables in Inline Assembler
30611 @section Output Variables in Inline Assembler
30612
30613 @noindent
30614 The examples in this section, showing how to access the processor flags,
30615 illustrate how to specify the destination operands for assembly language
30616 statements.
30617
30618 @smallexample @c ada
30619 @group
30620 with Interfaces; use Interfaces;
30621 with Ada.Text_IO; use Ada.Text_IO;
30622 with System.Machine_Code; use System.Machine_Code;
30623 procedure Get_Flags is
30624    Flags : Unsigned_32;
30625    use ASCII;
30626 begin
30627    Asm ("pushfl"          & LF & HT & -- push flags on stack
30628         "popl %%eax"      & LF & HT & -- load eax with flags
30629         "movl %%eax, %0",             -- store flags in variable
30630         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30631    Put_Line ("Flags register:" & Flags'Img);
30632 end Get_Flags;
30633 @end group
30634 @end smallexample
30635
30636 In order to have a nicely aligned assembly listing, we have separated
30637 multiple assembler statements in the Asm template string with linefeed
30638 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30639 The resulting section of the assembly output file is:
30640
30641 @smallexample
30642 @group
30643 #APP
30644    pushfl
30645    popl %eax
30646    movl %eax, -40(%ebp)
30647 #NO_APP
30648 @end group
30649 @end smallexample
30650
30651 It would have been legal to write the Asm invocation as:
30652
30653 @smallexample
30654 Asm ("pushfl popl %%eax movl %%eax, %0")
30655 @end smallexample
30656
30657 but in the generated assembler file, this would come out as:
30658
30659 @smallexample
30660 #APP
30661    pushfl popl %eax movl %eax, -40(%ebp)
30662 #NO_APP
30663 @end smallexample
30664
30665 which is not so convenient for the human reader.
30666
30667 We use Ada comments
30668 at the end of each line to explain what the assembler instructions
30669 actually do.  This is a useful convention.
30670
30671 When writing Inline Assembler instructions, you need to precede each register
30672 and variable name with a percent sign.  Since the assembler already requires
30673 a percent sign at the beginning of a register name, you need two consecutive
30674 percent signs for such names in the Asm template string, thus @code{%%eax}.
30675 In the generated assembly code, one of the percent signs will be stripped off.
30676
30677 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30678 variables: operands you later define using @code{Input} or @code{Output}
30679 parameters to @code{Asm}.
30680 An output variable is illustrated in
30681 the third statement in the Asm template string:
30682 @smallexample
30683 movl %%eax, %0
30684 @end smallexample
30685 The intent is to store the contents of the eax register in a variable that can
30686 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30687 necessarily work, since the compiler might optimize by using a register
30688 to hold Flags, and the expansion of the @code{movl} instruction would not be
30689 aware of this optimization.  The solution is not to store the result directly
30690 but rather to advise the compiler to choose the correct operand form;
30691 that is the purpose of the @code{%0} output variable.
30692
30693 Information about the output variable is supplied in the @code{Outputs}
30694 parameter to @code{Asm}:
30695 @smallexample
30696 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30697 @end smallexample
30698
30699 The output is defined by the @code{Asm_Output} attribute of the target type;
30700 the general format is
30701 @smallexample
30702 Type'Asm_Output (constraint_string, variable_name)
30703 @end smallexample
30704
30705 The constraint string directs the compiler how
30706 to store/access the associated variable.  In the example
30707 @smallexample
30708 Unsigned_32'Asm_Output ("=m", Flags);
30709 @end smallexample
30710 the @code{"m"} (memory) constraint tells the compiler that the variable
30711 @code{Flags} should be stored in a memory variable, thus preventing
30712 the optimizer from keeping it in a register.  In contrast,
30713 @smallexample
30714 Unsigned_32'Asm_Output ("=r", Flags);
30715 @end smallexample
30716 uses the @code{"r"} (register) constraint, telling the compiler to
30717 store the variable in a register.
30718
30719 If the constraint is preceded by the equal character (@strong{=}), it tells
30720 the compiler that the variable will be used to store data into it.
30721
30722 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30723 allowing the optimizer to choose whatever it deems best.
30724
30725 There are a fairly large number of constraints, but the ones that are
30726 most useful (for the Intel x86 processor) are the following:
30727
30728 @table @code
30729 @item =
30730 output constraint
30731 @item g
30732 global (i.e.@: can be stored anywhere)
30733 @item m
30734 in memory
30735 @item I
30736 a constant
30737 @item a
30738 use eax
30739 @item b
30740 use ebx
30741 @item c
30742 use ecx
30743 @item d
30744 use edx
30745 @item S
30746 use esi
30747 @item D
30748 use edi
30749 @item r
30750 use one of eax, ebx, ecx or edx
30751 @item q
30752 use one of eax, ebx, ecx, edx, esi or edi
30753 @end table
30754
30755 The full set of constraints is described in the gcc and @emph{as}
30756 documentation; note that it is possible to combine certain constraints
30757 in one constraint string.
30758
30759 You specify the association of an output variable with an assembler operand
30760 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30761 integer.  Thus in
30762 @smallexample @c ada
30763 @group
30764 Asm ("pushfl"          & LF & HT & -- push flags on stack
30765      "popl %%eax"      & LF & HT & -- load eax with flags
30766      "movl %%eax, %0",             -- store flags in variable
30767      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30768 @end group
30769 @end smallexample
30770 @noindent
30771 @code{%0} will be replaced in the expanded code by the appropriate operand,
30772 whatever
30773 the compiler decided for the @code{Flags} variable.
30774
30775 In general, you may have any number of output variables:
30776 @itemize @bullet
30777 @item
30778 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30779 @item
30780 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30781 of @code{Asm_Output} attributes
30782 @end itemize
30783
30784 For example:
30785 @smallexample @c ada
30786 @group
30787 Asm ("movl %%eax, %0" & LF & HT &
30788      "movl %%ebx, %1" & LF & HT &
30789      "movl %%ecx, %2",
30790      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30791                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30792                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30793 @end group
30794 @end smallexample
30795 @noindent
30796 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30797 in the Ada program.
30798
30799 As a variation on the @code{Get_Flags} example, we can use the constraints
30800 string to direct the compiler to store the eax register into the @code{Flags}
30801 variable, instead of including the store instruction explicitly in the
30802 @code{Asm} template string:
30803
30804 @smallexample @c ada
30805 @group
30806 with Interfaces; use Interfaces;
30807 with Ada.Text_IO; use Ada.Text_IO;
30808 with System.Machine_Code; use System.Machine_Code;
30809 procedure Get_Flags_2 is
30810    Flags : Unsigned_32;
30811    use ASCII;
30812 begin
30813    Asm ("pushfl"      & LF & HT & -- push flags on stack
30814         "popl %%eax",             -- save flags in eax
30815         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30816    Put_Line ("Flags register:" & Flags'Img);
30817 end Get_Flags_2;
30818 @end group
30819 @end smallexample
30820
30821 @noindent
30822 The @code{"a"} constraint tells the compiler that the @code{Flags}
30823 variable will come from the eax register. Here is the resulting code:
30824
30825 @smallexample
30826 @group
30827 #APP
30828    pushfl
30829    popl %eax
30830 #NO_APP
30831    movl %eax,-40(%ebp)
30832 @end group
30833 @end smallexample
30834
30835 @noindent
30836 The compiler generated the store of eax into Flags after
30837 expanding the assembler code.
30838
30839 Actually, there was no need to pop the flags into the eax register;
30840 more simply, we could just pop the flags directly into the program variable:
30841
30842 @smallexample @c ada
30843 @group
30844 with Interfaces; use Interfaces;
30845 with Ada.Text_IO; use Ada.Text_IO;
30846 with System.Machine_Code; use System.Machine_Code;
30847 procedure Get_Flags_3 is
30848    Flags : Unsigned_32;
30849    use ASCII;
30850 begin
30851    Asm ("pushfl"  & LF & HT & -- push flags on stack
30852         "pop %0",             -- save flags in Flags
30853         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30854    Put_Line ("Flags register:" & Flags'Img);
30855 end Get_Flags_3;
30856 @end group
30857 @end smallexample
30858
30859 @c ---------------------------------------------------------------------------
30860 @node Input Variables in Inline Assembler
30861 @section Input Variables in Inline Assembler
30862
30863 @noindent
30864 The example in this section illustrates how to specify the source operands
30865 for assembly language statements.
30866 The program simply increments its input value by 1:
30867
30868 @smallexample @c ada
30869 @group
30870 with Interfaces; use Interfaces;
30871 with Ada.Text_IO; use Ada.Text_IO;
30872 with System.Machine_Code; use System.Machine_Code;
30873 procedure Increment is
30874
30875    function Incr (Value : Unsigned_32) return Unsigned_32 is
30876       Result : Unsigned_32;
30877    begin
30878       Asm ("incl %0",
30879            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30880            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30881       return Result;
30882    end Incr;
30883
30884    Value : Unsigned_32;
30885
30886 begin
30887    Value := 5;
30888    Put_Line ("Value before is" & Value'Img);
30889    Value := Incr (Value);
30890    Put_Line ("Value after is" & Value'Img);
30891 end Increment;
30892 @end group
30893 @end smallexample
30894
30895 The @code{Outputs} parameter to @code{Asm} specifies
30896 that the result will be in the eax register and that it is to be stored
30897 in the @code{Result} variable.
30898
30899 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30900 but with an @code{Asm_Input} attribute.
30901 The @code{"="} constraint, indicating an output value, is not present.
30902
30903 You can have multiple input variables, in the same way that you can have more
30904 than one output variable.
30905
30906 The parameter count (%0, %1) etc, now starts at the first input
30907 statement, and continues with the output statements.
30908 When both parameters use the same variable, the
30909 compiler will treat them as the same %n operand, which is the case here.
30910
30911 Just as the @code{Outputs} parameter causes the register to be stored into the
30912 target variable after execution of the assembler statements, so does the
30913 @code{Inputs} parameter cause its variable to be loaded into the register
30914 before execution of the assembler statements.
30915
30916 Thus the effect of the @code{Asm} invocation is:
30917 @enumerate
30918 @item load the 32-bit value of @code{Value} into eax
30919 @item execute the @code{incl %eax} instruction
30920 @item store the contents of eax into the @code{Result} variable
30921 @end enumerate
30922
30923 The resulting assembler file (with @option{-O2} optimization) contains:
30924 @smallexample
30925 @group
30926 _increment__incr.1:
30927    subl $4,%esp
30928    movl 8(%esp),%eax
30929 #APP
30930    incl %eax
30931 #NO_APP
30932    movl %eax,%edx
30933    movl %ecx,(%esp)
30934    addl $4,%esp
30935    ret
30936 @end group
30937 @end smallexample
30938
30939 @c ---------------------------------------------------------------------------
30940 @node Inlining Inline Assembler Code
30941 @section Inlining Inline Assembler Code
30942
30943 @noindent
30944 For a short subprogram such as the @code{Incr} function in the previous
30945 section, the overhead of the call and return (creating / deleting the stack
30946 frame) can be significant, compared to the amount of code in the subprogram
30947 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30948 which directs the compiler to expand invocations of the subprogram at the
30949 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30950 Here is the resulting program:
30951
30952 @smallexample @c ada
30953 @group
30954 with Interfaces; use Interfaces;
30955 with Ada.Text_IO; use Ada.Text_IO;
30956 with System.Machine_Code; use System.Machine_Code;
30957 procedure Increment_2 is
30958
30959    function Incr (Value : Unsigned_32) return Unsigned_32 is
30960       Result : Unsigned_32;
30961    begin
30962       Asm ("incl %0",
30963            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30964            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30965       return Result;
30966    end Incr;
30967    pragma Inline (Increment);
30968
30969    Value : Unsigned_32;
30970
30971 begin
30972    Value := 5;
30973    Put_Line ("Value before is" & Value'Img);
30974    Value := Increment (Value);
30975    Put_Line ("Value after is" & Value'Img);
30976 end Increment_2;
30977 @end group
30978 @end smallexample
30979
30980 Compile the program with both optimization (@option{-O2}) and inlining
30981 (@option{-gnatn}) enabled.
30982
30983 The @code{Incr} function is still compiled as usual, but at the
30984 point in @code{Increment} where our function used to be called:
30985
30986 @smallexample
30987 @group
30988 pushl %edi
30989 call _increment__incr.1
30990 @end group
30991 @end smallexample
30992
30993 @noindent
30994 the code for the function body directly appears:
30995
30996 @smallexample
30997 @group
30998 movl %esi,%eax
30999 #APP
31000    incl %eax
31001 #NO_APP
31002    movl %eax,%edx
31003 @end group
31004 @end smallexample
31005
31006 @noindent
31007 thus saving the overhead of stack frame setup and an out-of-line call.
31008
31009 @c ---------------------------------------------------------------------------
31010 @node Other Asm Functionality
31011 @section Other @code{Asm} Functionality
31012
31013 @noindent
31014 This section describes two important parameters to the @code{Asm}
31015 procedure: @code{Clobber}, which identifies register usage;
31016 and @code{Volatile}, which inhibits unwanted optimizations.
31017
31018 @menu
31019 * The Clobber Parameter::
31020 * The Volatile Parameter::
31021 @end menu
31022
31023 @c ---------------------------------------------------------------------------
31024 @node The Clobber Parameter
31025 @subsection The @code{Clobber} Parameter
31026
31027 @noindent
31028 One of the dangers of intermixing assembly language and a compiled language
31029 such as Ada is that the compiler needs to be aware of which registers are
31030 being used by the assembly code.  In some cases, such as the earlier examples,
31031 the constraint string is sufficient to indicate register usage (e.g.,
31032 @code{"a"} for
31033 the eax register).  But more generally, the compiler needs an explicit
31034 identification of the registers that are used by the Inline Assembly
31035 statements.
31036
31037 Using a register that the compiler doesn't know about
31038 could be a side effect of an instruction (like @code{mull}
31039 storing its result in both eax and edx).
31040 It can also arise from explicit register usage in your
31041 assembly code; for example:
31042 @smallexample
31043 @group
31044 Asm ("movl %0, %%ebx" & LF & HT &
31045      "movl %%ebx, %1",
31046      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31047      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
31048 @end group
31049 @end smallexample
31050 @noindent
31051 where the compiler (since it does not analyze the @code{Asm} template string)
31052 does not know you are using the ebx register.
31053
31054 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
31055 to identify the registers that will be used by your assembly code:
31056
31057 @smallexample
31058 @group
31059 Asm ("movl %0, %%ebx" & LF & HT &
31060      "movl %%ebx, %1",
31061      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31062      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
31063      Clobber => "ebx");
31064 @end group
31065 @end smallexample
31066
31067 The Clobber parameter is a static string expression specifying the
31068 register(s) you are using.  Note that register names are @emph{not} prefixed
31069 by a percent sign. Also, if more than one register is used then their names
31070 are separated by commas; e.g., @code{"eax, ebx"}
31071
31072 The @code{Clobber} parameter has several additional uses:
31073 @enumerate
31074 @item Use ``register'' name @code{cc} to indicate that flags might have changed
31075 @item Use ``register'' name @code{memory} if you changed a memory location
31076 @end enumerate
31077
31078 @c ---------------------------------------------------------------------------
31079 @node The Volatile Parameter
31080 @subsection The @code{Volatile} Parameter
31081 @cindex Volatile parameter
31082
31083 @noindent
31084 Compiler optimizations in the presence of Inline Assembler may sometimes have
31085 unwanted effects.  For example, when an @code{Asm} invocation with an input
31086 variable is inside a loop, the compiler might move the loading of the input
31087 variable outside the loop, regarding it as a one-time initialization.
31088
31089 If this effect is not desired, you can disable such optimizations by setting
31090 the @code{Volatile} parameter to @code{True}; for example:
31091
31092 @smallexample @c ada
31093 @group
31094 Asm ("movl %0, %%ebx" & LF & HT &
31095      "movl %%ebx, %1",
31096      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
31097      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
31098      Clobber  => "ebx",
31099      Volatile => True);
31100 @end group
31101 @end smallexample
31102
31103 By default, @code{Volatile} is set to @code{False} unless there is no
31104 @code{Outputs} parameter.
31105
31106 Although setting @code{Volatile} to @code{True} prevents unwanted
31107 optimizations, it will also disable other optimizations that might be
31108 important for efficiency. In general, you should set @code{Volatile}
31109 to @code{True} only if the compiler's optimizations have created
31110 problems.
31111 @c END OF INLINE ASSEMBLER CHAPTER
31112 @c ===============================
31113
31114 @c ***********************************
31115 @c * Compatibility and Porting Guide *
31116 @c ***********************************
31117 @node Compatibility and Porting Guide
31118 @appendix Compatibility and Porting Guide
31119
31120 @noindent
31121 This chapter describes the compatibility issues that may arise between
31122 GNAT and other Ada compilation systems (including those for Ada 83),
31123 and shows how GNAT can expedite porting
31124 applications developed in other Ada environments.
31125
31126 @menu
31127 * Compatibility with Ada 83::
31128 * Compatibility between Ada 95 and Ada 2005::
31129 * Implementation-dependent characteristics::
31130 * Compatibility with Other Ada Systems::
31131 * Representation Clauses::
31132 @ifclear vms
31133 @c Brief section is only in non-VMS version
31134 @c Full chapter is in VMS version
31135 * Compatibility with HP Ada 83::
31136 @end ifclear
31137 @ifset vms
31138 * Transitioning to 64-Bit GNAT for OpenVMS::
31139 @end ifset
31140 @end menu
31141
31142 @node Compatibility with Ada 83
31143 @section Compatibility with Ada 83
31144 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
31145
31146 @noindent
31147 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
31148 particular, the design intention was that the difficulties associated
31149 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
31150 that occur when moving from one Ada 83 system to another.
31151
31152 However, there are a number of points at which there are minor
31153 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
31154 full details of these issues,
31155 and should be consulted for a complete treatment.
31156 In practice the
31157 following subsections treat the most likely issues to be encountered.
31158
31159 @menu
31160 * Legal Ada 83 programs that are illegal in Ada 95::
31161 * More deterministic semantics::
31162 * Changed semantics::
31163 * Other language compatibility issues::
31164 @end menu
31165
31166 @node Legal Ada 83 programs that are illegal in Ada 95
31167 @subsection Legal Ada 83 programs that are illegal in Ada 95
31168
31169 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
31170 Ada 95 and thus also in Ada 2005:
31171
31172 @table @emph
31173 @item Character literals
31174 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
31175 @code{Wide_Character} as a new predefined character type, some uses of
31176 character literals that were legal in Ada 83 are illegal in Ada 95.
31177 For example:
31178 @smallexample @c ada
31179    for Char in 'A' .. 'Z' loop @dots{} end loop;
31180 @end smallexample
31181
31182 @noindent
31183 The problem is that @code{'A'} and @code{'Z'} could be from either
31184 @code{Character} or @code{Wide_Character}.  The simplest correction
31185 is to make the type explicit; e.g.:
31186 @smallexample @c ada
31187    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
31188 @end smallexample
31189
31190 @item New reserved words
31191 The identifiers @code{abstract}, @code{aliased}, @code{protected},
31192 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
31193 Existing Ada 83 code using any of these identifiers must be edited to
31194 use some alternative name.
31195
31196 @item Freezing rules
31197 The rules in Ada 95 are slightly different with regard to the point at
31198 which entities are frozen, and representation pragmas and clauses are
31199 not permitted past the freeze point.  This shows up most typically in
31200 the form of an error message complaining that a representation item
31201 appears too late, and the appropriate corrective action is to move
31202 the item nearer to the declaration of the entity to which it refers.
31203
31204 A particular case is that representation pragmas
31205 @ifset vms
31206 (including the
31207 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
31208 @end ifset
31209 cannot be applied to a subprogram body.  If necessary, a separate subprogram
31210 declaration must be introduced to which the pragma can be applied.
31211
31212 @item Optional bodies for library packages
31213 In Ada 83, a package that did not require a package body was nevertheless
31214 allowed to have one.  This lead to certain surprises in compiling large
31215 systems (situations in which the body could be unexpectedly ignored by the
31216 binder).  In Ada 95, if a package does not require a body then it is not
31217 permitted to have a body.  To fix this problem, simply remove a redundant
31218 body if it is empty, or, if it is non-empty, introduce a dummy declaration
31219 into the spec that makes the body required.  One approach is to add a private
31220 part to the package declaration (if necessary), and define a parameterless
31221 procedure called @code{Requires_Body}, which must then be given a dummy
31222 procedure body in the package body, which then becomes required.
31223 Another approach (assuming that this does not introduce elaboration
31224 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
31225 since one effect of this pragma is to require the presence of a package body.
31226
31227 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
31228 In Ada 95, the exception @code{Numeric_Error} is a renaming of
31229 @code{Constraint_Error}.
31230 This means that it is illegal to have separate exception handlers for
31231 the two exceptions.  The fix is simply to remove the handler for the
31232 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
31233 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
31234
31235 @item Indefinite subtypes in generics
31236 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
31237 as the actual for a generic formal private type, but then the instantiation
31238 would be illegal if there were any instances of declarations of variables
31239 of this type in the generic body.  In Ada 95, to avoid this clear violation
31240 of the methodological principle known as the ``contract model'',
31241 the generic declaration explicitly indicates whether
31242 or not such instantiations are permitted.  If a generic formal parameter
31243 has explicit unknown discriminants, indicated by using @code{(<>)} after the
31244 type name, then it can be instantiated with indefinite types, but no
31245 stand-alone variables can be declared of this type.  Any attempt to declare
31246 such a variable will result in an illegality at the time the generic is
31247 declared.  If the @code{(<>)} notation is not used, then it is illegal
31248 to instantiate the generic with an indefinite type.
31249 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
31250 It will show up as a compile time error, and
31251 the fix is usually simply to add the @code{(<>)} to the generic declaration.
31252 @end table
31253
31254 @node More deterministic semantics
31255 @subsection More deterministic semantics
31256
31257 @table @emph
31258 @item Conversions
31259 Conversions from real types to integer types round away from 0.  In Ada 83
31260 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
31261 implementation freedom was intended to support unbiased rounding in
31262 statistical applications, but in practice it interfered with portability.
31263 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
31264 is required.  Numeric code may be affected by this change in semantics.
31265 Note, though, that this issue is no worse than already existed in Ada 83
31266 when porting code from one vendor to another.
31267
31268 @item Tasking
31269 The Real-Time Annex introduces a set of policies that define the behavior of
31270 features that were implementation dependent in Ada 83, such as the order in
31271 which open select branches are executed.
31272 @end table
31273
31274 @node Changed semantics
31275 @subsection Changed semantics
31276
31277 @noindent
31278 The worst kind of incompatibility is one where a program that is legal in
31279 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31280 possible in Ada 83.  Fortunately this is extremely rare, but the one
31281 situation that you should be alert to is the change in the predefined type
31282 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31283
31284 @table @emph
31285 @item Range of type @code{Character}
31286 The range of @code{Standard.Character} is now the full 256 characters
31287 of Latin-1, whereas in most Ada 83 implementations it was restricted
31288 to 128 characters. Although some of the effects of
31289 this change will be manifest in compile-time rejection of legal
31290 Ada 83 programs it is possible for a working Ada 83 program to have
31291 a different effect in Ada 95, one that was not permitted in Ada 83.
31292 As an example, the expression
31293 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31294 delivers @code{255} as its value.
31295 In general, you should look at the logic of any
31296 character-processing Ada 83 program and see whether it needs to be adapted
31297 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31298 character handling package that may be relevant if code needs to be adapted
31299 to account for the additional Latin-1 elements.
31300 The desirable fix is to
31301 modify the program to accommodate the full character set, but in some cases
31302 it may be convenient to define a subtype or derived type of Character that
31303 covers only the restricted range.
31304 @cindex Latin-1
31305 @end table
31306
31307 @node Other language compatibility issues
31308 @subsection Other language compatibility issues
31309
31310 @table @emph
31311 @item @option{-gnat83} switch
31312 All implementations of GNAT provide a switch that causes GNAT to operate
31313 in Ada 83 mode.  In this mode, some but not all compatibility problems
31314 of the type described above are handled automatically.  For example, the
31315 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31316 as identifiers as in Ada 83.
31317 However,
31318 in practice, it is usually advisable to make the necessary modifications
31319 to the program to remove the need for using this switch.
31320 See @ref{Compiling Different Versions of Ada}.
31321
31322 @item Support for removed Ada 83 pragmas and attributes
31323 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31324 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31325 compilers are allowed, but not required, to implement these missing
31326 elements.  In contrast with some other compilers, GNAT implements all
31327 such pragmas and attributes, eliminating this compatibility concern.  These
31328 include @code{pragma Interface} and the floating point type attributes
31329 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31330 @end table
31331
31332
31333 @node Compatibility between Ada 95 and Ada 2005
31334 @section Compatibility between Ada 95 and Ada 2005
31335 @cindex Compatibility between Ada 95 and Ada 2005
31336
31337 @noindent
31338 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31339 a number of incompatibilities. Several are enumerated below;
31340 for a complete description please see the
31341 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31342 @cite{Rationale for Ada 2005}.
31343
31344 @table @emph
31345 @item New reserved words.
31346 The words @code{interface}, @code{overriding} and @code{synchronized} are
31347 reserved in Ada 2005.
31348 A pre-Ada 2005 program that uses any of these as an identifier will be
31349 illegal.
31350
31351 @item New declarations in predefined packages.
31352 A number of packages in the predefined environment contain new declarations:
31353 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31354 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31355 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31356 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31357 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31358 If an Ada 95 program does a @code{with} and @code{use} of any of these
31359 packages, the new declarations may cause name clashes.
31360
31361 @item Access parameters.
31362 A nondispatching subprogram with an access parameter cannot be renamed
31363 as a dispatching operation.  This was permitted in Ada 95.
31364
31365 @item Access types, discriminants, and constraints.
31366 Rule changes in this area have led to some incompatibilities; for example,
31367 constrained subtypes of some access types are not permitted in Ada 2005.
31368
31369 @item Aggregates for limited types.
31370 The allowance of aggregates for limited types in Ada 2005 raises the
31371 possibility of ambiguities in legal Ada 95 programs, since additional types
31372 now need to be considered in expression resolution.
31373
31374 @item Fixed-point multiplication and division.
31375 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31376 were legal in Ada 95 and invoked the predefined versions of these operations,
31377 are now ambiguous.
31378 The ambiguity may be resolved either by applying a type conversion to the
31379 expression, or by explicitly invoking the operation from package
31380 @code{Standard}.
31381
31382 @item Return-by-reference types.
31383 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31384 can declare a function returning a value from an anonymous access type.
31385 @end table
31386
31387
31388 @node Implementation-dependent characteristics
31389 @section Implementation-dependent characteristics
31390 @noindent
31391 Although the Ada language defines the semantics of each construct as
31392 precisely as practical, in some situations (for example for reasons of
31393 efficiency, or where the effect is heavily dependent on the host or target
31394 platform) the implementation is allowed some freedom.  In porting Ada 83
31395 code to GNAT, you need to be aware of whether / how the existing code
31396 exercised such implementation dependencies.  Such characteristics fall into
31397 several categories, and GNAT offers specific support in assisting the
31398 transition from certain Ada 83 compilers.
31399
31400 @menu
31401 * Implementation-defined pragmas::
31402 * Implementation-defined attributes::
31403 * Libraries::
31404 * Elaboration order::
31405 * Target-specific aspects::
31406 @end menu
31407
31408 @node Implementation-defined pragmas
31409 @subsection Implementation-defined pragmas
31410
31411 @noindent
31412 Ada compilers are allowed to supplement the language-defined pragmas, and
31413 these are a potential source of non-portability.  All GNAT-defined pragmas
31414 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31415 Reference Manual}, and these include several that are specifically
31416 intended to correspond to other vendors' Ada 83 pragmas.
31417 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31418 For compatibility with HP Ada 83, GNAT supplies the pragmas
31419 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31420 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31421 and @code{Volatile}.
31422 Other relevant pragmas include @code{External} and @code{Link_With}.
31423 Some vendor-specific
31424 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31425 recognized, thus
31426 avoiding compiler rejection of units that contain such pragmas; they are not
31427 relevant in a GNAT context and hence are not otherwise implemented.
31428
31429 @node Implementation-defined attributes
31430 @subsection Implementation-defined attributes
31431
31432 Analogous to pragmas, the set of attributes may be extended by an
31433 implementation.  All GNAT-defined attributes are described in
31434 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31435 Manual}, and these include several that are specifically intended
31436 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31437 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31438 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31439 @code{Type_Class}.
31440
31441 @node Libraries
31442 @subsection Libraries
31443 @noindent
31444 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31445 code uses vendor-specific libraries then there are several ways to manage
31446 this in Ada 95 or Ada 2005:
31447 @enumerate
31448 @item
31449 If the source code for the libraries (specs and bodies) are
31450 available, then the libraries can be migrated in the same way as the
31451 application.
31452 @item
31453 If the source code for the specs but not the bodies are
31454 available, then you can reimplement the bodies.
31455 @item
31456 Some features introduced by Ada 95 obviate the need for library support.  For
31457 example most Ada 83 vendors supplied a package for unsigned integers.  The
31458 Ada 95 modular type feature is the preferred way to handle this need, so
31459 instead of migrating or reimplementing the unsigned integer package it may
31460 be preferable to retrofit the application using modular types.
31461 @end enumerate
31462
31463 @node Elaboration order
31464 @subsection Elaboration order
31465 @noindent
31466 The implementation can choose any elaboration order consistent with the unit
31467 dependency relationship.  This freedom means that some orders can result in
31468 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31469 to invoke a subprogram its body has been elaborated, or to instantiate a
31470 generic before the generic body has been elaborated.  By default GNAT
31471 attempts to choose a safe order (one that will not encounter access before
31472 elaboration problems) by implicitly inserting @code{Elaborate} or
31473 @code{Elaborate_All} pragmas where
31474 needed.  However, this can lead to the creation of elaboration circularities
31475 and a resulting rejection of the program by gnatbind.  This issue is
31476 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31477 In brief, there are several
31478 ways to deal with this situation:
31479
31480 @itemize @bullet
31481 @item
31482 Modify the program to eliminate the circularities, e.g.@: by moving
31483 elaboration-time code into explicitly-invoked procedures
31484 @item
31485 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31486 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31487 @code{Elaborate_All}
31488 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31489 (by selectively suppressing elaboration checks via pragma
31490 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31491 @end itemize
31492
31493 @node Target-specific aspects
31494 @subsection Target-specific aspects
31495 @noindent
31496 Low-level applications need to deal with machine addresses, data
31497 representations, interfacing with assembler code, and similar issues.  If
31498 such an Ada 83 application is being ported to different target hardware (for
31499 example where the byte endianness has changed) then you will need to
31500 carefully examine the program logic; the porting effort will heavily depend
31501 on the robustness of the original design.  Moreover, Ada 95 (and thus
31502 Ada 2005) are sometimes
31503 incompatible with typical Ada 83 compiler practices regarding implicit
31504 packing, the meaning of the Size attribute, and the size of access values.
31505 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31506
31507 @node Compatibility with Other Ada Systems
31508 @section Compatibility with Other Ada Systems
31509
31510 @noindent
31511 If programs avoid the use of implementation dependent and
31512 implementation defined features, as documented in the @cite{Ada
31513 Reference Manual}, there should be a high degree of portability between
31514 GNAT and other Ada systems.  The following are specific items which
31515 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31516 compilers, but do not affect porting code to GNAT@.
31517 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31518 the following issues may or may not arise for Ada 2005 programs
31519 when other compilers appear.)
31520
31521 @table @emph
31522 @item Ada 83 Pragmas and Attributes
31523 Ada 95 compilers are allowed, but not required, to implement the missing
31524 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31525 GNAT implements all such pragmas and attributes, eliminating this as
31526 a compatibility concern, but some other Ada 95 compilers reject these
31527 pragmas and attributes.
31528
31529 @item Specialized Needs Annexes
31530 GNAT implements the full set of special needs annexes.  At the
31531 current time, it is the only Ada 95 compiler to do so.  This means that
31532 programs making use of these features may not be portable to other Ada
31533 95 compilation systems.
31534
31535 @item Representation Clauses
31536 Some other Ada 95 compilers implement only the minimal set of
31537 representation clauses required by the Ada 95 reference manual.  GNAT goes
31538 far beyond this minimal set, as described in the next section.
31539 @end table
31540
31541 @node Representation Clauses
31542 @section Representation Clauses
31543
31544 @noindent
31545 The Ada 83 reference manual was quite vague in describing both the minimal
31546 required implementation of representation clauses, and also their precise
31547 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31548 minimal set of capabilities required is still quite limited.
31549
31550 GNAT implements the full required set of capabilities in
31551 Ada 95 and Ada 2005, but also goes much further, and in particular
31552 an effort has been made to be compatible with existing Ada 83 usage to the
31553 greatest extent possible.
31554
31555 A few cases exist in which Ada 83 compiler behavior is incompatible with
31556 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31557 intentional or accidental dependence on specific implementation dependent
31558 characteristics of these Ada 83 compilers.  The following is a list of
31559 the cases most likely to arise in existing Ada 83 code.
31560
31561 @table @emph
31562 @item Implicit Packing
31563 Some Ada 83 compilers allowed a Size specification to cause implicit
31564 packing of an array or record.  This could cause expensive implicit
31565 conversions for change of representation in the presence of derived
31566 types, and the Ada design intends to avoid this possibility.
31567 Subsequent AI's were issued to make it clear that such implicit
31568 change of representation in response to a Size clause is inadvisable,
31569 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31570 Reference Manuals as implementation advice that is followed by GNAT@.
31571 The problem will show up as an error
31572 message rejecting the size clause.  The fix is simply to provide
31573 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31574 a Component_Size clause.
31575
31576 @item Meaning of Size Attribute
31577 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31578 the minimal number of bits required to hold values of the type.  For example,
31579 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31580 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31581 some 32 in this situation.  This problem will usually show up as a compile
31582 time error, but not always.  It is a good idea to check all uses of the
31583 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31584 Object_Size can provide a useful way of duplicating the behavior of
31585 some Ada 83 compiler systems.
31586
31587 @item Size of Access Types
31588 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31589 and that therefore it will be the same size as a System.Address value.  This
31590 assumption is true for GNAT in most cases with one exception.  For the case of
31591 a pointer to an unconstrained array type (where the bounds may vary from one
31592 value of the access type to another), the default is to use a ``fat pointer'',
31593 which is represented as two separate pointers, one to the bounds, and one to
31594 the array.  This representation has a number of advantages, including improved
31595 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31596 code which makes the assumption that, for example, pointers fit in 32 bits on
31597 a machine with 32-bit addressing.
31598
31599 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31600 access types in this case (where the designated type is an unconstrained array
31601 type).  These thin pointers are indeed the same size as a System.Address value.
31602 To specify a thin pointer, use a size clause for the type, for example:
31603
31604 @smallexample @c ada
31605 type X is access all String;
31606 for X'Size use Standard'Address_Size;
31607 @end smallexample
31608
31609 @noindent
31610 which will cause the type X to be represented using a single pointer.
31611 When using this representation, the bounds are right behind the array.
31612 This representation is slightly less efficient, and does not allow quite
31613 such flexibility in the use of foreign pointers or in using the
31614 Unrestricted_Access attribute to create pointers to non-aliased objects.
31615 But for any standard portable use of the access type it will work in
31616 a functionally correct manner and allow porting of existing code.
31617 Note that another way of forcing a thin pointer representation
31618 is to use a component size clause for the element size in an array,
31619 or a record representation clause for an access field in a record.
31620 @end table
31621
31622 @ifclear vms
31623 @c This brief section is only in the non-VMS version
31624 @c The complete chapter on HP Ada is in the VMS version
31625 @node Compatibility with HP Ada 83
31626 @section Compatibility with HP Ada 83
31627
31628 @noindent
31629 The VMS version of GNAT fully implements all the pragmas and attributes
31630 provided by HP Ada 83, as well as providing the standard HP Ada 83
31631 libraries, including Starlet.  In addition, data layouts and parameter
31632 passing conventions are highly compatible.  This means that porting
31633 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31634 most other porting efforts.  The following are some of the most
31635 significant differences between GNAT and HP Ada 83.
31636
31637 @table @emph
31638 @item Default floating-point representation
31639 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31640 it is VMS format.  GNAT does implement the necessary pragmas
31641 (Long_Float, Float_Representation) for changing this default.
31642
31643 @item System
31644 The package System in GNAT exactly corresponds to the definition in the
31645 Ada 95 reference manual, which means that it excludes many of the
31646 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31647 that contains the additional definitions, and a special pragma,
31648 Extend_System allows this package to be treated transparently as an
31649 extension of package System.
31650
31651 @item To_Address
31652 The definitions provided by Aux_DEC are exactly compatible with those
31653 in the HP Ada 83 version of System, with one exception.
31654 HP Ada provides the following declarations:
31655
31656 @smallexample @c ada
31657 TO_ADDRESS (INTEGER)
31658 TO_ADDRESS (UNSIGNED_LONGWORD)
31659 TO_ADDRESS (@i{universal_integer})
31660 @end smallexample
31661
31662 @noindent
31663 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31664 an extension to Ada 83 not strictly compatible with the reference manual.
31665 In GNAT, we are constrained to be exactly compatible with the standard,
31666 and this means we cannot provide this capability.  In HP Ada 83, the
31667 point of this definition is to deal with a call like:
31668
31669 @smallexample @c ada
31670 TO_ADDRESS (16#12777#);
31671 @end smallexample
31672
31673 @noindent
31674 Normally, according to the Ada 83 standard, one would expect this to be
31675 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31676 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31677 definition using @i{universal_integer} takes precedence.
31678
31679 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31680 is not possible to be 100% compatible.  Since there are many programs using
31681 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31682 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31683 declarations provided in the GNAT version of AUX_Dec are:
31684
31685 @smallexample @c ada
31686 function To_Address (X : Integer) return Address;
31687 pragma Pure_Function (To_Address);
31688
31689 function To_Address_Long (X : Unsigned_Longword)
31690  return Address;
31691 pragma Pure_Function (To_Address_Long);
31692 @end smallexample
31693
31694 @noindent
31695 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31696 change the name to TO_ADDRESS_LONG@.
31697
31698 @item Task_Id values
31699 The Task_Id values assigned will be different in the two systems, and GNAT
31700 does not provide a specified value for the Task_Id of the environment task,
31701 which in GNAT is treated like any other declared task.
31702 @end table
31703
31704 @noindent
31705 For full details on these and other less significant compatibility issues,
31706 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31707 Overview and Comparison on HP Platforms}.
31708
31709 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31710 attributes are recognized, although only a subset of them can sensibly
31711 be implemented.  The description of pragmas in @ref{Implementation
31712 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31713 indicates whether or not they are applicable to non-VMS systems.
31714 @end ifclear
31715
31716 @ifset vms
31717 @node Transitioning to 64-Bit GNAT for OpenVMS
31718 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31719
31720 @noindent
31721 This section is meant to assist users of pre-2006 @value{EDITION}
31722 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31723 the version of the GNAT technology supplied in 2006 and later for
31724 OpenVMS on both Alpha and I64.
31725
31726 @menu
31727 * Introduction to transitioning::
31728 * Migration of 32 bit code::
31729 * Taking advantage of 64 bit addressing::
31730 * Technical details::
31731 @end menu
31732
31733 @node Introduction to transitioning
31734 @subsection Introduction
31735
31736 @noindent
31737 64-bit @value{EDITION} for Open VMS has been designed to meet
31738 three main goals:
31739
31740 @enumerate
31741 @item
31742 Providing a full conforming implementation of Ada 95 and Ada 2005
31743
31744 @item
31745 Allowing maximum backward compatibility, thus easing migration of existing
31746 Ada source code
31747
31748 @item
31749 Supplying a path for exploiting the full 64-bit address range
31750 @end enumerate
31751
31752 @noindent
31753 Ada's strong typing semantics has made it
31754 impractical to have different 32-bit and 64-bit modes. As soon as
31755 one object could possibly be outside the 32-bit address space, this
31756 would make it necessary for the @code{System.Address} type to be 64 bits.
31757 In particular, this would cause inconsistencies if 32-bit code is
31758 called from 64-bit code that raises an exception.
31759
31760 This issue has been resolved by always using 64-bit addressing
31761 at the system level, but allowing for automatic conversions between
31762 32-bit and 64-bit addresses where required. Thus users who
31763 do not currently require 64-bit addressing capabilities, can
31764 recompile their code with only minimal changes (and indeed
31765 if the code is written in portable Ada, with no assumptions about
31766 the size of the @code{Address} type, then no changes at all are necessary).
31767 At the same time,
31768 this approach provides a simple, gradual upgrade path to future
31769 use of larger memories than available for 32-bit systems.
31770 Also, newly written applications or libraries will by default
31771 be fully compatible with future systems exploiting 64-bit
31772 addressing capabilities.
31773
31774 @ref{Migration of 32 bit code}, will focus on porting applications
31775 that do not require more than 2 GB of
31776 addressable memory. This code will be referred to as
31777 @emph{32-bit code}.
31778 For applications intending to exploit the full 64-bit address space,
31779 @ref{Taking advantage of 64 bit addressing},
31780 will consider further changes that may be required.
31781 Such code will be referred to below as @emph{64-bit code}.
31782
31783 @node Migration of 32 bit code
31784 @subsection Migration of 32-bit code
31785
31786 @menu
31787 * Address types::
31788 * Access types::
31789 * Unchecked conversions::
31790 * Predefined constants::
31791 * Interfacing with C::
31792 * Experience with source compatibility::
31793 @end menu
31794
31795 @node Address types
31796 @subsubsection Address types
31797
31798 @noindent
31799 To solve the problem of mixing 64-bit and 32-bit addressing,
31800 while maintaining maximum backward compatibility, the following
31801 approach has been taken:
31802
31803 @itemize @bullet
31804 @item
31805 @code{System.Address} always has a size of 64 bits
31806
31807 @item
31808 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31809 @end itemize
31810
31811 @noindent
31812 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31813 a @code{Short_Address}
31814 may be used where an @code{Address} is required, and vice versa, without
31815 needing explicit type conversions.
31816 By virtue of the Open VMS parameter passing conventions,
31817 even imported
31818 and exported subprograms that have 32-bit address parameters are
31819 compatible with those that have 64-bit address parameters.
31820 (See @ref{Making code 64 bit clean} for details.)
31821
31822 The areas that may need attention are those where record types have
31823 been defined that contain components of the type @code{System.Address}, and
31824 where objects of this type are passed to code expecting a record layout with
31825 32-bit addresses.
31826
31827 Different compilers on different platforms cannot be
31828 expected to represent the same type in the same way,
31829 since alignment constraints
31830 and other system-dependent properties affect the compiler's decision.
31831 For that reason, Ada code
31832 generally uses representation clauses to specify the expected
31833 layout where required.
31834
31835 If such a representation clause uses 32 bits for a component having
31836 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31837 will detect that error and produce a specific diagnostic message.
31838 The developer should then determine whether the representation
31839 should be 64 bits or not and make either of two changes:
31840 change the size to 64 bits and leave the type as @code{System.Address}, or
31841 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31842 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31843 required in any code setting or accessing the field; the compiler will
31844 automatically perform any needed conversions between address
31845 formats.
31846
31847 @node Access types
31848 @subsubsection Access types
31849
31850 @noindent
31851 By default, objects designated by access values are always
31852 allocated in the 32-bit
31853 address space. Thus legacy code will never contain
31854 any objects that are not addressable with 32-bit addresses, and
31855 the compiler will never raise exceptions as result of mixing
31856 32-bit and 64-bit addresses.
31857
31858 However, the access values themselves are represented in 64 bits, for optimum
31859 performance and future compatibility with 64-bit code. As was
31860 the case with @code{System.Address}, the compiler will give an error message
31861 if an object or record component has a representation clause that
31862 requires the access value to fit in 32 bits. In such a situation,
31863 an explicit size clause for the access type, specifying 32 bits,
31864 will have the desired effect.
31865
31866 General access types (declared with @code{access all}) can never be
31867 32 bits, as values of such types must be able to refer to any object
31868 of the  designated type,
31869 including objects residing outside the 32-bit address range.
31870 Existing Ada 83 code will not contain such type definitions,
31871 however, since general access types were introduced in Ada 95.
31872
31873 @node Unchecked conversions
31874 @subsubsection Unchecked conversions
31875
31876 @noindent
31877 In the case of an @code{Unchecked_Conversion} where the source type is a
31878 64-bit access type or the type @code{System.Address}, and the target
31879 type is a 32-bit type, the compiler will generate a warning.
31880 Even though the generated code will still perform the required
31881 conversions, it is highly recommended in these cases to use
31882 respectively a 32-bit access type or @code{System.Short_Address}
31883 as the source type.
31884
31885 @node Predefined constants
31886 @subsubsection Predefined constants
31887
31888 @noindent
31889 The following table shows the correspondence between pre-2006 versions of
31890 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31891 (``New''):
31892
31893 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31894 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31895 @item   @code{System.Word_Size}          @tab 32      @tab 64
31896 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31897 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31898 @item   @code{System.Address_Size}       @tab 32      @tab 64
31899 @end multitable
31900
31901 @noindent
31902 If you need to refer to the specific
31903 memory size of a 32-bit implementation, instead of the
31904 actual memory size, use @code{System.Short_Memory_Size}
31905 rather than @code{System.Memory_Size}.
31906 Similarly, references to @code{System.Address_Size} may need
31907 to be replaced by @code{System.Short_Address'Size}.
31908 The program @command{gnatfind} may be useful for locating
31909 references to the above constants, so that you can verify that they
31910 are still correct.
31911
31912 @node Interfacing with C
31913 @subsubsection Interfacing with C
31914
31915 @noindent
31916 In order to minimize the impact of the transition to 64-bit addresses on
31917 legacy programs, some fundamental types in the @code{Interfaces.C}
31918 package hierarchy continue to be represented in 32 bits.
31919 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31920 This eases integration with the default HP C layout choices, for example
31921 as found in the system routines in @code{DECC$SHR.EXE}.
31922 Because of this implementation choice, the type fully compatible with
31923 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31924 Depending on the context the compiler will issue a
31925 warning or an error when type @code{Address} is used, alerting the user to a
31926 potential problem. Otherwise 32-bit programs that use
31927 @code{Interfaces.C} should normally not require code modifications
31928
31929 The other issue arising with C interfacing concerns pragma @code{Convention}.
31930 For VMS 64-bit systems, there is an issue of the appropriate default size
31931 of C convention pointers in the absence of an explicit size clause. The HP
31932 C compiler can choose either 32 or 64 bits depending on compiler options.
31933 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31934 clause is given. This proves a better choice for porting 32-bit legacy
31935 applications. In order to have a 64-bit representation, it is necessary to
31936 specify a size representation clause. For example:
31937
31938 @smallexample @c ada
31939 type int_star is access Interfaces.C.int;
31940 pragma Convention(C, int_star);
31941 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31942 @end smallexample
31943
31944 @node Experience with source compatibility
31945 @subsubsection Experience with source compatibility
31946
31947 @noindent
31948 The Security Server and STARLET on I64 provide an interesting ``test case''
31949 for source compatibility issues, since it is in such system code
31950 where assumptions about @code{Address} size might be expected to occur.
31951 Indeed, there were a small number of occasions in the Security Server
31952 file @file{jibdef.ads}
31953 where a representation clause for a record type specified
31954 32 bits for a component of type @code{Address}.
31955 All of these errors were detected by the compiler.
31956 The repair was obvious and immediate; to simply replace @code{Address} by
31957 @code{Short_Address}.
31958
31959 In the case of STARLET, there were several record types that should
31960 have had representation clauses but did not.  In these record types
31961 there was an implicit assumption that an @code{Address} value occupied
31962 32 bits.
31963 These compiled without error, but their usage resulted in run-time error
31964 returns from STARLET system calls.
31965 Future GNAT technology enhancements may include a tool that detects and flags
31966 these sorts of potential source code porting problems.
31967
31968 @c ****************************************
31969 @node Taking advantage of 64 bit addressing
31970 @subsection Taking advantage of 64-bit addressing
31971
31972 @menu
31973 * Making code 64 bit clean::
31974 * Allocating memory from the 64 bit storage pool::
31975 * Restrictions on use of 64 bit objects::
31976 * Using 64 bit storage pools by default::
31977 * General access types::
31978 * STARLET and other predefined libraries::
31979 @end menu
31980
31981 @node Making code 64 bit clean
31982 @subsubsection Making code 64-bit clean
31983
31984 @noindent
31985 In order to prevent problems that may occur when (parts of) a
31986 system start using memory outside the 32-bit address range,
31987 we recommend some additional guidelines:
31988
31989 @itemize @bullet
31990 @item
31991 For imported subprograms that take parameters of the
31992 type @code{System.Address}, ensure that these subprograms can
31993 indeed handle 64-bit addresses. If not, or when in doubt,
31994 change the subprogram declaration to specify
31995 @code{System.Short_Address} instead.
31996
31997 @item
31998 Resolve all warnings related to size mismatches in
31999 unchecked conversions. Failing to do so causes
32000 erroneous execution if the source object is outside
32001 the 32-bit address space.
32002
32003 @item
32004 (optional) Explicitly use the 32-bit storage pool
32005 for access types used in a 32-bit context, or use
32006 generic access types where possible
32007 (@pxref{Restrictions on use of 64 bit objects}).
32008 @end itemize
32009
32010 @noindent
32011 If these rules are followed, the compiler will automatically insert
32012 any necessary checks to ensure that no addresses or access values
32013 passed to 32-bit code ever refer to objects outside the 32-bit
32014 address range.
32015 Any attempt to do this will raise @code{Constraint_Error}.
32016
32017 @node Allocating memory from the 64 bit storage pool
32018 @subsubsection Allocating memory from the 64-bit storage pool
32019
32020 @noindent
32021 For any access type @code{T} that potentially requires memory allocations
32022 beyond the 32-bit address space,
32023 use the following representation clause:
32024
32025 @smallexample @c ada
32026    for T'Storage_Pool use System.Pool_64;
32027 @end smallexample
32028
32029 @node Restrictions on use of 64 bit objects
32030 @subsubsection Restrictions on use of 64-bit objects
32031
32032 @noindent
32033 Taking the address of an object allocated from a 64-bit storage pool,
32034 and then passing this address to a subprogram expecting
32035 @code{System.Short_Address},
32036 or assigning it to a variable of type @code{Short_Address}, will cause
32037 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
32038 (@pxref{Making code 64 bit clean}), or checks are suppressed,
32039 no exception is raised and execution
32040 will become erroneous.
32041
32042 @node Using 64 bit storage pools by default
32043 @subsubsection Using 64-bit storage pools by default
32044
32045 @noindent
32046 In some cases it may be desirable to have the compiler allocate
32047 from 64-bit storage pools by default. This may be the case for
32048 libraries that are 64-bit clean, but may be used in both 32-bit
32049 and 64-bit contexts. For these cases the following configuration
32050 pragma may be specified:
32051
32052 @smallexample @c ada
32053   pragma Pool_64_Default;
32054 @end smallexample
32055
32056 @noindent
32057 Any code compiled in the context of this pragma will by default
32058 use the @code{System.Pool_64} storage pool. This default may be overridden
32059 for a specific access type @code{T} by the representation clause:
32060
32061 @smallexample @c ada
32062    for T'Storage_Pool use System.Pool_32;
32063 @end smallexample
32064
32065 @noindent
32066 Any object whose address may be passed to a subprogram with a
32067 @code{Short_Address} argument, or assigned to a variable of type
32068 @code{Short_Address}, needs to be allocated from this pool.
32069
32070 @node General access types
32071 @subsubsection General access types
32072
32073 @noindent
32074 Objects designated by access values from a
32075 general access type (declared with @code{access all}) are never allocated
32076 from a 64-bit storage pool. Code that uses general access types will
32077 accept objects allocated in either 32-bit or 64-bit address spaces,
32078 but never allocate objects outside the 32-bit address space.
32079 Using general access types ensures maximum compatibility with both
32080 32-bit and 64-bit code.
32081
32082 @node STARLET and other predefined libraries
32083 @subsubsection STARLET and other predefined libraries
32084
32085 @noindent
32086 All code that comes as part of GNAT is 64-bit clean, but the
32087 restrictions given in @ref{Restrictions on use of 64 bit objects},
32088 still apply. Look at the package
32089 specs to see in which contexts objects allocated
32090 in 64-bit address space are acceptable.
32091
32092 @node Technical details
32093 @subsection Technical details
32094
32095 @noindent
32096 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
32097 Ada standard with respect to the type of @code{System.Address}. Previous
32098 versions of GNAT Pro have defined this type as private and implemented it as a
32099 modular type.
32100
32101 In order to allow defining @code{System.Short_Address} as a proper subtype,
32102 and to match the implicit sign extension in parameter passing,
32103 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
32104 visible (i.e., non-private) integer type.
32105 Standard operations on the type, such as the binary operators ``+'', ``-'',
32106 etc., that take @code{Address} operands and return an @code{Address} result,
32107 have been hidden by declaring these
32108 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
32109 ambiguities that would otherwise result from overloading.
32110 (Note that, although @code{Address} is a visible integer type,
32111 good programming practice dictates against exploiting the type's
32112 integer properties such as literals, since this will compromise
32113 code portability.)
32114
32115 Defining @code{Address} as a visible integer type helps achieve
32116 maximum compatibility for existing Ada code,
32117 without sacrificing the capabilities of the 64-bit architecture.
32118 @end ifset
32119
32120 @c ************************************************
32121 @ifset unw
32122 @node Microsoft Windows Topics
32123 @appendix Microsoft Windows Topics
32124 @cindex Windows NT
32125 @cindex Windows 95
32126 @cindex Windows 98
32127
32128 @noindent
32129 This chapter describes topics that are specific to the Microsoft Windows
32130 platforms (NT, 2000, and XP Professional).
32131
32132 @menu
32133 * Using GNAT on Windows::
32134 * Using a network installation of GNAT::
32135 * CONSOLE and WINDOWS subsystems::
32136 * Temporary Files::
32137 * Mixed-Language Programming on Windows::
32138 * Windows Calling Conventions::
32139 * Introduction to Dynamic Link Libraries (DLLs)::
32140 * Using DLLs with GNAT::
32141 * Building DLLs with GNAT::
32142 * Building DLLs with GNAT Project files::
32143 * Building DLLs with gnatdll::
32144 * GNAT and Windows Resources::
32145 * Debugging a DLL::
32146 * Setting Stack Size from gnatlink::
32147 * Setting Heap Size from gnatlink::
32148 @end menu
32149
32150 @node Using GNAT on Windows
32151 @section Using GNAT on Windows
32152
32153 @noindent
32154 One of the strengths of the GNAT technology is that its tool set
32155 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
32156 @code{gdb} debugger, etc.) is used in the same way regardless of the
32157 platform.
32158
32159 On Windows this tool set is complemented by a number of Microsoft-specific
32160 tools that have been provided to facilitate interoperability with Windows
32161 when this is required. With these tools:
32162
32163 @itemize @bullet
32164
32165 @item
32166 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
32167 subsystems.
32168
32169 @item
32170 You can use any Dynamically Linked Library (DLL) in your Ada code (both
32171 relocatable and non-relocatable DLLs are supported).
32172
32173 @item
32174 You can build Ada DLLs for use in other applications. These applications
32175 can be written in a language other than Ada (e.g., C, C++, etc). Again both
32176 relocatable and non-relocatable Ada DLLs are supported.
32177
32178 @item
32179 You can include Windows resources in your Ada application.
32180
32181 @item
32182 You can use or create COM/DCOM objects.
32183 @end itemize
32184
32185 @noindent
32186 Immediately below are listed all known general GNAT-for-Windows restrictions.
32187 Other restrictions about specific features like Windows Resources and DLLs
32188 are listed in separate sections below.
32189
32190 @itemize @bullet
32191
32192 @item
32193 It is not possible to use @code{GetLastError} and @code{SetLastError}
32194 when tasking, protected records, or exceptions are used. In these
32195 cases, in order to implement Ada semantics, the GNAT run-time system
32196 calls certain Win32 routines that set the last error variable to 0 upon
32197 success. It should be possible to use @code{GetLastError} and
32198 @code{SetLastError} when tasking, protected record, and exception
32199 features are not used, but it is not guaranteed to work.
32200
32201 @item
32202 It is not possible to link against Microsoft libraries except for
32203 import libraries. The library must be built to be compatible with
32204 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
32205 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
32206 not be compatible with the GNAT runtime. Even if the library is
32207 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
32208
32209 @item
32210 When the compilation environment is located on FAT32 drives, users may
32211 experience recompilations of the source files that have not changed if
32212 Daylight Saving Time (DST) state has changed since the last time files
32213 were compiled. NTFS drives do not have this problem.
32214
32215 @item
32216 No components of the GNAT toolset use any entries in the Windows
32217 registry. The only entries that can be created are file associations and
32218 PATH settings, provided the user has chosen to create them at installation
32219 time, as well as some minimal book-keeping information needed to correctly
32220 uninstall or integrate different GNAT products.
32221 @end itemize
32222
32223 @node Using a network installation of GNAT
32224 @section Using a network installation of GNAT
32225
32226 @noindent
32227 Make sure the system on which GNAT is installed is accessible from the
32228 current machine, i.e., the install location is shared over the network.
32229 Shared resources are accessed on Windows by means of UNC paths, which
32230 have the format @code{\\server\sharename\path}
32231
32232 In order to use such a network installation, simply add the UNC path of the
32233 @file{bin} directory of your GNAT installation in front of your PATH. For
32234 example, if GNAT is installed in @file{\GNAT} directory of a share location
32235 called @file{c-drive} on a machine @file{LOKI}, the following command will
32236 make it available:
32237
32238 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
32239
32240 Be aware that every compilation using the network installation results in the
32241 transfer of large amounts of data across the network and will likely cause
32242 serious performance penalty.
32243
32244 @node CONSOLE and WINDOWS subsystems
32245 @section CONSOLE and WINDOWS subsystems
32246 @cindex CONSOLE Subsystem
32247 @cindex WINDOWS Subsystem
32248 @cindex -mwindows
32249
32250 @noindent
32251 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
32252 (which is the default subsystem) will always create a console when
32253 launching the application. This is not something desirable when the
32254 application has a Windows GUI. To get rid of this console the
32255 application must be using the @code{WINDOWS} subsystem. To do so
32256 the @option{-mwindows} linker option must be specified.
32257
32258 @smallexample
32259 $ gnatmake winprog -largs -mwindows
32260 @end smallexample
32261
32262 @node Temporary Files
32263 @section Temporary Files
32264 @cindex Temporary files
32265
32266 @noindent
32267 It is possible to control where temporary files gets created by setting
32268 the @env{TMP} environment variable. The file will be created:
32269
32270 @itemize
32271 @item Under the directory pointed to by the @env{TMP} environment variable if
32272 this directory exists.
32273
32274 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
32275 set (or not pointing to a directory) and if this directory exists.
32276
32277 @item Under the current working directory otherwise.
32278 @end itemize
32279
32280 @noindent
32281 This allows you to determine exactly where the temporary
32282 file will be created. This is particularly useful in networked
32283 environments where you may not have write access to some
32284 directories.
32285
32286 @node Mixed-Language Programming on Windows
32287 @section Mixed-Language Programming on Windows
32288
32289 @noindent
32290 Developing pure Ada applications on Windows is no different than on
32291 other GNAT-supported platforms. However, when developing or porting an
32292 application that contains a mix of Ada and C/C++, the choice of your
32293 Windows C/C++ development environment conditions your overall
32294 interoperability strategy.
32295
32296 If you use @command{gcc} to compile the non-Ada part of your application,
32297 there are no Windows-specific restrictions that affect the overall
32298 interoperability with your Ada code. If you plan to use
32299 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32300 the following limitations:
32301
32302 @itemize @bullet
32303 @item
32304 You cannot link your Ada code with an object or library generated with
32305 Microsoft tools if these use the @code{.tls} section (Thread Local
32306 Storage section) since the GNAT linker does not yet support this section.
32307
32308 @item
32309 You cannot link your Ada code with an object or library generated with
32310 Microsoft tools if these use I/O routines other than those provided in
32311 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32312 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32313 libraries can cause a conflict with @code{msvcrt.dll} services. For
32314 instance Visual C++ I/O stream routines conflict with those in
32315 @code{msvcrt.dll}.
32316 @end itemize
32317
32318 @noindent
32319 If you do want to use the Microsoft tools for your non-Ada code and hit one
32320 of the above limitations, you have two choices:
32321
32322 @enumerate
32323 @item
32324 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32325 application. In this case, use the Microsoft or whatever environment to
32326 build the DLL and use GNAT to build your executable
32327 (@pxref{Using DLLs with GNAT}).
32328
32329 @item
32330 Or you can encapsulate your Ada code in a DLL to be linked with the
32331 other part of your application. In this case, use GNAT to build the DLL
32332 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32333 environment to build your executable.
32334 @end enumerate
32335
32336 @node Windows Calling Conventions
32337 @section Windows Calling Conventions
32338 @findex Stdcall
32339 @findex APIENTRY
32340
32341 @menu
32342 * C Calling Convention::
32343 * Stdcall Calling Convention::
32344 * Win32 Calling Convention::
32345 * DLL Calling Convention::
32346 @end menu
32347
32348 @noindent
32349 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32350 (callee), there are several ways to push @code{G}'s parameters on the
32351 stack and there are several possible scenarios to clean up the stack
32352 upon @code{G}'s return. A calling convention is an agreed upon software
32353 protocol whereby the responsibilities between the caller (@code{F}) and
32354 the callee (@code{G}) are clearly defined. Several calling conventions
32355 are available for Windows:
32356
32357 @itemize @bullet
32358 @item
32359 @code{C} (Microsoft defined)
32360
32361 @item
32362 @code{Stdcall} (Microsoft defined)
32363
32364 @item
32365 @code{Win32} (GNAT specific)
32366
32367 @item
32368 @code{DLL} (GNAT specific)
32369 @end itemize
32370
32371 @node C Calling Convention
32372 @subsection @code{C} Calling Convention
32373
32374 @noindent
32375 This is the default calling convention used when interfacing to C/C++
32376 routines compiled with either @command{gcc} or Microsoft Visual C++.
32377
32378 In the @code{C} calling convention subprogram parameters are pushed on the
32379 stack by the caller from right to left. The caller itself is in charge of
32380 cleaning up the stack after the call. In addition, the name of a routine
32381 with @code{C} calling convention is mangled by adding a leading underscore.
32382
32383 The name to use on the Ada side when importing (or exporting) a routine
32384 with @code{C} calling convention is the name of the routine. For
32385 instance the C function:
32386
32387 @smallexample
32388 int get_val (long);
32389 @end smallexample
32390
32391 @noindent
32392 should be imported from Ada as follows:
32393
32394 @smallexample @c ada
32395 @group
32396 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32397 pragma Import (C, Get_Val, External_Name => "get_val");
32398 @end group
32399 @end smallexample
32400
32401 @noindent
32402 Note that in this particular case the @code{External_Name} parameter could
32403 have been omitted since, when missing, this parameter is taken to be the
32404 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32405 is missing, as in the above example, this parameter is set to be the
32406 @code{External_Name} with a leading underscore.
32407
32408 When importing a variable defined in C, you should always use the @code{C}
32409 calling convention unless the object containing the variable is part of a
32410 DLL (in which case you should use the @code{Stdcall} calling
32411 convention, @pxref{Stdcall Calling Convention}).
32412
32413 @node Stdcall Calling Convention
32414 @subsection @code{Stdcall} Calling Convention
32415
32416 @noindent
32417 This convention, which was the calling convention used for Pascal
32418 programs, is used by Microsoft for all the routines in the Win32 API for
32419 efficiency reasons. It must be used to import any routine for which this
32420 convention was specified.
32421
32422 In the @code{Stdcall} calling convention subprogram parameters are pushed
32423 on the stack by the caller from right to left. The callee (and not the
32424 caller) is in charge of cleaning the stack on routine exit. In addition,
32425 the name of a routine with @code{Stdcall} calling convention is mangled by
32426 adding a leading underscore (as for the @code{C} calling convention) and a
32427 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32428 bytes) of the parameters passed to the routine.
32429
32430 The name to use on the Ada side when importing a C routine with a
32431 @code{Stdcall} calling convention is the name of the C routine. The leading
32432 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32433 the compiler. For instance the Win32 function:
32434
32435 @smallexample
32436 @b{APIENTRY} int get_val (long);
32437 @end smallexample
32438
32439 @noindent
32440 should be imported from Ada as follows:
32441
32442 @smallexample @c ada
32443 @group
32444 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32445 pragma Import (Stdcall, Get_Val);
32446 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32447 @end group
32448 @end smallexample
32449
32450 @noindent
32451 As for the @code{C} calling convention, when the @code{External_Name}
32452 parameter is missing, it is taken to be the name of the Ada entity in lower
32453 case. If instead of writing the above import pragma you write:
32454
32455 @smallexample @c ada
32456 @group
32457 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32458 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32459 @end group
32460 @end smallexample
32461
32462 @noindent
32463 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32464 of specifying the @code{External_Name} parameter you specify the
32465 @code{Link_Name} as in the following example:
32466
32467 @smallexample @c ada
32468 @group
32469 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32470 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32471 @end group
32472 @end smallexample
32473
32474 @noindent
32475 then the imported routine is @code{retrieve_val}, that is, there is no
32476 decoration at all. No leading underscore and no Stdcall suffix
32477 @code{@@}@code{@var{nn}}.
32478
32479 @noindent
32480 This is especially important as in some special cases a DLL's entry
32481 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32482 name generated for a call has it.
32483
32484 @noindent
32485 It is also possible to import variables defined in a DLL by using an
32486 import pragma for a variable. As an example, if a DLL contains a
32487 variable defined as:
32488
32489 @smallexample
32490 int my_var;
32491 @end smallexample
32492
32493 @noindent
32494 then, to access this variable from Ada you should write:
32495
32496 @smallexample @c ada
32497 @group
32498 My_Var : Interfaces.C.int;
32499 pragma Import (Stdcall, My_Var);
32500 @end group
32501 @end smallexample
32502
32503 @noindent
32504 Note that to ease building cross-platform bindings this convention
32505 will be handled as a @code{C} calling convention on non-Windows platforms.
32506
32507 @node Win32 Calling Convention
32508 @subsection @code{Win32} Calling Convention
32509
32510 @noindent
32511 This convention, which is GNAT-specific is fully equivalent to the
32512 @code{Stdcall} calling convention described above.
32513
32514 @node DLL Calling Convention
32515 @subsection @code{DLL} Calling Convention
32516
32517 @noindent
32518 This convention, which is GNAT-specific is fully equivalent to the
32519 @code{Stdcall} calling convention described above.
32520
32521 @node Introduction to Dynamic Link Libraries (DLLs)
32522 @section Introduction to Dynamic Link Libraries (DLLs)
32523 @findex DLL
32524
32525 @noindent
32526 A Dynamically Linked Library (DLL) is a library that can be shared by
32527 several applications running under Windows. A DLL can contain any number of
32528 routines and variables.
32529
32530 One advantage of DLLs is that you can change and enhance them without
32531 forcing all the applications that depend on them to be relinked or
32532 recompiled. However, you should be aware than all calls to DLL routines are
32533 slower since, as you will understand below, such calls are indirect.
32534
32535 To illustrate the remainder of this section, suppose that an application
32536 wants to use the services of a DLL @file{API.dll}. To use the services
32537 provided by @file{API.dll} you must statically link against the DLL or
32538 an import library which contains a jump table with an entry for each
32539 routine and variable exported by the DLL. In the Microsoft world this
32540 import library is called @file{API.lib}. When using GNAT this import
32541 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32542 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32543
32544 After you have linked your application with the DLL or the import library
32545 and you run your application, here is what happens:
32546
32547 @enumerate
32548 @item
32549 Your application is loaded into memory.
32550
32551 @item
32552 The DLL @file{API.dll} is mapped into the address space of your
32553 application. This means that:
32554
32555 @itemize @bullet
32556 @item
32557 The DLL will use the stack of the calling thread.
32558
32559 @item
32560 The DLL will use the virtual address space of the calling process.
32561
32562 @item
32563 The DLL will allocate memory from the virtual address space of the calling
32564 process.
32565
32566 @item
32567 Handles (pointers) can be safely exchanged between routines in the DLL
32568 routines and routines in the application using the DLL.
32569 @end itemize
32570
32571 @item
32572 The entries in the jump table (from the import library @file{libAPI.dll.a}
32573 or @file{API.lib} or automatically created when linking against a DLL)
32574 which is part of your application are initialized with the addresses
32575 of the routines and variables in @file{API.dll}.
32576
32577 @item
32578 If present in @file{API.dll}, routines @code{DllMain} or
32579 @code{DllMainCRTStartup} are invoked. These routines typically contain
32580 the initialization code needed for the well-being of the routines and
32581 variables exported by the DLL.
32582 @end enumerate
32583
32584 @noindent
32585 There is an additional point which is worth mentioning. In the Windows
32586 world there are two kind of DLLs: relocatable and non-relocatable
32587 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32588 in the target application address space. If the addresses of two
32589 non-relocatable DLLs overlap and these happen to be used by the same
32590 application, a conflict will occur and the application will run
32591 incorrectly. Hence, when possible, it is always preferable to use and
32592 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32593 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32594 User's Guide) removes the debugging symbols from the DLL but the DLL can
32595 still be relocated.
32596
32597 As a side note, an interesting difference between Microsoft DLLs and
32598 Unix shared libraries, is the fact that on most Unix systems all public
32599 routines are exported by default in a Unix shared library, while under
32600 Windows it is possible (but not required) to list exported routines in
32601 a definition file (@pxref{The Definition File}).
32602
32603 @node Using DLLs with GNAT
32604 @section Using DLLs with GNAT
32605
32606 @menu
32607 * Creating an Ada Spec for the DLL Services::
32608 * Creating an Import Library::
32609 @end menu
32610
32611 @noindent
32612 To use the services of a DLL, say @file{API.dll}, in your Ada application
32613 you must have:
32614
32615 @enumerate
32616 @item
32617 The Ada spec for the routines and/or variables you want to access in
32618 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32619 header files provided with the DLL.
32620
32621 @item
32622 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32623 mentioned an import library is a statically linked library containing the
32624 import table which will be filled at load time to point to the actual
32625 @file{API.dll} routines. Sometimes you don't have an import library for the
32626 DLL you want to use. The following sections will explain how to build
32627 one. Note that this is optional.
32628
32629 @item
32630 The actual DLL, @file{API.dll}.
32631 @end enumerate
32632
32633 @noindent
32634 Once you have all the above, to compile an Ada application that uses the
32635 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32636 you simply issue the command
32637
32638 @smallexample
32639 $ gnatmake my_ada_app -largs -lAPI
32640 @end smallexample
32641
32642 @noindent
32643 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32644 tells the GNAT linker to look first for a library named @file{API.lib}
32645 (Microsoft-style name) and if not found for a libraries named
32646 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32647 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32648 contains the following pragma
32649
32650 @smallexample @c ada
32651 pragma Linker_Options ("-lAPI");
32652 @end smallexample
32653
32654 @noindent
32655 you do not have to add @option{-largs -lAPI} at the end of the
32656 @command{gnatmake} command.
32657
32658 If any one of the items above is missing you will have to create it
32659 yourself. The following sections explain how to do so using as an
32660 example a fictitious DLL called @file{API.dll}.
32661
32662 @node Creating an Ada Spec for the DLL Services
32663 @subsection Creating an Ada Spec for the DLL Services
32664
32665 @noindent
32666 A DLL typically comes with a C/C++ header file which provides the
32667 definitions of the routines and variables exported by the DLL. The Ada
32668 equivalent of this header file is a package spec that contains definitions
32669 for the imported entities. If the DLL you intend to use does not come with
32670 an Ada spec you have to generate one such spec yourself. For example if
32671 the header file of @file{API.dll} is a file @file{api.h} containing the
32672 following two definitions:
32673
32674 @smallexample
32675 @group
32676 @cartouche
32677 int some_var;
32678 int get (char *);
32679 @end cartouche
32680 @end group
32681 @end smallexample
32682
32683 @noindent
32684 then the equivalent Ada spec could be:
32685
32686 @smallexample @c ada
32687 @group
32688 @cartouche
32689 with Interfaces.C.Strings;
32690 package API is
32691    use Interfaces;
32692
32693    Some_Var : C.int;
32694    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32695
32696 private
32697    pragma Import (C, Get);
32698    pragma Import (DLL, Some_Var);
32699 end API;
32700 @end cartouche
32701 @end group
32702 @end smallexample
32703
32704 @noindent
32705 Note that a variable is
32706 @strong{always imported with a Stdcall convention}. A function
32707 can have @code{C} or @code{Stdcall} convention.
32708 (@pxref{Windows Calling Conventions}).
32709
32710 @node Creating an Import Library
32711 @subsection Creating an Import Library
32712 @cindex Import library
32713
32714 @menu
32715 * The Definition File::
32716 * GNAT-Style Import Library::
32717 * Microsoft-Style Import Library::
32718 @end menu
32719
32720 @noindent
32721 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32722 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32723 with @file{API.dll} you can skip this section. You can also skip this
32724 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32725 as in this case it is possible to link directly against the
32726 DLL. Otherwise read on.
32727
32728 @node The Definition File
32729 @subsubsection The Definition File
32730 @cindex Definition file
32731 @findex .def
32732
32733 @noindent
32734 As previously mentioned, and unlike Unix systems, the list of symbols
32735 that are exported from a DLL must be provided explicitly in Windows.
32736 The main goal of a definition file is precisely that: list the symbols
32737 exported by a DLL. A definition file (usually a file with a @code{.def}
32738 suffix) has the following structure:
32739
32740 @smallexample
32741 @group
32742 @cartouche
32743 @r{[}LIBRARY @var{name}@r{]}
32744 @r{[}DESCRIPTION @var{string}@r{]}
32745 EXPORTS
32746    @var{symbol1}
32747    @var{symbol2}
32748    @dots{}
32749 @end cartouche
32750 @end group
32751 @end smallexample
32752
32753 @table @code
32754 @item LIBRARY @var{name}
32755 This section, which is optional, gives the name of the DLL.
32756
32757 @item DESCRIPTION @var{string}
32758 This section, which is optional, gives a description string that will be
32759 embedded in the import library.
32760
32761 @item EXPORTS
32762 This section gives the list of exported symbols (procedures, functions or
32763 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32764 section of @file{API.def} looks like:
32765
32766 @smallexample
32767 @group
32768 @cartouche
32769 EXPORTS
32770    some_var
32771    get
32772 @end cartouche
32773 @end group
32774 @end smallexample
32775 @end table
32776
32777 @noindent
32778 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32779 (@pxref{Windows Calling Conventions}) for a Stdcall
32780 calling convention function in the exported symbols list.
32781
32782 @noindent
32783 There can actually be other sections in a definition file, but these
32784 sections are not relevant to the discussion at hand.
32785
32786 @node GNAT-Style Import Library
32787 @subsubsection GNAT-Style Import Library
32788
32789 @noindent
32790 To create a static import library from @file{API.dll} with the GNAT tools
32791 you should proceed as follows:
32792
32793 @enumerate
32794 @item
32795 Create the definition file @file{API.def} (@pxref{The Definition File}).
32796 For that use the @code{dll2def} tool as follows:
32797
32798 @smallexample
32799 $ dll2def API.dll > API.def
32800 @end smallexample
32801
32802 @noindent
32803 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32804 to standard output the list of entry points in the DLL. Note that if
32805 some routines in the DLL have the @code{Stdcall} convention
32806 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32807 suffix then you'll have to edit @file{api.def} to add it, and specify
32808 @option{-k} to @command{gnatdll} when creating the import library.
32809
32810 @noindent
32811 Here are some hints to find the right @code{@@}@var{nn} suffix.
32812
32813 @enumerate
32814 @item
32815 If you have the Microsoft import library (.lib), it is possible to get
32816 the right symbols by using Microsoft @code{dumpbin} tool (see the
32817 corresponding Microsoft documentation for further details).
32818
32819 @smallexample
32820 $ dumpbin /exports api.lib
32821 @end smallexample
32822
32823 @item
32824 If you have a message about a missing symbol at link time the compiler
32825 tells you what symbol is expected. You just have to go back to the
32826 definition file and add the right suffix.
32827 @end enumerate
32828
32829 @item
32830 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32831 (@pxref{Using gnatdll}) as follows:
32832
32833 @smallexample
32834 $ gnatdll -e API.def -d API.dll
32835 @end smallexample
32836
32837 @noindent
32838 @code{gnatdll} takes as input a definition file @file{API.def} and the
32839 name of the DLL containing the services listed in the definition file
32840 @file{API.dll}. The name of the static import library generated is
32841 computed from the name of the definition file as follows: if the
32842 definition file name is @var{xyz}@code{.def}, the import library name will
32843 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32844 @option{-e} could have been removed because the name of the definition
32845 file (before the ``@code{.def}'' suffix) is the same as the name of the
32846 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32847 @end enumerate
32848
32849 @node Microsoft-Style Import Library
32850 @subsubsection Microsoft-Style Import Library
32851
32852 @noindent
32853 With GNAT you can either use a GNAT-style or Microsoft-style import
32854 library. A Microsoft import library is needed only if you plan to make an
32855 Ada DLL available to applications developed with Microsoft
32856 tools (@pxref{Mixed-Language Programming on Windows}).
32857
32858 To create a Microsoft-style import library for @file{API.dll} you
32859 should proceed as follows:
32860
32861 @enumerate
32862 @item
32863 Create the definition file @file{API.def} from the DLL. For this use either
32864 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32865 tool (see the corresponding Microsoft documentation for further details).
32866
32867 @item
32868 Build the actual import library using Microsoft's @code{lib} utility:
32869
32870 @smallexample
32871 $ lib -machine:IX86 -def:API.def -out:API.lib
32872 @end smallexample
32873
32874 @noindent
32875 If you use the above command the definition file @file{API.def} must
32876 contain a line giving the name of the DLL:
32877
32878 @smallexample
32879 LIBRARY      "API"
32880 @end smallexample
32881
32882 @noindent
32883 See the Microsoft documentation for further details about the usage of
32884 @code{lib}.
32885 @end enumerate
32886
32887 @node Building DLLs with GNAT
32888 @section Building DLLs with GNAT
32889 @cindex DLLs, building
32890
32891 @noindent
32892 This section explain how to build DLLs using the GNAT built-in DLL
32893 support. With the following procedure it is straight forward to build
32894 and use DLLs with GNAT.
32895
32896 @enumerate
32897
32898 @item building object files
32899
32900 The first step is to build all objects files that are to be included
32901 into the DLL. This is done by using the standard @command{gnatmake} tool.
32902
32903 @item building the DLL
32904
32905 To build the DLL you must use @command{gcc}'s @option{-shared}
32906 option. It is quite simple to use this method:
32907
32908 @smallexample
32909 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32910 @end smallexample
32911
32912 It is important to note that in this case all symbols found in the
32913 object files are automatically exported. It is possible to restrict
32914 the set of symbols to export by passing to @command{gcc} a definition
32915 file, @pxref{The Definition File}. For example:
32916
32917 @smallexample
32918 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32919 @end smallexample
32920
32921 If you use a definition file you must export the elaboration procedures
32922 for every package that required one. Elaboration procedures are named
32923 using the package name followed by "_E".
32924
32925 @item preparing DLL to be used
32926
32927 For the DLL to be used by client programs the bodies must be hidden
32928 from it and the .ali set with read-only attribute. This is very important
32929 otherwise GNAT will recompile all packages and will not actually use
32930 the code in the DLL. For example:
32931
32932 @smallexample
32933 $ mkdir apilib
32934 $ copy *.ads *.ali api.dll apilib
32935 $ attrib +R apilib\*.ali
32936 @end smallexample
32937
32938 @end enumerate
32939
32940 At this point it is possible to use the DLL by directly linking
32941 against it. Note that you must use the GNAT shared runtime when using
32942 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32943 option.
32944
32945 @smallexample
32946 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32947 @end smallexample
32948
32949 @node Building DLLs with GNAT Project files
32950 @section Building DLLs with GNAT Project files
32951 @cindex DLLs, building
32952
32953 @noindent
32954 There is nothing specific to Windows in the build process.
32955 @pxref{Library Projects}.
32956
32957 @noindent
32958 Due to a system limitation, it is not possible under Windows to create threads
32959 when inside the @code{DllMain} routine which is used for auto-initialization
32960 of shared libraries, so it is not possible to have library level tasks in SALs.
32961
32962 @node Building DLLs with gnatdll
32963 @section Building DLLs with gnatdll
32964 @cindex DLLs, building
32965
32966 @menu
32967 * Limitations When Using Ada DLLs from Ada::
32968 * Exporting Ada Entities::
32969 * Ada DLLs and Elaboration::
32970 * Ada DLLs and Finalization::
32971 * Creating a Spec for Ada DLLs::
32972 * Creating the Definition File::
32973 * Using gnatdll::
32974 @end menu
32975
32976 @noindent
32977 Note that it is preferred to use the built-in GNAT DLL support
32978 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32979 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32980
32981 This section explains how to build DLLs containing Ada code using
32982 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32983 remainder of this section.
32984
32985 The steps required to build an Ada DLL that is to be used by Ada as well as
32986 non-Ada applications are as follows:
32987
32988 @enumerate
32989 @item
32990 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32991 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32992 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32993 skip this step if you plan to use the Ada DLL only from Ada applications.
32994
32995 @item
32996 Your Ada code must export an initialization routine which calls the routine
32997 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32998 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32999 routine exported by the Ada DLL must be invoked by the clients of the DLL
33000 to initialize the DLL.
33001
33002 @item
33003 When useful, the DLL should also export a finalization routine which calls
33004 routine @code{adafinal} generated by @command{gnatbind} to perform the
33005 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
33006 The finalization routine exported by the Ada DLL must be invoked by the
33007 clients of the DLL when the DLL services are no further needed.
33008
33009 @item
33010 You must provide a spec for the services exported by the Ada DLL in each
33011 of the programming languages to which you plan to make the DLL available.
33012
33013 @item
33014 You must provide a definition file listing the exported entities
33015 (@pxref{The Definition File}).
33016
33017 @item
33018 Finally you must use @code{gnatdll} to produce the DLL and the import
33019 library (@pxref{Using gnatdll}).
33020 @end enumerate
33021
33022 @noindent
33023 Note that a relocatable DLL stripped using the @code{strip}
33024 binutils tool will not be relocatable anymore. To build a DLL without
33025 debug information pass @code{-largs -s} to @code{gnatdll}. This
33026 restriction does not apply to a DLL built using a Library Project.
33027 @pxref{Library Projects}.
33028
33029 @node Limitations When Using Ada DLLs from Ada
33030 @subsection Limitations When Using Ada DLLs from Ada
33031
33032 @noindent
33033 When using Ada DLLs from Ada applications there is a limitation users
33034 should be aware of. Because on Windows the GNAT run time is not in a DLL of
33035 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
33036 each Ada DLL includes the services of the GNAT run time that are necessary
33037 to the Ada code inside the DLL. As a result, when an Ada program uses an
33038 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
33039 one in the main program.
33040
33041 It is therefore not possible to exchange GNAT run-time objects between the
33042 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
33043 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
33044 types, etc.
33045
33046 It is completely safe to exchange plain elementary, array or record types,
33047 Windows object handles, etc.
33048
33049 @node Exporting Ada Entities
33050 @subsection Exporting Ada Entities
33051 @cindex Export table
33052
33053 @noindent
33054 Building a DLL is a way to encapsulate a set of services usable from any
33055 application. As a result, the Ada entities exported by a DLL should be
33056 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
33057 any Ada name mangling. As an example here is an Ada package
33058 @code{API}, spec and body, exporting two procedures, a function, and a
33059 variable:
33060
33061 @smallexample @c ada
33062 @group
33063 @cartouche
33064 with Interfaces.C; use Interfaces;
33065 package API is
33066    Count : C.int := 0;
33067    function Factorial (Val : C.int) return C.int;
33068
33069    procedure Initialize_API;
33070    procedure Finalize_API;
33071    --  Initialization & Finalization routines. More in the next section.
33072 private
33073    pragma Export (C, Initialize_API);
33074    pragma Export (C, Finalize_API);
33075    pragma Export (C, Count);
33076    pragma Export (C, Factorial);
33077 end API;
33078 @end cartouche
33079 @end group
33080 @end smallexample
33081
33082 @smallexample @c ada
33083 @group
33084 @cartouche
33085 package body API is
33086    function Factorial (Val : C.int) return C.int is
33087       Fact : C.int := 1;
33088    begin
33089       Count := Count + 1;
33090       for K in 1 .. Val loop
33091          Fact := Fact * K;
33092       end loop;
33093       return Fact;
33094    end Factorial;
33095
33096    procedure Initialize_API is
33097       procedure Adainit;
33098       pragma Import (C, Adainit);
33099    begin
33100       Adainit;
33101    end Initialize_API;
33102
33103    procedure Finalize_API is
33104       procedure Adafinal;
33105       pragma Import (C, Adafinal);
33106    begin
33107       Adafinal;
33108    end Finalize_API;
33109 end API;
33110 @end cartouche
33111 @end group
33112 @end smallexample
33113
33114 @noindent
33115 If the Ada DLL you are building will only be used by Ada applications
33116 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
33117 convention. As an example, the previous package could be written as
33118 follows:
33119
33120 @smallexample @c ada
33121 @group
33122 @cartouche
33123 package API is
33124    Count : Integer := 0;
33125    function Factorial (Val : Integer) return Integer;
33126
33127    procedure Initialize_API;
33128    procedure Finalize_API;
33129    --  Initialization and Finalization routines.
33130 end API;
33131 @end cartouche
33132 @end group
33133 @end smallexample
33134
33135 @smallexample @c ada
33136 @group
33137 @cartouche
33138 package body API is
33139    function Factorial (Val : Integer) return Integer is
33140       Fact : Integer := 1;
33141    begin
33142       Count := Count + 1;
33143       for K in 1 .. Val loop
33144          Fact := Fact * K;
33145       end loop;
33146       return Fact;
33147    end Factorial;
33148
33149    @dots{}
33150    --  The remainder of this package body is unchanged.
33151 end API;
33152 @end cartouche
33153 @end group
33154 @end smallexample
33155
33156 @noindent
33157 Note that if you do not export the Ada entities with a @code{C} or
33158 @code{Stdcall} convention you will have to provide the mangled Ada names
33159 in the definition file of the Ada DLL
33160 (@pxref{Creating the Definition File}).
33161
33162 @node Ada DLLs and Elaboration
33163 @subsection Ada DLLs and Elaboration
33164 @cindex DLLs and elaboration
33165
33166 @noindent
33167 The DLL that you are building contains your Ada code as well as all the
33168 routines in the Ada library that are needed by it. The first thing a
33169 user of your DLL must do is elaborate the Ada code
33170 (@pxref{Elaboration Order Handling in GNAT}).
33171
33172 To achieve this you must export an initialization routine
33173 (@code{Initialize_API} in the previous example), which must be invoked
33174 before using any of the DLL services. This elaboration routine must call
33175 the Ada elaboration routine @code{adainit} generated by the GNAT binder
33176 (@pxref{Binding with Non-Ada Main Programs}). See the body of
33177 @code{Initialize_Api} for an example. Note that the GNAT binder is
33178 automatically invoked during the DLL build process by the @code{gnatdll}
33179 tool (@pxref{Using gnatdll}).
33180
33181 When a DLL is loaded, Windows systematically invokes a routine called
33182 @code{DllMain}. It would therefore be possible to call @code{adainit}
33183 directly from @code{DllMain} without having to provide an explicit
33184 initialization routine. Unfortunately, it is not possible to call
33185 @code{adainit} from the @code{DllMain} if your program has library level
33186 tasks because access to the @code{DllMain} entry point is serialized by
33187 the system (that is, only a single thread can execute ``through'' it at a
33188 time), which means that the GNAT run time will deadlock waiting for the
33189 newly created task to complete its initialization.
33190
33191 @node Ada DLLs and Finalization
33192 @subsection Ada DLLs and Finalization
33193 @cindex DLLs and finalization
33194
33195 @noindent
33196 When the services of an Ada DLL are no longer needed, the client code should
33197 invoke the DLL finalization routine, if available. The DLL finalization
33198 routine is in charge of releasing all resources acquired by the DLL. In the
33199 case of the Ada code contained in the DLL, this is achieved by calling
33200 routine @code{adafinal} generated by the GNAT binder
33201 (@pxref{Binding with Non-Ada Main Programs}).
33202 See the body of @code{Finalize_Api} for an
33203 example. As already pointed out the GNAT binder is automatically invoked
33204 during the DLL build process by the @code{gnatdll} tool
33205 (@pxref{Using gnatdll}).
33206
33207 @node Creating a Spec for Ada DLLs
33208 @subsection Creating a Spec for Ada DLLs
33209
33210 @noindent
33211 To use the services exported by the Ada DLL from another programming
33212 language (e.g.@: C), you have to translate the specs of the exported Ada
33213 entities in that language. For instance in the case of @code{API.dll},
33214 the corresponding C header file could look like:
33215
33216 @smallexample
33217 @group
33218 @cartouche
33219 extern int *_imp__count;
33220 #define count (*_imp__count)
33221 int factorial (int);
33222 @end cartouche
33223 @end group
33224 @end smallexample
33225
33226 @noindent
33227 It is important to understand that when building an Ada DLL to be used by
33228 other Ada applications, you need two different specs for the packages
33229 contained in the DLL: one for building the DLL and the other for using
33230 the DLL. This is because the @code{DLL} calling convention is needed to
33231 use a variable defined in a DLL, but when building the DLL, the variable
33232 must have either the @code{Ada} or @code{C} calling convention. As an
33233 example consider a DLL comprising the following package @code{API}:
33234
33235 @smallexample @c ada
33236 @group
33237 @cartouche
33238 package API is
33239    Count : Integer := 0;
33240    @dots{}
33241    --  Remainder of the package omitted.
33242 end API;
33243 @end cartouche
33244 @end group
33245 @end smallexample
33246
33247 @noindent
33248 After producing a DLL containing package @code{API}, the spec that
33249 must be used to import @code{API.Count} from Ada code outside of the
33250 DLL is:
33251
33252 @smallexample @c ada
33253 @group
33254 @cartouche
33255 package API is
33256    Count : Integer;
33257    pragma Import (DLL, Count);
33258 end API;
33259 @end cartouche
33260 @end group
33261 @end smallexample
33262
33263 @node Creating the Definition File
33264 @subsection Creating the Definition File
33265
33266 @noindent
33267 The definition file is the last file needed to build the DLL. It lists
33268 the exported symbols. As an example, the definition file for a DLL
33269 containing only package @code{API} (where all the entities are exported
33270 with a @code{C} calling convention) is:
33271
33272 @smallexample
33273 @group
33274 @cartouche
33275 EXPORTS
33276     count
33277     factorial
33278     finalize_api
33279     initialize_api
33280 @end cartouche
33281 @end group
33282 @end smallexample
33283
33284 @noindent
33285 If the @code{C} calling convention is missing from package @code{API},
33286 then the definition file contains the mangled Ada names of the above
33287 entities, which in this case are:
33288
33289 @smallexample
33290 @group
33291 @cartouche
33292 EXPORTS
33293     api__count
33294     api__factorial
33295     api__finalize_api
33296     api__initialize_api
33297 @end cartouche
33298 @end group
33299 @end smallexample
33300
33301 @node Using gnatdll
33302 @subsection Using @code{gnatdll}
33303 @findex gnatdll
33304
33305 @menu
33306 * gnatdll Example::
33307 * gnatdll behind the Scenes::
33308 * Using dlltool::
33309 @end menu
33310
33311 @noindent
33312 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33313 and non-Ada sources that make up your DLL have been compiled.
33314 @code{gnatdll} is actually in charge of two distinct tasks: build the
33315 static import library for the DLL and the actual DLL. The form of the
33316 @code{gnatdll} command is
33317
33318 @smallexample
33319 @cartouche
33320 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33321 @c Expanding @ovar macro inline (explanation in macro def comments)
33322 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33323 @end cartouche
33324 @end smallexample
33325
33326 @noindent
33327 where @var{list-of-files} is a list of ALI and object files. The object
33328 file list must be the exact list of objects corresponding to the non-Ada
33329 sources whose services are to be included in the DLL. The ALI file list
33330 must be the exact list of ALI files for the corresponding Ada sources
33331 whose services are to be included in the DLL. If @var{list-of-files} is
33332 missing, only the static import library is generated.
33333
33334 @noindent
33335 You may specify any of the following switches to @code{gnatdll}:
33336
33337 @table @code
33338 @c @item -a@ovar{address}
33339 @c Expanding @ovar macro inline (explanation in macro def comments)
33340 @item -a@r{[}@var{address}@r{]}
33341 @cindex @option{-a} (@code{gnatdll})
33342 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33343 specified the default address @var{0x11000000} will be used. By default,
33344 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33345 advise the reader to build relocatable DLL.
33346
33347 @item -b @var{address}
33348 @cindex @option{-b} (@code{gnatdll})
33349 Set the relocatable DLL base address. By default the address is
33350 @code{0x11000000}.
33351
33352 @item -bargs @var{opts}
33353 @cindex @option{-bargs} (@code{gnatdll})
33354 Binder options. Pass @var{opts} to the binder.
33355
33356 @item -d @var{dllfile}
33357 @cindex @option{-d} (@code{gnatdll})
33358 @var{dllfile} is the name of the DLL. This switch must be present for
33359 @code{gnatdll} to do anything. The name of the generated import library is
33360 obtained algorithmically from @var{dllfile} as shown in the following
33361 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33362 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33363 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33364 as shown in the following example:
33365 if @var{dllfile} is @code{xyz.dll}, the definition
33366 file used is @code{xyz.def}.
33367
33368 @item -e @var{deffile}
33369 @cindex @option{-e} (@code{gnatdll})
33370 @var{deffile} is the name of the definition file.
33371
33372 @item -g
33373 @cindex @option{-g} (@code{gnatdll})
33374 Generate debugging information. This information is stored in the object
33375 file and copied from there to the final DLL file by the linker,
33376 where it can be read by the debugger. You must use the
33377 @option{-g} switch if you plan on using the debugger or the symbolic
33378 stack traceback.
33379
33380 @item -h
33381 @cindex @option{-h} (@code{gnatdll})
33382 Help mode. Displays @code{gnatdll} switch usage information.
33383
33384 @item -Idir
33385 @cindex @option{-I} (@code{gnatdll})
33386 Direct @code{gnatdll} to search the @var{dir} directory for source and
33387 object files needed to build the DLL.
33388 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33389
33390 @item -k
33391 @cindex @option{-k} (@code{gnatdll})
33392 Removes the @code{@@}@var{nn} suffix from the import library's exported
33393 names, but keeps them for the link names. You must specify this
33394 option if you want to use a @code{Stdcall} function in a DLL for which
33395 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33396 of the Windows NT DLL for example. This option has no effect when
33397 @option{-n} option is specified.
33398
33399 @item -l @var{file}
33400 @cindex @option{-l} (@code{gnatdll})
33401 The list of ALI and object files used to build the DLL are listed in
33402 @var{file}, instead of being given in the command line. Each line in
33403 @var{file} contains the name of an ALI or object file.
33404
33405 @item -n
33406 @cindex @option{-n} (@code{gnatdll})
33407 No Import. Do not create the import library.
33408
33409 @item -q
33410 @cindex @option{-q} (@code{gnatdll})
33411 Quiet mode. Do not display unnecessary messages.
33412
33413 @item -v
33414 @cindex @option{-v} (@code{gnatdll})
33415 Verbose mode. Display extra information.
33416
33417 @item -largs @var{opts}
33418 @cindex @option{-largs} (@code{gnatdll})
33419 Linker options. Pass @var{opts} to the linker.
33420 @end table
33421
33422 @node gnatdll Example
33423 @subsubsection @code{gnatdll} Example
33424
33425 @noindent
33426 As an example the command to build a relocatable DLL from @file{api.adb}
33427 once @file{api.adb} has been compiled and @file{api.def} created is
33428
33429 @smallexample
33430 $ gnatdll -d api.dll api.ali
33431 @end smallexample
33432
33433 @noindent
33434 The above command creates two files: @file{libapi.dll.a} (the import
33435 library) and @file{api.dll} (the actual DLL). If you want to create
33436 only the DLL, just type:
33437
33438 @smallexample
33439 $ gnatdll -d api.dll -n api.ali
33440 @end smallexample
33441
33442 @noindent
33443 Alternatively if you want to create just the import library, type:
33444
33445 @smallexample
33446 $ gnatdll -d api.dll
33447 @end smallexample
33448
33449 @node gnatdll behind the Scenes
33450 @subsubsection @code{gnatdll} behind the Scenes
33451
33452 @noindent
33453 This section details the steps involved in creating a DLL. @code{gnatdll}
33454 does these steps for you. Unless you are interested in understanding what
33455 goes on behind the scenes, you should skip this section.
33456
33457 We use the previous example of a DLL containing the Ada package @code{API},
33458 to illustrate the steps necessary to build a DLL. The starting point is a
33459 set of objects that will make up the DLL and the corresponding ALI
33460 files. In the case of this example this means that @file{api.o} and
33461 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33462 the following:
33463
33464 @enumerate
33465 @item
33466 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33467 the information necessary to generate relocation information for the
33468 DLL.
33469
33470 @smallexample
33471 @group
33472 $ gnatbind -n api
33473 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33474 @end group
33475 @end smallexample
33476
33477 @noindent
33478 In addition to the base file, the @command{gnatlink} command generates an
33479 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33480 asks @command{gnatlink} to generate the routines @code{DllMain} and
33481 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33482 is loaded into memory.
33483
33484 @item
33485 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33486 export table (@file{api.exp}). The export table contains the relocation
33487 information in a form which can be used during the final link to ensure
33488 that the Windows loader is able to place the DLL anywhere in memory.
33489
33490 @smallexample
33491 @group
33492 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33493           --output-exp api.exp
33494 @end group
33495 @end smallexample
33496
33497 @item
33498 @code{gnatdll} builds the base file using the new export table. Note that
33499 @command{gnatbind} must be called once again since the binder generated file
33500 has been deleted during the previous call to @command{gnatlink}.
33501
33502 @smallexample
33503 @group
33504 $ gnatbind -n api
33505 $ gnatlink api -o api.jnk api.exp -mdll
33506       -Wl,--base-file,api.base
33507 @end group
33508 @end smallexample
33509
33510 @item
33511 @code{gnatdll} builds the new export table using the new base file and
33512 generates the DLL import library @file{libAPI.dll.a}.
33513
33514 @smallexample
33515 @group
33516 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33517           --output-exp api.exp --output-lib libAPI.a
33518 @end group
33519 @end smallexample
33520
33521 @item
33522 Finally @code{gnatdll} builds the relocatable DLL using the final export
33523 table.
33524
33525 @smallexample
33526 @group
33527 $ gnatbind -n api
33528 $ gnatlink api api.exp -o api.dll -mdll
33529 @end group
33530 @end smallexample
33531 @end enumerate
33532
33533 @node Using dlltool
33534 @subsubsection Using @code{dlltool}
33535
33536 @noindent
33537 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33538 DLLs and static import libraries. This section summarizes the most
33539 common @code{dlltool} switches. The form of the @code{dlltool} command
33540 is
33541
33542 @smallexample
33543 @c $ dlltool @ovar{switches}
33544 @c Expanding @ovar macro inline (explanation in macro def comments)
33545 $ dlltool @r{[}@var{switches}@r{]}
33546 @end smallexample
33547
33548 @noindent
33549 @code{dlltool} switches include:
33550
33551 @table @option
33552 @item --base-file @var{basefile}
33553 @cindex @option{--base-file} (@command{dlltool})
33554 Read the base file @var{basefile} generated by the linker. This switch
33555 is used to create a relocatable DLL.
33556
33557 @item --def @var{deffile}
33558 @cindex @option{--def} (@command{dlltool})
33559 Read the definition file.
33560
33561 @item --dllname @var{name}
33562 @cindex @option{--dllname} (@command{dlltool})
33563 Gives the name of the DLL. This switch is used to embed the name of the
33564 DLL in the static import library generated by @code{dlltool} with switch
33565 @option{--output-lib}.
33566
33567 @item -k
33568 @cindex @option{-k} (@command{dlltool})
33569 Kill @code{@@}@var{nn} from exported names
33570 (@pxref{Windows Calling Conventions}
33571 for a discussion about @code{Stdcall}-style symbols.
33572
33573 @item --help
33574 @cindex @option{--help} (@command{dlltool})
33575 Prints the @code{dlltool} switches with a concise description.
33576
33577 @item --output-exp @var{exportfile}
33578 @cindex @option{--output-exp} (@command{dlltool})
33579 Generate an export file @var{exportfile}. The export file contains the
33580 export table (list of symbols in the DLL) and is used to create the DLL.
33581
33582 @item --output-lib @var{libfile}
33583 @cindex @option{--output-lib} (@command{dlltool})
33584 Generate a static import library @var{libfile}.
33585
33586 @item -v
33587 @cindex @option{-v} (@command{dlltool})
33588 Verbose mode.
33589
33590 @item --as @var{assembler-name}
33591 @cindex @option{--as} (@command{dlltool})
33592 Use @var{assembler-name} as the assembler. The default is @code{as}.
33593 @end table
33594
33595 @node GNAT and Windows Resources
33596 @section GNAT and Windows Resources
33597 @cindex Resources, windows
33598
33599 @menu
33600 * Building Resources::
33601 * Compiling Resources::
33602 * Using Resources::
33603 @end menu
33604
33605 @noindent
33606 Resources are an easy way to add Windows specific objects to your
33607 application. The objects that can be added as resources include:
33608
33609 @itemize @bullet
33610 @item
33611 menus
33612
33613 @item
33614 accelerators
33615
33616 @item
33617 dialog boxes
33618
33619 @item
33620 string tables
33621
33622 @item
33623 bitmaps
33624
33625 @item
33626 cursors
33627
33628 @item
33629 icons
33630
33631 @item
33632 fonts
33633 @end itemize
33634
33635 @noindent
33636 This section explains how to build, compile and use resources.
33637
33638 @node Building Resources
33639 @subsection Building Resources
33640 @cindex Resources, building
33641
33642 @noindent
33643 A resource file is an ASCII file. By convention resource files have an
33644 @file{.rc} extension.
33645 The easiest way to build a resource file is to use Microsoft tools
33646 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33647 @code{dlgedit.exe} to build dialogs.
33648 It is always possible to build an @file{.rc} file yourself by writing a
33649 resource script.
33650
33651 It is not our objective to explain how to write a resource file. A
33652 complete description of the resource script language can be found in the
33653 Microsoft documentation.
33654
33655 @node Compiling Resources
33656 @subsection Compiling Resources
33657 @findex rc
33658 @findex windres
33659 @cindex Resources, compiling
33660
33661 @noindent
33662 This section describes how to build a GNAT-compatible (COFF) object file
33663 containing the resources. This is done using the Resource Compiler
33664 @code{windres} as follows:
33665
33666 @smallexample
33667 $ windres -i myres.rc -o myres.o
33668 @end smallexample
33669
33670 @noindent
33671 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33672 file. You can specify an alternate preprocessor (usually named
33673 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33674 parameter. A list of all possible options may be obtained by entering
33675 the command @code{windres} @option{--help}.
33676
33677 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33678 to produce a @file{.res} file (binary resource file). See the
33679 corresponding Microsoft documentation for further details. In this case
33680 you need to use @code{windres} to translate the @file{.res} file to a
33681 GNAT-compatible object file as follows:
33682
33683 @smallexample
33684 $ windres -i myres.res -o myres.o
33685 @end smallexample
33686
33687 @node Using Resources
33688 @subsection Using Resources
33689 @cindex Resources, using
33690
33691 @noindent
33692 To include the resource file in your program just add the
33693 GNAT-compatible object file for the resource(s) to the linker
33694 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33695 option:
33696
33697 @smallexample
33698 $ gnatmake myprog -largs myres.o
33699 @end smallexample
33700
33701 @node Debugging a DLL
33702 @section Debugging a DLL
33703 @cindex DLL debugging
33704
33705 @menu
33706 * Program and DLL Both Built with GCC/GNAT::
33707 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33708 @end menu
33709
33710 @noindent
33711 Debugging a DLL is similar to debugging a standard program. But
33712 we have to deal with two different executable parts: the DLL and the
33713 program that uses it. We have the following four possibilities:
33714
33715 @enumerate 1
33716 @item
33717 The program and the DLL are built with @code{GCC/GNAT}.
33718 @item
33719 The program is built with foreign tools and the DLL is built with
33720 @code{GCC/GNAT}.
33721 @item
33722 The program is built with @code{GCC/GNAT} and the DLL is built with
33723 foreign tools.
33724 @item
33725 @end enumerate
33726
33727 @noindent
33728 In this section we address only cases one and two above.
33729 There is no point in trying to debug
33730 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33731 information in it. To do so you must use a debugger compatible with the
33732 tools suite used to build the DLL.
33733
33734 @node Program and DLL Both Built with GCC/GNAT
33735 @subsection Program and DLL Both Built with GCC/GNAT
33736
33737 @noindent
33738 This is the simplest case. Both the DLL and the program have @code{GDB}
33739 compatible debugging information. It is then possible to break anywhere in
33740 the process. Let's suppose here that the main procedure is named
33741 @code{ada_main} and that in the DLL there is an entry point named
33742 @code{ada_dll}.
33743
33744 @noindent
33745 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33746 program must have been built with the debugging information (see GNAT -g
33747 switch). Here are the step-by-step instructions for debugging it:
33748
33749 @enumerate 1
33750 @item Launch @code{GDB} on the main program.
33751
33752 @smallexample
33753 $ gdb -nw ada_main
33754 @end smallexample
33755
33756 @item Start the program and stop at the beginning of the main procedure
33757
33758 @smallexample
33759 (gdb) start
33760 @end smallexample
33761
33762 @noindent
33763 This step is required to be able to set a breakpoint inside the DLL. As long
33764 as the program is not run, the DLL is not loaded. This has the
33765 consequence that the DLL debugging information is also not loaded, so it is not
33766 possible to set a breakpoint in the DLL.
33767
33768 @item Set a breakpoint inside the DLL
33769
33770 @smallexample
33771 (gdb) break ada_dll
33772 (gdb) cont
33773 @end smallexample
33774
33775 @end enumerate
33776
33777 @noindent
33778 At this stage a breakpoint is set inside the DLL. From there on
33779 you can use the standard approach to debug the whole program
33780 (@pxref{Running and Debugging Ada Programs}).
33781
33782 @ignore
33783 @c This used to work, probably because the DLLs were non-relocatable
33784 @c keep this section around until the problem is sorted out.
33785
33786 To break on the @code{DllMain} routine it is not possible to follow
33787 the procedure above. At the time the program stop on @code{ada_main}
33788 the @code{DllMain} routine as already been called. Either you can use
33789 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33790
33791 @enumerate 1
33792 @item Launch @code{GDB} on the main program.
33793
33794 @smallexample
33795 $ gdb ada_main
33796 @end smallexample
33797
33798 @item Load DLL symbols
33799
33800 @smallexample
33801 (gdb) add-sym api.dll
33802 @end smallexample
33803
33804 @item Set a breakpoint inside the DLL
33805
33806 @smallexample
33807 (gdb) break ada_dll.adb:45
33808 @end smallexample
33809
33810 Note that at this point it is not possible to break using the routine symbol
33811 directly as the program is not yet running. The solution is to break
33812 on the proper line (break in @file{ada_dll.adb} line 45).
33813
33814 @item Start the program
33815
33816 @smallexample
33817 (gdb) run
33818 @end smallexample
33819
33820 @end enumerate
33821 @end ignore
33822
33823 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33824 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33825
33826 @menu
33827 * Debugging the DLL Directly::
33828 * Attaching to a Running Process::
33829 @end menu
33830
33831 @noindent
33832 In this case things are slightly more complex because it is not possible to
33833 start the main program and then break at the beginning to load the DLL and the
33834 associated DLL debugging information. It is not possible to break at the
33835 beginning of the program because there is no @code{GDB} debugging information,
33836 and therefore there is no direct way of getting initial control. This
33837 section addresses this issue by describing some methods that can be used
33838 to break somewhere in the DLL to debug it.
33839
33840 @noindent
33841 First suppose that the main procedure is named @code{main} (this is for
33842 example some C code built with Microsoft Visual C) and that there is a
33843 DLL named @code{test.dll} containing an Ada entry point named
33844 @code{ada_dll}.
33845
33846 @noindent
33847 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33848 been built with debugging information (see GNAT -g option).
33849
33850 @node Debugging the DLL Directly
33851 @subsubsection Debugging the DLL Directly
33852
33853 @enumerate 1
33854 @item
33855 Find out the executable starting address
33856
33857 @smallexample
33858 $ objdump --file-header main.exe
33859 @end smallexample
33860
33861 The starting address is reported on the last line. For example:
33862
33863 @smallexample
33864 main.exe:     file format pei-i386
33865 architecture: i386, flags 0x0000010a:
33866 EXEC_P, HAS_DEBUG, D_PAGED
33867 start address 0x00401010
33868 @end smallexample
33869
33870 @item
33871 Launch the debugger on the executable.
33872
33873 @smallexample
33874 $ gdb main.exe
33875 @end smallexample
33876
33877 @item
33878 Set a breakpoint at the starting address, and launch the program.
33879
33880 @smallexample
33881 $ (gdb) break *0x00401010
33882 $ (gdb) run
33883 @end smallexample
33884
33885 The program will stop at the given address.
33886
33887 @item
33888 Set a breakpoint on a DLL subroutine.
33889
33890 @smallexample
33891 (gdb) break ada_dll.adb:45
33892 @end smallexample
33893
33894 Or if you want to break using a symbol on the DLL, you need first to
33895 select the Ada language (language used by the DLL).
33896
33897 @smallexample
33898 (gdb) set language ada
33899 (gdb) break ada_dll
33900 @end smallexample
33901
33902 @item
33903 Continue the program.
33904
33905 @smallexample
33906 (gdb) cont
33907 @end smallexample
33908
33909 @noindent
33910 This will run the program until it reaches the breakpoint that has been
33911 set. From that point you can use the standard way to debug a program
33912 as described in (@pxref{Running and Debugging Ada Programs}).
33913
33914 @end enumerate
33915
33916 @noindent
33917 It is also possible to debug the DLL by attaching to a running process.
33918
33919 @node Attaching to a Running Process
33920 @subsubsection Attaching to a Running Process
33921 @cindex DLL debugging, attach to process
33922
33923 @noindent
33924 With @code{GDB} it is always possible to debug a running process by
33925 attaching to it. It is possible to debug a DLL this way. The limitation
33926 of this approach is that the DLL must run long enough to perform the
33927 attach operation. It may be useful for instance to insert a time wasting
33928 loop in the code of the DLL to meet this criterion.
33929
33930 @enumerate 1
33931
33932 @item Launch the main program @file{main.exe}.
33933
33934 @smallexample
33935 $ main
33936 @end smallexample
33937
33938 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33939 that the process PID for @file{main.exe} is 208.
33940
33941 @item Launch gdb.
33942
33943 @smallexample
33944 $ gdb
33945 @end smallexample
33946
33947 @item Attach to the running process to be debugged.
33948
33949 @smallexample
33950 (gdb) attach 208
33951 @end smallexample
33952
33953 @item Load the process debugging information.
33954
33955 @smallexample
33956 (gdb) symbol-file main.exe
33957 @end smallexample
33958
33959 @item Break somewhere in the DLL.
33960
33961 @smallexample
33962 (gdb) break ada_dll
33963 @end smallexample
33964
33965 @item Continue process execution.
33966
33967 @smallexample
33968 (gdb) cont
33969 @end smallexample
33970
33971 @end enumerate
33972
33973 @noindent
33974 This last step will resume the process execution, and stop at
33975 the breakpoint we have set. From there you can use the standard
33976 approach to debug a program as described in
33977 (@pxref{Running and Debugging Ada Programs}).
33978
33979 @node Setting Stack Size from gnatlink
33980 @section Setting Stack Size from @command{gnatlink}
33981
33982 @noindent
33983 It is possible to specify the program stack size at link time. On modern
33984 versions of Windows, starting with XP, this is mostly useful to set the size of
33985 the main stack (environment task). The other task stacks are set with pragma
33986 Storage_Size or with the @command{gnatbind -d} command.
33987
33988 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33989 reserve size of individual tasks, the link-time stack size applies to all
33990 tasks, and pragma Storage_Size has no effect.
33991 In particular, Stack Overflow checks are made against this
33992 link-time specified size.
33993
33994 This setting can be done with
33995 @command{gnatlink} using either:
33996
33997 @itemize @bullet
33998
33999 @item using @option{-Xlinker} linker option
34000
34001 @smallexample
34002 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
34003 @end smallexample
34004
34005 This sets the stack reserve size to 0x10000 bytes and the stack commit
34006 size to 0x1000 bytes.
34007
34008 @item using @option{-Wl} linker option
34009
34010 @smallexample
34011 $ gnatlink hello -Wl,--stack=0x1000000
34012 @end smallexample
34013
34014 This sets the stack reserve size to 0x1000000 bytes. Note that with
34015 @option{-Wl} option it is not possible to set the stack commit size
34016 because the coma is a separator for this option.
34017
34018 @end itemize
34019
34020 @node Setting Heap Size from gnatlink
34021 @section Setting Heap Size from @command{gnatlink}
34022
34023 @noindent
34024 Under Windows systems, it is possible to specify the program heap size from
34025 @command{gnatlink} using either:
34026
34027 @itemize @bullet
34028
34029 @item using @option{-Xlinker} linker option
34030
34031 @smallexample
34032 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
34033 @end smallexample
34034
34035 This sets the heap reserve size to 0x10000 bytes and the heap commit
34036 size to 0x1000 bytes.
34037
34038 @item using @option{-Wl} linker option
34039
34040 @smallexample
34041 $ gnatlink hello -Wl,--heap=0x1000000
34042 @end smallexample
34043
34044 This sets the heap reserve size to 0x1000000 bytes. Note that with
34045 @option{-Wl} option it is not possible to set the heap commit size
34046 because the coma is a separator for this option.
34047
34048 @end itemize
34049
34050 @end ifset
34051
34052 @c **********************************
34053 @c * GNU Free Documentation License *
34054 @c **********************************
34055 @include fdl.texi
34056 @c GNU Free Documentation License
34057
34058 @node Index,,GNU Free Documentation License, Top
34059 @unnumbered Index
34060
34061 @printindex cp
34062
34063 @contents
34064 @c Put table of contents at end, otherwise it precedes the "title page" in
34065 @c the .txt version
34066 @c Edit the pdf file to move the contents to the beginning, after the title
34067 @c page
34068
34069 @bye