OSDN Git Service

* gnat_rm.texi: Move to GFDL version 1.3.
[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
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * Switches for gnatxref::
394 * Switches for gnatfind::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Rule exemption::
494 * Predefined Rules::
495 * Example of gnatcheck Usage::
496
497 Sample Bodies Using gnatstub
498
499 * Running gnatstub::
500 * Switches for gnatstub::
501
502 Other Utility Programs
503
504 * Using Other Utility Programs with GNAT::
505 * The External Symbol Naming Scheme of GNAT::
506 * Converting Ada Files to html with gnathtml::
507
508 @ifclear vms
509 Code Coverage and Profiling
510
511 * Code Coverage of Ada Programs using gcov::
512 * Profiling an Ada Program using gprof::
513 @end ifclear
514
515 Running and Debugging Ada Programs
516
517 * The GNAT Debugger GDB::
518 * Running GDB::
519 * Introduction to GDB Commands::
520 * Using Ada Expressions::
521 * Calling User-Defined Subprograms::
522 * Using the Next Command in a Function::
523 * Ada Exceptions::
524 * Ada Tasks::
525 * Debugging Generic Units::
526 * GNAT Abnormal Termination or Failure to Terminate::
527 * Naming Conventions for GNAT Source Files::
528 * Getting Internal Debugging Information::
529 * Stack Traceback::
530
531 @ifset vms
532 * LSE::
533 @end ifset
534
535 @ifset vms
536 Compatibility with HP Ada
537
538 * Ada Language Compatibility::
539 * Differences in the Definition of Package System::
540 * Language-Related Features::
541 * The Package STANDARD::
542 * The Package SYSTEM::
543 * Tasking and Task-Related Features::
544 * Pragmas and Pragma-Related Features::
545 * Library of Predefined Units::
546 * Bindings::
547 * Main Program Definition::
548 * Implementation-Defined Attributes::
549 * Compiler and Run-Time Interfacing::
550 * Program Compilation and Library Management::
551 * Input-Output::
552 * Implementation Limits::
553 * Tools and Utilities::
554
555 Language-Related Features
556
557 * Integer Types and Representations::
558 * Floating-Point Types and Representations::
559 * Pragmas Float_Representation and Long_Float::
560 * Fixed-Point Types and Representations::
561 * Record and Array Component Alignment::
562 * Address Clauses::
563 * Other Representation Clauses::
564
565 Tasking and Task-Related Features
566
567 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
568 * Assigning Task IDs::
569 * Task IDs and Delays::
570 * Task-Related Pragmas::
571 * Scheduling and Task Priority::
572 * The Task Stack::
573 * External Interrupts::
574
575 Pragmas and Pragma-Related Features
576
577 * Restrictions on the Pragma INLINE::
578 * Restrictions on the Pragma INTERFACE::
579 * Restrictions on the Pragma SYSTEM_NAME::
580
581 Library of Predefined Units
582
583 * Changes to DECLIB::
584
585 Bindings
586
587 * Shared Libraries and Options Files::
588 * Interfaces to C::
589 @end ifset
590
591 Platform-Specific Information for the Run-Time Libraries
592
593 * Summary of Run-Time Configurations::
594 * Specifying a Run-Time Library::
595 * Choosing the Scheduling Policy::
596 * Solaris-Specific Considerations::
597 * Linux-Specific Considerations::
598 * AIX-Specific Considerations::
599 * Irix-Specific Considerations::
600
601 Example of Binder Output File
602
603 Elaboration Order Handling in GNAT
604
605 * Elaboration Code::
606 * Checking the Elaboration Order::
607 * Controlling the Elaboration Order::
608 * Controlling Elaboration in GNAT - Internal Calls::
609 * Controlling Elaboration in GNAT - External Calls::
610 * Default Behavior in GNAT - Ensuring Safety::
611 * Treatment of Pragma Elaborate::
612 * Elaboration Issues for Library Tasks::
613 * Mixing Elaboration Models::
614 * What to Do If the Default Elaboration Behavior Fails::
615 * Elaboration for Access-to-Subprogram Values::
616 * Summary of Procedures for Elaboration Control::
617 * Other Elaboration Order Considerations::
618
619 Conditional Compilation
620 * Use of Boolean Constants::
621 * Debugging - A Special Case::
622 * Conditionalizing Declarations::
623 * Use of Alternative Implementations::
624 * Preprocessing::
625
626 Inline Assembler
627
628 * Basic Assembler Syntax::
629 * A Simple Example of Inline Assembler::
630 * Output Variables in Inline Assembler::
631 * Input Variables in Inline Assembler::
632 * Inlining Inline Assembler Code::
633 * Other Asm Functionality::
634
635 Compatibility and Porting Guide
636
637 * Compatibility with Ada 83::
638 * Compatibility between Ada 95 and Ada 2005::
639 * Implementation-dependent characteristics::
640 @ifclear vms
641 @c This brief section is only in the non-VMS version
642 @c The complete chapter on HP Ada issues is in the VMS version
643 * Compatibility with HP Ada 83::
644 @end ifclear
645 * Compatibility with Other Ada Systems::
646 * Representation Clauses::
647 @ifset vms
648 * Transitioning to 64-Bit GNAT for OpenVMS::
649 @end ifset
650
651 @ifset unw
652 Microsoft Windows Topics
653
654 * Using GNAT on Windows::
655 * CONSOLE and WINDOWS subsystems::
656 * Temporary Files::
657 * Mixed-Language Programming on Windows::
658 * Windows Calling Conventions::
659 * Introduction to Dynamic Link Libraries (DLLs)::
660 * Using DLLs with GNAT::
661 * Building DLLs with GNAT::
662 * GNAT and Windows Resources::
663 * Debugging a DLL::
664 * Setting Stack Size from gnatlink::
665 * Setting Heap Size from gnatlink::
666 @end ifset
667
668 * Index::
669 @end menu
670 @end ifnottex
671
672 @node About This Guide
673 @unnumbered About This Guide
674
675 @noindent
676 @ifset vms
677 This guide describes the use of @value{EDITION},
678 a compiler and software development toolset for the full Ada
679 programming language, implemented on OpenVMS for HP's Alpha and
680 Integrity server (I64) platforms.
681 @end ifset
682 @ifclear vms
683 This guide describes the use of @value{EDITION},
684 a compiler and software development
685 toolset for the full Ada programming language.
686 @end ifclear
687 It documents the features of the compiler and tools, and explains
688 how to use them to build Ada applications.
689
690 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
691 Ada 83 compatibility mode.
692 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
693 but you can override with a compiler switch
694 (@pxref{Compiling Different Versions of Ada})
695 to explicitly specify the language version.
696 Throughout this manual, references to ``Ada'' without a year suffix
697 apply to both the Ada 95 and Ada 2005 versions of the language.
698
699
700 @ifclear FSFEDITION
701 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
702 ``GNAT'' in the remainder of this document.
703 @end ifclear
704
705
706
707
708 @menu
709 * What This Guide Contains::
710 * What You Should Know before Reading This Guide::
711 * Related Information::
712 * Conventions::
713 @end menu
714
715 @node What This Guide Contains
716 @unnumberedsec What This Guide Contains
717
718 @noindent
719 This guide contains the following chapters:
720 @itemize @bullet
721
722 @item
723 @ref{Getting Started with GNAT}, describes how to get started compiling
724 and running Ada programs with the GNAT Ada programming environment.
725 @item
726 @ref{The GNAT Compilation Model}, describes the compilation model used
727 by GNAT.
728
729 @item
730 @ref{Compiling Using gcc}, describes how to compile
731 Ada programs with @command{gcc}, the Ada compiler.
732
733 @item
734 @ref{Binding Using gnatbind}, describes how to
735 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
736 utility.
737
738 @item
739 @ref{Linking Using gnatlink},
740 describes @command{gnatlink}, a
741 program that provides for linking using the GNAT run-time library to
742 construct a program. @command{gnatlink} can also incorporate foreign language
743 object units into the executable.
744
745 @item
746 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
747 utility that automatically determines the set of sources
748 needed by an Ada compilation unit, and executes the necessary compilations
749 binding and link.
750
751 @item
752 @ref{Improving Performance}, shows various techniques for making your
753 Ada program run faster or take less space.
754 It discusses the effect of the compiler's optimization switch and
755 also describes the @command{gnatelim} tool and unused subprogram/data
756 elimination.
757
758 @item
759 @ref{Renaming Files Using gnatchop}, describes
760 @code{gnatchop}, a utility that allows you to preprocess a file that
761 contains Ada source code, and split it into one or more new files, one
762 for each compilation unit.
763
764 @item
765 @ref{Configuration Pragmas}, describes the configuration pragmas
766 handled by GNAT.
767
768 @item
769 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
770 shows how to override the default GNAT file naming conventions,
771 either for an individual unit or globally.
772
773 @item
774 @ref{GNAT Project Manager}, describes how to use project files
775 to organize large projects.
776
777 @item
778 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
779 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
780 way to navigate through sources.
781
782 @item
783 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
784 version of an Ada source file with control over casing, indentation,
785 comment placement, and other elements of program presentation style.
786
787 @item
788 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
789 metrics for an Ada source file, such as the number of types and subprograms,
790 and assorted complexity measures.
791
792 @item
793 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
794 file name krunching utility, used to handle shortened
795 file names on operating systems with a limit on the length of names.
796
797 @item
798 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
799 preprocessor utility that allows a single source file to be used to
800 generate multiple or parameterized source files by means of macro
801 substitution.
802
803 @ifset vms
804 @item
805 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
806 a tool for rebuilding the GNAT run time with user-supplied
807 configuration pragmas.
808 @end ifset
809
810 @item
811 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
812 utility that displays information about compiled units, including dependences
813 on the corresponding sources files, and consistency of compilations.
814
815 @item
816 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
817 to delete files that are produced by the compiler, binder and linker.
818
819 @ifclear vms
820 @item
821 @ref{GNAT and Libraries}, describes the process of creating and using
822 Libraries with GNAT. It also describes how to recompile the GNAT run-time
823 library.
824
825 @item
826 @ref{Using the GNU make Utility}, describes some techniques for using
827 the GNAT toolset in Makefiles.
828 @end ifclear
829
830 @item
831 @ref{Memory Management Issues}, describes some useful predefined storage pools
832 and in particular the GNAT Debug Pool facility, which helps detect incorrect
833 memory references.
834 @ifclear vms
835 It also describes @command{gnatmem}, a utility that monitors dynamic
836 allocation and deallocation and helps detect ``memory leaks''.
837 @end ifclear
838
839 @item
840 @ref{Stack Related Facilities}, describes some useful tools associated with
841 stack checking and analysis.
842
843 @item
844 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
845 a utility that checks Ada code against a set of rules.
846
847 @item
848 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
849 a utility that generates empty but compilable bodies for library units.
850
851 @item
852 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
853 generate automatically Ada bindings from C and C++ headers.
854
855 @item
856 @ref{Other Utility Programs}, discusses several other GNAT utilities,
857 including @code{gnathtml}.
858
859 @ifclear vms
860 @item
861 @ref{Code Coverage and Profiling}, describes how to perform a structural
862 coverage and profile the execution of Ada programs.
863 @end ifclear
864
865 @item
866 @ref{Running and Debugging Ada Programs}, describes how to run and debug
867 Ada programs.
868
869 @ifset vms
870 @item
871 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
872 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
873 developed by Digital Equipment Corporation and currently supported by HP.}
874 for OpenVMS Alpha. This product was formerly known as DEC Ada,
875 @cindex DEC Ada
876 and for
877 historical compatibility reasons, the relevant libraries still use the
878 DEC prefix.
879 @end ifset
880
881 @item
882 @ref{Platform-Specific Information for the Run-Time Libraries},
883 describes the various run-time
884 libraries supported by GNAT on various platforms and explains how to
885 choose a particular library.
886
887 @item
888 @ref{Example of Binder Output File}, shows the source code for the binder
889 output file for a sample program.
890
891 @item
892 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
893 you deal with elaboration order issues.
894
895 @item
896 @ref{Conditional Compilation}, describes how to model conditional compilation,
897 both with Ada in general and with GNAT facilities in particular.
898
899 @item
900 @ref{Inline Assembler}, shows how to use the inline assembly facility
901 in an Ada program.
902
903 @item
904 @ref{Compatibility and Porting Guide}, contains sections on compatibility
905 of GNAT with other Ada development environments (including Ada 83 systems),
906 to assist in porting code from those environments.
907
908 @ifset unw
909 @item
910 @ref{Microsoft Windows Topics}, presents information relevant to the
911 Microsoft Windows platform.
912 @end ifset
913 @end itemize
914
915 @c *************************************************
916 @node What You Should Know before Reading This Guide
917 @c *************************************************
918 @unnumberedsec What You Should Know before Reading This Guide
919
920 @cindex Ada 95 Language Reference Manual
921 @cindex Ada 2005 Language Reference Manual
922 @noindent
923 This guide assumes a basic familiarity with the Ada 95 language, as
924 described in the International Standard ANSI/ISO/IEC-8652:1995, January
925 1995.
926 It does not require knowledge of the new features introduced by Ada 2005,
927 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
928 and Amendment 1).
929 Both reference manuals are included in the GNAT documentation
930 package.
931
932 @node Related Information
933 @unnumberedsec Related Information
934
935 @noindent
936 For further information about related tools, refer to the following
937 documents:
938
939 @itemize @bullet
940 @item
941 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
942 Reference Manual}, which contains all reference material for the GNAT
943 implementation of Ada.
944
945 @ifset unw
946 @item
947 @cite{Using the GNAT Programming Studio}, which describes the GPS
948 Integrated Development Environment.
949
950 @item
951 @cite{GNAT Programming Studio Tutorial}, which introduces the
952 main GPS features through examples.
953 @end ifset
954
955 @item
956 @cite{Ada 95 Reference Manual}, which contains reference
957 material for the Ada 95 programming language.
958
959 @item
960 @cite{Ada 2005 Reference Manual}, which contains reference
961 material for the Ada 2005 programming language.
962
963 @item
964 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
965 @ifset vms
966 in the GNU:[DOCS] directory,
967 @end ifset
968 for all details on the use of the GNU source-level debugger.
969
970 @item
971 @xref{Top,, The extensible self-documenting text editor, emacs,
972 GNU Emacs Manual},
973 @ifset vms
974 located in the GNU:[DOCS] directory if the EMACS kit is installed,
975 @end ifset
976 for full information on the extensible editor and programming
977 environment Emacs.
978
979 @end itemize
980
981 @c **************
982 @node Conventions
983 @unnumberedsec Conventions
984 @cindex Conventions
985 @cindex Typographical conventions
986
987 @noindent
988 Following are examples of the typographical and graphic conventions used
989 in this guide:
990
991 @itemize @bullet
992 @item
993 @code{Functions}, @command{utility program names}, @code{standard names},
994 and @code{classes}.
995
996 @item
997 @option{Option flags}
998
999 @item
1000 @file{File names}, @samp{button names}, and @samp{field names}.
1001
1002 @item
1003 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1004 variables}.
1005
1006 @item
1007 @emph{Emphasis}.
1008
1009 @item
1010 @r{[}optional information or parameters@r{]}
1011
1012 @item
1013 Examples are described by text
1014 @smallexample
1015 and then shown this way.
1016 @end smallexample
1017 @end itemize
1018
1019 @noindent
1020 Commands that are entered by the user are preceded in this manual by the
1021 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1022 uses this sequence as a prompt, then the commands will appear exactly as
1023 you see them in the manual. If your system uses some other prompt, then
1024 the command will appear with the @code{$} replaced by whatever prompt
1025 character you are using.
1026
1027 @ifset unw
1028 Full file names are shown with the ``@code{/}'' character
1029 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1030 If you are using GNAT on a Windows platform, please note that
1031 the ``@code{\}'' character should be used instead.
1032 @end ifset
1033
1034 @c ****************************
1035 @node Getting Started with GNAT
1036 @chapter Getting Started with GNAT
1037
1038 @noindent
1039 This chapter describes some simple ways of using GNAT to build
1040 executable Ada programs.
1041 @ifset unw
1042 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1043 show how to use the command line environment.
1044 @ref{Introduction to GPS}, provides a brief
1045 introduction to the GNAT Programming Studio, a visually-oriented
1046 Integrated Development Environment for GNAT.
1047 GPS offers a graphical ``look and feel'', support for development in
1048 other programming languages, comprehensive browsing features, and
1049 many other capabilities.
1050 For information on GPS please refer to
1051 @cite{Using the GNAT Programming Studio}.
1052 @end ifset
1053
1054 @menu
1055 * Running GNAT::
1056 * Running a Simple Ada Program::
1057 * Running a Program with Multiple Units::
1058 * Using the gnatmake Utility::
1059 @ifset vms
1060 * Editing with Emacs::
1061 @end ifset
1062 @ifclear vms
1063 * Introduction to GPS::
1064 @end ifclear
1065 @end menu
1066
1067 @node Running GNAT
1068 @section Running GNAT
1069
1070 @noindent
1071 Three steps are needed to create an executable file from an Ada source
1072 file:
1073
1074 @enumerate
1075 @item
1076 The source file(s) must be compiled.
1077 @item
1078 The file(s) must be bound using the GNAT binder.
1079 @item
1080 All appropriate object files must be linked to produce an executable.
1081 @end enumerate
1082
1083 @noindent
1084 All three steps are most commonly handled by using the @command{gnatmake}
1085 utility program that, given the name of the main program, automatically
1086 performs the necessary compilation, binding and linking steps.
1087
1088 @node Running a Simple Ada Program
1089 @section Running a Simple Ada Program
1090
1091 @noindent
1092 Any text editor may be used to prepare an Ada program.
1093 (If @code{Emacs} is
1094 used, the optional Ada mode may be helpful in laying out the program.)
1095 The
1096 program text is a normal text file. We will assume in our initial
1097 example that you have used your editor to prepare the following
1098 standard format text file:
1099
1100 @smallexample @c ada
1101 @cartouche
1102 with Ada.Text_IO; use Ada.Text_IO;
1103 procedure Hello is
1104 begin
1105    Put_Line ("Hello WORLD!");
1106 end Hello;
1107 @end cartouche
1108 @end smallexample
1109
1110 @noindent
1111 This file should be named @file{hello.adb}.
1112 With the normal default file naming conventions, GNAT requires
1113 that each file
1114 contain a single compilation unit whose file name is the
1115 unit name,
1116 with periods replaced by hyphens; the
1117 extension is @file{ads} for a
1118 spec and @file{adb} for a body.
1119 You can override this default file naming convention by use of the
1120 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1121 Alternatively, if you want to rename your files according to this default
1122 convention, which is probably more convenient if you will be using GNAT
1123 for all your compilations, then the @code{gnatchop} utility
1124 can be used to generate correctly-named source files
1125 (@pxref{Renaming Files Using gnatchop}).
1126
1127 You can compile the program using the following command (@code{$} is used
1128 as the command prompt in the examples in this document):
1129
1130 @smallexample
1131 $ gcc -c hello.adb
1132 @end smallexample
1133
1134 @noindent
1135 @command{gcc} is the command used to run the compiler. This compiler is
1136 capable of compiling programs in several languages, including Ada and
1137 C. It assumes that you have given it an Ada program if the file extension is
1138 either @file{.ads} or @file{.adb}, and it will then call
1139 the GNAT compiler to compile the specified file.
1140
1141 @ifclear vms
1142 The @option{-c} switch is required. It tells @command{gcc} to only do a
1143 compilation. (For C programs, @command{gcc} can also do linking, but this
1144 capability is not used directly for Ada programs, so the @option{-c}
1145 switch must always be present.)
1146 @end ifclear
1147
1148 This compile command generates a file
1149 @file{hello.o}, which is the object
1150 file corresponding to your Ada program. It also generates
1151 an ``Ada Library Information'' file @file{hello.ali},
1152 which contains additional information used to check
1153 that an Ada program is consistent.
1154 To build an executable file,
1155 use @code{gnatbind} to bind the program
1156 and @command{gnatlink} to link it. The
1157 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1158 @file{ALI} file, but the default extension of @file{.ali} can
1159 be omitted. This means that in the most common case, the argument
1160 is simply the name of the main program:
1161
1162 @smallexample
1163 $ gnatbind hello
1164 $ gnatlink hello
1165 @end smallexample
1166
1167 @noindent
1168 A simpler method of carrying out these steps is to use
1169 @command{gnatmake},
1170 a master program that invokes all the required
1171 compilation, binding and linking tools in the correct order. In particular,
1172 @command{gnatmake} automatically recompiles any sources that have been
1173 modified since they were last compiled, or sources that depend
1174 on such modified sources, so that ``version skew'' is avoided.
1175 @cindex Version skew (avoided by @command{gnatmake})
1176
1177 @smallexample
1178 $ gnatmake hello.adb
1179 @end smallexample
1180
1181 @noindent
1182 The result is an executable program called @file{hello}, which can be
1183 run by entering:
1184
1185 @smallexample
1186 $ ^hello^RUN HELLO^
1187 @end smallexample
1188
1189 @noindent
1190 assuming that the current directory is on the search path
1191 for executable programs.
1192
1193 @noindent
1194 and, if all has gone well, you will see
1195
1196 @smallexample
1197 Hello WORLD!
1198 @end smallexample
1199
1200 @noindent
1201 appear in response to this command.
1202
1203 @c ****************************************
1204 @node Running a Program with Multiple Units
1205 @section Running a Program with Multiple Units
1206
1207 @noindent
1208 Consider a slightly more complicated example that has three files: a
1209 main program, and the spec and body of a package:
1210
1211 @smallexample @c ada
1212 @cartouche
1213 @group
1214 package Greetings is
1215    procedure Hello;
1216    procedure Goodbye;
1217 end Greetings;
1218
1219 with Ada.Text_IO; use Ada.Text_IO;
1220 package body Greetings is
1221    procedure Hello is
1222    begin
1223       Put_Line ("Hello WORLD!");
1224    end Hello;
1225
1226    procedure Goodbye is
1227    begin
1228       Put_Line ("Goodbye WORLD!");
1229    end Goodbye;
1230 end Greetings;
1231 @end group
1232
1233 @group
1234 with Greetings;
1235 procedure Gmain is
1236 begin
1237    Greetings.Hello;
1238    Greetings.Goodbye;
1239 end Gmain;
1240 @end group
1241 @end cartouche
1242 @end smallexample
1243
1244 @noindent
1245 Following the one-unit-per-file rule, place this program in the
1246 following three separate files:
1247
1248 @table @file
1249 @item greetings.ads
1250 spec of package @code{Greetings}
1251
1252 @item greetings.adb
1253 body of package @code{Greetings}
1254
1255 @item gmain.adb
1256 body of main program
1257 @end table
1258
1259 @noindent
1260 To build an executable version of
1261 this program, we could use four separate steps to compile, bind, and link
1262 the program, as follows:
1263
1264 @smallexample
1265 $ gcc -c gmain.adb
1266 $ gcc -c greetings.adb
1267 $ gnatbind gmain
1268 $ gnatlink gmain
1269 @end smallexample
1270
1271 @noindent
1272 Note that there is no required order of compilation when using GNAT.
1273 In particular it is perfectly fine to compile the main program first.
1274 Also, it is not necessary to compile package specs in the case where
1275 there is an accompanying body; you only need to compile the body. If you want
1276 to submit these files to the compiler for semantic checking and not code
1277 generation, then use the
1278 @option{-gnatc} switch:
1279
1280 @smallexample
1281 $ gcc -c greetings.ads -gnatc
1282 @end smallexample
1283
1284 @noindent
1285 Although the compilation can be done in separate steps as in the
1286 above example, in practice it is almost always more convenient
1287 to use the @command{gnatmake} tool. All you need to know in this case
1288 is the name of the main program's source file. The effect of the above four
1289 commands can be achieved with a single one:
1290
1291 @smallexample
1292 $ gnatmake gmain.adb
1293 @end smallexample
1294
1295 @noindent
1296 In the next section we discuss the advantages of using @command{gnatmake} in
1297 more detail.
1298
1299 @c *****************************
1300 @node Using the gnatmake Utility
1301 @section Using the @command{gnatmake} Utility
1302
1303 @noindent
1304 If you work on a program by compiling single components at a time using
1305 @command{gcc}, you typically keep track of the units you modify. In order to
1306 build a consistent system, you compile not only these units, but also any
1307 units that depend on the units you have modified.
1308 For example, in the preceding case,
1309 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1310 you edit @file{greetings.ads}, you must recompile both
1311 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1312 units that depend on @file{greetings.ads}.
1313
1314 @code{gnatbind} will warn you if you forget one of these compilation
1315 steps, so that it is impossible to generate an inconsistent program as a
1316 result of forgetting to do a compilation. Nevertheless it is tedious and
1317 error-prone to keep track of dependencies among units.
1318 One approach to handle the dependency-bookkeeping is to use a
1319 makefile. However, makefiles present maintenance problems of their own:
1320 if the dependencies change as you change the program, you must make
1321 sure that the makefile is kept up-to-date manually, which is also an
1322 error-prone process.
1323
1324 The @command{gnatmake} utility takes care of these details automatically.
1325 Invoke it using either one of the following forms:
1326
1327 @smallexample
1328 $ gnatmake gmain.adb
1329 $ gnatmake ^gmain^GMAIN^
1330 @end smallexample
1331
1332 @noindent
1333 The argument is the name of the file containing the main program;
1334 you may omit the extension. @command{gnatmake}
1335 examines the environment, automatically recompiles any files that need
1336 recompiling, and binds and links the resulting set of object files,
1337 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1338 In a large program, it
1339 can be extremely helpful to use @command{gnatmake}, because working out by hand
1340 what needs to be recompiled can be difficult.
1341
1342 Note that @command{gnatmake}
1343 takes into account all the Ada rules that
1344 establish dependencies among units. These include dependencies that result
1345 from inlining subprogram bodies, and from
1346 generic instantiation. Unlike some other
1347 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1348 found by the compiler on a previous compilation, which may possibly
1349 be wrong when sources change. @command{gnatmake} determines the exact set of
1350 dependencies from scratch each time it is run.
1351
1352 @ifset vms
1353 @node Editing with Emacs
1354 @section Editing with Emacs
1355 @cindex Emacs
1356
1357 @noindent
1358 Emacs is an extensible self-documenting text editor that is available in a
1359 separate VMSINSTAL kit.
1360
1361 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1362 click on the Emacs Help menu and run the Emacs Tutorial.
1363 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1364 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1365
1366 Documentation on Emacs and other tools is available in Emacs under the
1367 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1368 use the middle mouse button to select a topic (e.g.@: Emacs).
1369
1370 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1371 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1372 get to the Emacs manual.
1373 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1374 prompt.
1375
1376 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1377 which is sufficiently extensible to provide for a complete programming
1378 environment and shell for the sophisticated user.
1379 @end ifset
1380
1381 @ifclear vms
1382 @node Introduction to GPS
1383 @section Introduction to GPS
1384 @cindex GPS (GNAT Programming Studio)
1385 @cindex GNAT Programming Studio (GPS)
1386 @noindent
1387 Although the command line interface (@command{gnatmake}, etc.) alone
1388 is sufficient, a graphical Interactive Development
1389 Environment can make it easier for you to compose, navigate, and debug
1390 programs.  This section describes the main features of GPS
1391 (``GNAT Programming Studio''), the GNAT graphical IDE.
1392 You will see how to use GPS to build and debug an executable, and
1393 you will also learn some of the basics of the GNAT ``project'' facility.
1394
1395 GPS enables you to do much more than is presented here;
1396 e.g., you can produce a call graph, interface to a third-party
1397 Version Control System, and inspect the generated assembly language
1398 for a program.
1399 Indeed, GPS also supports languages other than Ada.
1400 Such additional information, and an explanation of all of the GPS menu
1401 items. may be found in the on-line help, which includes
1402 a user's guide and a tutorial (these are also accessible from the GNAT
1403 startup menu).
1404
1405 @menu
1406 * Building a New Program with GPS::
1407 * Simple Debugging with GPS::
1408 @end menu
1409
1410 @node Building a New Program with GPS
1411 @subsection Building a New Program with GPS
1412 @noindent
1413 GPS invokes the GNAT compilation tools using information
1414 contained in a @emph{project} (also known as a @emph{project file}):
1415 a collection of properties such
1416 as source directories, identities of main subprograms, tool switches, etc.,
1417 and their associated values.
1418 See @ref{GNAT Project Manager} for details.
1419 In order to run GPS, you will need to either create a new project
1420 or else open an existing one.
1421
1422 This section will explain how you can use GPS to create a project,
1423 to associate Ada source files with a project, and to build and run
1424 programs.
1425
1426 @enumerate
1427 @item @emph{Creating a project}
1428
1429 Invoke GPS, either from the command line or the platform's IDE.
1430 After it starts, GPS will display a ``Welcome'' screen with three
1431 radio buttons:
1432
1433 @itemize @bullet
1434 @item
1435 @code{Start with default project in directory}
1436
1437 @item
1438 @code{Create new project with wizard}
1439
1440 @item
1441 @code{Open existing project}
1442 @end itemize
1443
1444 @noindent
1445 Select @code{Create new project with wizard} and press @code{OK}.
1446 A new window will appear.  In the text box labeled with
1447 @code{Enter the name of the project to create}, type @file{sample}
1448 as the project name.
1449 In the next box, browse to choose the directory in which you
1450 would like to create the project file.
1451 After selecting an appropriate directory, press @code{Forward}.
1452
1453 A window will appear with the title
1454 @code{Version Control System Configuration}.
1455 Simply press @code{Forward}.
1456
1457 A window will appear with the title
1458 @code{Please select the source directories for this project}.
1459 The directory that you specified for the project file will be selected
1460 by default as the one to use for sources; simply press @code{Forward}.
1461
1462 A window will appear with the title
1463 @code{Please select the build directory for this project}.
1464 The directory that you specified for the project file will be selected
1465 by default for object files and executables;
1466 simply press @code{Forward}.
1467
1468 A window will appear with the title
1469 @code{Please select the main units for this project}.
1470 You will supply this information later, after creating the source file.
1471 Simply press @code{Forward} for now.
1472
1473 A window will appear with the title
1474 @code{Please select the switches to build the project}.
1475 Press @code{Apply}.  This will create a project file named
1476 @file{sample.prj} in the directory that you had specified.
1477
1478 @item @emph{Creating and saving the source file}
1479
1480 After you create the new project, a GPS window will appear, which is
1481 partitioned into two main sections:
1482
1483 @itemize @bullet
1484 @item
1485 A @emph{Workspace area}, initially greyed out, which you will use for
1486 creating and editing source files
1487
1488 @item
1489 Directly below, a @emph{Messages area}, which initially displays a
1490 ``Welcome'' message.
1491 (If the Messages area is not visible, drag its border upward to expand it.)
1492 @end itemize
1493
1494 @noindent
1495 Select @code{File} on the menu bar, and then the @code{New} command.
1496 The Workspace area will become white, and you can now
1497 enter the source program explicitly.
1498 Type the following text
1499
1500 @smallexample @c ada
1501 @group
1502 with Ada.Text_IO; use Ada.Text_IO;
1503 procedure Hello is
1504 begin
1505   Put_Line("Hello from GPS!");
1506 end Hello;
1507 @end group
1508 @end smallexample
1509
1510 @noindent
1511 Select @code{File}, then @code{Save As}, and enter the source file name
1512 @file{hello.adb}.
1513 The file will be saved in the same directory you specified as the
1514 location of the default project file.
1515
1516 @item @emph{Updating the project file}
1517
1518 You need to add the new source file to the project.
1519 To do this, select
1520 the @code{Project} menu and then @code{Edit project properties}.
1521 Click the @code{Main files} tab on the left, and then the
1522 @code{Add} button.
1523 Choose @file{hello.adb} from the list, and press @code{Open}.
1524 The project settings window will reflect this action.
1525 Click @code{OK}.
1526
1527 @item @emph{Building and running the program}
1528
1529 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1530 and select @file{hello.adb}.
1531 The Messages window will display the resulting invocations of @command{gcc},
1532 @command{gnatbind}, and @command{gnatlink}
1533 (reflecting the default switch settings from the
1534 project file that you created) and then a ``successful compilation/build''
1535 message.
1536
1537 To run the program, choose the @code{Build} menu, then @code{Run}, and
1538 select @command{hello}.
1539 An @emph{Arguments Selection} window will appear.
1540 There are no command line arguments, so just click @code{OK}.
1541
1542 The Messages window will now display the program's output (the string
1543 @code{Hello from GPS}), and at the bottom of the GPS window a status
1544 update is displayed (@code{Run: hello}).
1545 Close the GPS window (or select @code{File}, then @code{Exit}) to
1546 terminate this GPS session.
1547 @end enumerate
1548
1549 @node Simple Debugging with GPS
1550 @subsection Simple Debugging with GPS
1551 @noindent
1552 This section illustrates basic debugging techniques (setting breakpoints,
1553 examining/modifying variables, single stepping).
1554
1555 @enumerate
1556 @item @emph{Opening a project}
1557
1558 Start GPS and select @code{Open existing project}; browse to
1559 specify the project file @file{sample.prj} that you had created in the
1560 earlier example.
1561
1562 @item @emph{Creating a source file}
1563
1564 Select @code{File}, then @code{New}, and type in the following program:
1565
1566 @smallexample @c ada
1567 @group
1568 with Ada.Text_IO; use Ada.Text_IO;
1569 procedure Example is
1570    Line : String (1..80);
1571    N    : Natural;
1572 begin
1573    Put_Line("Type a line of text at each prompt; an empty line to exit");
1574    loop
1575       Put(": ");
1576       Get_Line (Line, N);
1577       Put_Line (Line (1..N) );
1578       exit when N=0;
1579    end loop;
1580 end Example;
1581 @end group
1582 @end smallexample
1583
1584 @noindent
1585 Select @code{File}, then @code{Save as}, and enter the file name
1586 @file{example.adb}.
1587
1588 @item @emph{Updating the project file}
1589
1590 Add @code{Example} as a new main unit for the project:
1591 @enumerate a
1592 @item
1593 Select @code{Project}, then @code{Edit Project Properties}.
1594
1595 @item
1596 Select the @code{Main files} tab, click @code{Add}, then
1597 select the file @file{example.adb} from the list, and
1598 click @code{Open}.
1599 You will see the file name appear in the list of main units
1600
1601 @item
1602 Click @code{OK}
1603 @end enumerate
1604
1605 @item @emph{Building/running the executable}
1606
1607 To build the executable
1608 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1609
1610 Run the program to see its effect (in the Messages area).
1611 Each line that you enter is displayed; an empty line will
1612 cause the loop to exit and the program to terminate.
1613
1614 @item @emph{Debugging the program}
1615
1616 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1617 which are required for debugging, are on by default when you create
1618 a new project.
1619 Thus unless you intentionally remove these settings, you will be able
1620 to debug any program that you develop using GPS.
1621
1622 @enumerate a
1623 @item @emph{Initializing}
1624
1625 Select @code{Debug}, then @code{Initialize}, then @file{example}
1626
1627 @item @emph{Setting a breakpoint}
1628
1629 After performing the initialization step, you will observe a small
1630 icon to the right of each line number.
1631 This serves as a toggle for breakpoints; clicking the icon will
1632 set a breakpoint at the corresponding line (the icon will change to
1633 a red circle with an ``x''), and clicking it again
1634 will remove the breakpoint / reset the icon.
1635
1636 For purposes of this example, set a breakpoint at line 10 (the
1637 statement @code{Put_Line@ (Line@ (1..N));}
1638
1639 @item @emph{Starting program execution}
1640
1641 Select @code{Debug}, then @code{Run}.  When the
1642 @code{Program Arguments} window appears, click @code{OK}.
1643 A console window will appear; enter some line of text,
1644 e.g.@: @code{abcde}, at the prompt.
1645 The program will pause execution when it gets to the
1646 breakpoint, and the corresponding line is highlighted.
1647
1648 @item @emph{Examining a variable}
1649
1650 Move the mouse over one of the occurrences of the variable @code{N}.
1651 You will see the value (5) displayed, in ``tool tip'' fashion.
1652 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1653 You will see information about @code{N} appear in the @code{Debugger Data}
1654 pane, showing the value as 5.
1655
1656 @item @emph{Assigning a new value to a variable}
1657
1658 Right click on the @code{N} in the @code{Debugger Data} pane, and
1659 select @code{Set value of N}.
1660 When the input window appears, enter the value @code{4} and click
1661 @code{OK}.
1662 This value does not automatically appear in the @code{Debugger Data}
1663 pane; to see it, right click again on the @code{N} in the
1664 @code{Debugger Data} pane and select @code{Update value}.
1665 The new value, 4, will appear in red.
1666
1667 @item @emph{Single stepping}
1668
1669 Select @code{Debug}, then @code{Next}.
1670 This will cause the next statement to be executed, in this case the
1671 call of @code{Put_Line} with the string slice.
1672 Notice in the console window that the displayed string is simply
1673 @code{abcd} and not @code{abcde} which you had entered.
1674 This is because the upper bound of the slice is now 4 rather than 5.
1675
1676 @item @emph{Removing a breakpoint}
1677
1678 Toggle the breakpoint icon at line 10.
1679
1680 @item @emph{Resuming execution from a breakpoint}
1681
1682 Select @code{Debug}, then @code{Continue}.
1683 The program will reach the next iteration of the loop, and
1684 wait for input after displaying the prompt.
1685 This time, just hit the @kbd{Enter} key.
1686 The value of @code{N} will be 0, and the program will terminate.
1687 The console window will disappear.
1688 @end enumerate
1689 @end enumerate
1690 @end ifclear
1691
1692 @node The GNAT Compilation Model
1693 @chapter The GNAT Compilation Model
1694 @cindex GNAT compilation model
1695 @cindex Compilation model
1696
1697 @menu
1698 * Source Representation::
1699 * Foreign Language Representation::
1700 * File Naming Rules::
1701 * Using Other File Names::
1702 * Alternative File Naming Schemes::
1703 * Generating Object Files::
1704 * Source Dependencies::
1705 * The Ada Library Information Files::
1706 * Binding an Ada Program::
1707 * Mixed Language Programming::
1708 @ifclear vms
1709 * Building Mixed Ada & C++ Programs::
1710 * Comparison between GNAT and C/C++ Compilation Models::
1711 @end ifclear
1712 * Comparison between GNAT and Conventional Ada Library Models::
1713 @ifset vms
1714 * Placement of temporary files::
1715 @end ifset
1716 @end menu
1717
1718 @noindent
1719 This chapter describes the compilation model used by GNAT. Although
1720 similar to that used by other languages, such as C and C++, this model
1721 is substantially different from the traditional Ada compilation models,
1722 which are based on a library. The model is initially described without
1723 reference to the library-based model. If you have not previously used an
1724 Ada compiler, you need only read the first part of this chapter. The
1725 last section describes and discusses the differences between the GNAT
1726 model and the traditional Ada compiler models. If you have used other
1727 Ada compilers, this section will help you to understand those
1728 differences, and the advantages of the GNAT model.
1729
1730 @node Source Representation
1731 @section Source Representation
1732 @cindex Latin-1
1733
1734 @noindent
1735 Ada source programs are represented in standard text files, using
1736 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1737 7-bit ASCII set, plus additional characters used for
1738 representing foreign languages (@pxref{Foreign Language Representation}
1739 for support of non-USA character sets). The format effector characters
1740 are represented using their standard ASCII encodings, as follows:
1741
1742 @table @code
1743 @item VT
1744 @findex VT
1745 Vertical tab, @code{16#0B#}
1746
1747 @item HT
1748 @findex HT
1749 Horizontal tab, @code{16#09#}
1750
1751 @item CR
1752 @findex CR
1753 Carriage return, @code{16#0D#}
1754
1755 @item LF
1756 @findex LF
1757 Line feed, @code{16#0A#}
1758
1759 @item FF
1760 @findex FF
1761 Form feed, @code{16#0C#}
1762 @end table
1763
1764 @noindent
1765 Source files are in standard text file format. In addition, GNAT will
1766 recognize a wide variety of stream formats, in which the end of
1767 physical lines is marked by any of the following sequences:
1768 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1769 in accommodating files that are imported from other operating systems.
1770
1771 @cindex End of source file
1772 @cindex Source file, end
1773 @findex SUB
1774 The end of a source file is normally represented by the physical end of
1775 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1776 recognized as signalling the end of the source file. Again, this is
1777 provided for compatibility with other operating systems where this
1778 code is used to represent the end of file.
1779
1780 Each file contains a single Ada compilation unit, including any pragmas
1781 associated with the unit. For example, this means you must place a
1782 package declaration (a package @dfn{spec}) and the corresponding body in
1783 separate files. An Ada @dfn{compilation} (which is a sequence of
1784 compilation units) is represented using a sequence of files. Similarly,
1785 you will place each subunit or child unit in a separate file.
1786
1787 @node Foreign Language Representation
1788 @section Foreign Language Representation
1789
1790 @noindent
1791 GNAT supports the standard character sets defined in Ada as well as
1792 several other non-standard character sets for use in localized versions
1793 of the compiler (@pxref{Character Set Control}).
1794 @menu
1795 * Latin-1::
1796 * Other 8-Bit Codes::
1797 * Wide Character Encodings::
1798 @end menu
1799
1800 @node Latin-1
1801 @subsection Latin-1
1802 @cindex Latin-1
1803
1804 @noindent
1805 The basic character set is Latin-1. This character set is defined by ISO
1806 standard 8859, part 1. The lower half (character codes @code{16#00#}
1807 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1808 is used to represent additional characters. These include extended letters
1809 used by European languages, such as French accents, the vowels with umlauts
1810 used in German, and the extra letter A-ring used in Swedish.
1811
1812 @findex Ada.Characters.Latin_1
1813 For a complete list of Latin-1 codes and their encodings, see the source
1814 file of library unit @code{Ada.Characters.Latin_1} in file
1815 @file{a-chlat1.ads}.
1816 You may use any of these extended characters freely in character or
1817 string literals. In addition, the extended characters that represent
1818 letters can be used in identifiers.
1819
1820 @node Other 8-Bit Codes
1821 @subsection Other 8-Bit Codes
1822
1823 @noindent
1824 GNAT also supports several other 8-bit coding schemes:
1825
1826 @table @asis
1827 @item ISO 8859-2 (Latin-2)
1828 @cindex Latin-2
1829 @cindex ISO 8859-2
1830 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1831 equivalence.
1832
1833 @item ISO 8859-3 (Latin-3)
1834 @cindex Latin-3
1835 @cindex ISO 8859-3
1836 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1837 equivalence.
1838
1839 @item ISO 8859-4 (Latin-4)
1840 @cindex Latin-4
1841 @cindex ISO 8859-4
1842 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1843 equivalence.
1844
1845 @item ISO 8859-5 (Cyrillic)
1846 @cindex ISO 8859-5
1847 @cindex Cyrillic
1848 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1849 lowercase equivalence.
1850
1851 @item ISO 8859-15 (Latin-9)
1852 @cindex ISO 8859-15
1853 @cindex Latin-9
1854 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1855 lowercase equivalence
1856
1857 @item IBM PC (code page 437)
1858 @cindex code page 437
1859 This code page is the normal default for PCs in the U.S. It corresponds
1860 to the original IBM PC character set. This set has some, but not all, of
1861 the extended Latin-1 letters, but these letters do not have the same
1862 encoding as Latin-1. In this mode, these letters are allowed in
1863 identifiers with uppercase and lowercase equivalence.
1864
1865 @item IBM PC (code page 850)
1866 @cindex code page 850
1867 This code page is a modification of 437 extended to include all the
1868 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1869 mode, all these letters are allowed in identifiers with uppercase and
1870 lowercase equivalence.
1871
1872 @item Full Upper 8-bit
1873 Any character in the range 80-FF allowed in identifiers, and all are
1874 considered distinct. In other words, there are no uppercase and lowercase
1875 equivalences in this range. This is useful in conjunction with
1876 certain encoding schemes used for some foreign character sets (e.g.,
1877 the typical method of representing Chinese characters on the PC).
1878
1879 @item No Upper-Half
1880 No upper-half characters in the range 80-FF are allowed in identifiers.
1881 This gives Ada 83 compatibility for identifier names.
1882 @end table
1883
1884 @noindent
1885 For precise data on the encodings permitted, and the uppercase and lowercase
1886 equivalences that are recognized, see the file @file{csets.adb} in
1887 the GNAT compiler sources. You will need to obtain a full source release
1888 of GNAT to obtain this file.
1889
1890 @node Wide Character Encodings
1891 @subsection Wide Character Encodings
1892
1893 @noindent
1894 GNAT allows wide character codes to appear in character and string
1895 literals, and also optionally in identifiers, by means of the following
1896 possible encoding schemes:
1897
1898 @table @asis
1899
1900 @item Hex Coding
1901 In this encoding, a wide character is represented by the following five
1902 character sequence:
1903
1904 @smallexample
1905 ESC a b c d
1906 @end smallexample
1907
1908 @noindent
1909 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1910 characters (using uppercase letters) of the wide character code. For
1911 example, ESC A345 is used to represent the wide character with code
1912 @code{16#A345#}.
1913 This scheme is compatible with use of the full Wide_Character set.
1914
1915 @item Upper-Half Coding
1916 @cindex Upper-Half Coding
1917 The wide character with encoding @code{16#abcd#} where the upper bit is on
1918 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1919 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1920 character, but is not required to be in the upper half. This method can
1921 be also used for shift-JIS or EUC, where the internal coding matches the
1922 external coding.
1923
1924 @item Shift JIS Coding
1925 @cindex Shift JIS Coding
1926 A wide character is represented by a two-character sequence,
1927 @code{16#ab#} and
1928 @code{16#cd#}, with the restrictions described for upper-half encoding as
1929 described above. The internal character code is the corresponding JIS
1930 character according to the standard algorithm for Shift-JIS
1931 conversion. Only characters defined in the JIS code set table can be
1932 used with this encoding method.
1933
1934 @item EUC Coding
1935 @cindex EUC Coding
1936 A wide character is represented by a two-character sequence
1937 @code{16#ab#} and
1938 @code{16#cd#}, with both characters being in the upper half. The internal
1939 character code is the corresponding JIS character according to the EUC
1940 encoding algorithm. Only characters defined in the JIS code set table
1941 can be used with this encoding method.
1942
1943 @item UTF-8 Coding
1944 A wide character is represented using
1945 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1946 10646-1/Am.2. Depending on the character value, the representation
1947 is a one, two, or three byte sequence:
1948 @smallexample
1949 @iftex
1950 @leftskip=.7cm
1951 @end iftex
1952 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1953 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1954 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1955
1956 @end smallexample
1957
1958 @noindent
1959 where the @var{xxx} bits correspond to the left-padded bits of the
1960 16-bit character value. Note that all lower half ASCII characters
1961 are represented as ASCII bytes and all upper half characters and
1962 other wide characters are represented as sequences of upper-half
1963 (The full UTF-8 scheme allows for encoding 31-bit characters as
1964 6-byte sequences, but in this implementation, all UTF-8 sequences
1965 of four or more bytes length will be treated as illegal).
1966 @item Brackets Coding
1967 In this encoding, a wide character is represented by the following eight
1968 character sequence:
1969
1970 @smallexample
1971 [ " a b c d " ]
1972 @end smallexample
1973
1974 @noindent
1975 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1976 characters (using uppercase letters) of the wide character code. For
1977 example, [``A345''] is used to represent the wide character with code
1978 @code{16#A345#}. It is also possible (though not required) to use the
1979 Brackets coding for upper half characters. For example, the code
1980 @code{16#A3#} can be represented as @code{[``A3'']}.
1981
1982 This scheme is compatible with use of the full Wide_Character set,
1983 and is also the method used for wide character encoding in the standard
1984 ACVC (Ada Compiler Validation Capability) test suite distributions.
1985
1986 @end table
1987
1988 @noindent
1989 Note: Some of these coding schemes do not permit the full use of the
1990 Ada character set. For example, neither Shift JIS, nor EUC allow the
1991 use of the upper half of the Latin-1 set.
1992
1993 @node File Naming Rules
1994 @section File Naming Rules
1995
1996 @noindent
1997 The default file name is determined by the name of the unit that the
1998 file contains. The name is formed by taking the full expanded name of
1999 the unit and replacing the separating dots with hyphens and using
2000 ^lowercase^uppercase^ for all letters.
2001
2002 An exception arises if the file name generated by the above rules starts
2003 with one of the characters
2004 @ifset vms
2005 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2006 @end ifset
2007 @ifclear vms
2008 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2009 @end ifclear
2010 and the second character is a
2011 minus. In this case, the character ^tilde^dollar sign^ is used in place
2012 of the minus. The reason for this special rule is to avoid clashes with
2013 the standard names for child units of the packages System, Ada,
2014 Interfaces, and GNAT, which use the prefixes
2015 @ifset vms
2016 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2017 @end ifset
2018 @ifclear vms
2019 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2020 @end ifclear
2021 respectively.
2022
2023 The file extension is @file{.ads} for a spec and
2024 @file{.adb} for a body. The following list shows some
2025 examples of these rules.
2026
2027 @table @file
2028 @item main.ads
2029 Main (spec)
2030 @item main.adb
2031 Main (body)
2032 @item arith_functions.ads
2033 Arith_Functions (package spec)
2034 @item arith_functions.adb
2035 Arith_Functions (package body)
2036 @item func-spec.ads
2037 Func.Spec (child package spec)
2038 @item func-spec.adb
2039 Func.Spec (child package body)
2040 @item main-sub.adb
2041 Sub (subunit of Main)
2042 @item ^a~bad.adb^A$BAD.ADB^
2043 A.Bad (child package body)
2044 @end table
2045
2046 @noindent
2047 Following these rules can result in excessively long
2048 file names if corresponding
2049 unit names are long (for example, if child units or subunits are
2050 heavily nested). An option is available to shorten such long file names
2051 (called file name ``krunching''). This may be particularly useful when
2052 programs being developed with GNAT are to be used on operating systems
2053 with limited file name lengths. @xref{Using gnatkr}.
2054
2055 Of course, no file shortening algorithm can guarantee uniqueness over
2056 all possible unit names; if file name krunching is used, it is your
2057 responsibility to ensure no name clashes occur. Alternatively you
2058 can specify the exact file names that you want used, as described
2059 in the next section. Finally, if your Ada programs are migrating from a
2060 compiler with a different naming convention, you can use the gnatchop
2061 utility to produce source files that follow the GNAT naming conventions.
2062 (For details @pxref{Renaming Files Using gnatchop}.)
2063
2064 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2065 systems, case is not significant. So for example on @code{Windows XP}
2066 if the canonical name is @code{main-sub.adb}, you can use the file name
2067 @code{Main-Sub.adb} instead. However, case is significant for other
2068 operating systems, so for example, if you want to use other than
2069 canonically cased file names on a Unix system, you need to follow
2070 the procedures described in the next section.
2071
2072 @node Using Other File Names
2073 @section Using Other File Names
2074 @cindex File names
2075
2076 @noindent
2077 In the previous section, we have described the default rules used by
2078 GNAT to determine the file name in which a given unit resides. It is
2079 often convenient to follow these default rules, and if you follow them,
2080 the compiler knows without being explicitly told where to find all
2081 the files it needs.
2082
2083 However, in some cases, particularly when a program is imported from
2084 another Ada compiler environment, it may be more convenient for the
2085 programmer to specify which file names contain which units. GNAT allows
2086 arbitrary file names to be used by means of the Source_File_Name pragma.
2087 The form of this pragma is as shown in the following examples:
2088 @cindex Source_File_Name pragma
2089
2090 @smallexample @c ada
2091 @cartouche
2092 pragma Source_File_Name (My_Utilities.Stacks,
2093   Spec_File_Name => "myutilst_a.ada");
2094 pragma Source_File_name (My_Utilities.Stacks,
2095   Body_File_Name => "myutilst.ada");
2096 @end cartouche
2097 @end smallexample
2098
2099 @noindent
2100 As shown in this example, the first argument for the pragma is the unit
2101 name (in this example a child unit). The second argument has the form
2102 of a named association. The identifier
2103 indicates whether the file name is for a spec or a body;
2104 the file name itself is given by a string literal.
2105
2106 The source file name pragma is a configuration pragma, which means that
2107 normally it will be placed in the @file{gnat.adc}
2108 file used to hold configuration
2109 pragmas that apply to a complete compilation environment.
2110 For more details on how the @file{gnat.adc} file is created and used
2111 see @ref{Handling of Configuration Pragmas}.
2112 @cindex @file{gnat.adc}
2113
2114 @ifclear vms
2115 GNAT allows completely arbitrary file names to be specified using the
2116 source file name pragma. However, if the file name specified has an
2117 extension other than @file{.ads} or @file{.adb} it is necessary to use
2118 a special syntax when compiling the file. The name in this case must be
2119 preceded by the special sequence @option{-x} followed by a space and the name
2120 of the language, here @code{ada}, as in:
2121
2122 @smallexample
2123 $ gcc -c -x ada peculiar_file_name.sim
2124 @end smallexample
2125 @end ifclear
2126
2127 @noindent
2128 @command{gnatmake} handles non-standard file names in the usual manner (the
2129 non-standard file name for the main program is simply used as the
2130 argument to gnatmake). Note that if the extension is also non-standard,
2131 then it must be included in the @command{gnatmake} command, it may not
2132 be omitted.
2133
2134 @node Alternative File Naming Schemes
2135 @section Alternative File Naming Schemes
2136 @cindex File naming schemes, alternative
2137 @cindex File names
2138
2139 In the previous section, we described the use of the @code{Source_File_Name}
2140 pragma to allow arbitrary names to be assigned to individual source files.
2141 However, this approach requires one pragma for each file, and especially in
2142 large systems can result in very long @file{gnat.adc} files, and also create
2143 a maintenance problem.
2144
2145 GNAT also provides a facility for specifying systematic file naming schemes
2146 other than the standard default naming scheme previously described. An
2147 alternative scheme for naming is specified by the use of
2148 @code{Source_File_Name} pragmas having the following format:
2149 @cindex Source_File_Name pragma
2150
2151 @smallexample @c ada
2152 pragma Source_File_Name (
2153    Spec_File_Name  => FILE_NAME_PATTERN
2154  @r{[},Casing          => CASING_SPEC@r{]}
2155  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2156
2157 pragma Source_File_Name (
2158    Body_File_Name  => FILE_NAME_PATTERN
2159  @r{[},Casing          => CASING_SPEC@r{]}
2160  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2161
2162 pragma Source_File_Name (
2163    Subunit_File_Name  => FILE_NAME_PATTERN
2164  @r{[},Casing             => CASING_SPEC@r{]}
2165  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2166
2167 FILE_NAME_PATTERN ::= STRING_LITERAL
2168 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2169 @end smallexample
2170
2171 @noindent
2172 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2173 It contains a single asterisk character, and the unit name is substituted
2174 systematically for this asterisk. The optional parameter
2175 @code{Casing} indicates
2176 whether the unit name is to be all upper-case letters, all lower-case letters,
2177 or mixed-case. If no
2178 @code{Casing} parameter is used, then the default is all
2179 ^lower-case^upper-case^.
2180
2181 The optional @code{Dot_Replacement} string is used to replace any periods
2182 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2183 argument is used then separating dots appear unchanged in the resulting
2184 file name.
2185 Although the above syntax indicates that the
2186 @code{Casing} argument must appear
2187 before the @code{Dot_Replacement} argument, but it
2188 is also permissible to write these arguments in the opposite order.
2189
2190 As indicated, it is possible to specify different naming schemes for
2191 bodies, specs, and subunits. Quite often the rule for subunits is the
2192 same as the rule for bodies, in which case, there is no need to give
2193 a separate @code{Subunit_File_Name} rule, and in this case the
2194 @code{Body_File_name} rule is used for subunits as well.
2195
2196 The separate rule for subunits can also be used to implement the rather
2197 unusual case of a compilation environment (e.g.@: a single directory) which
2198 contains a subunit and a child unit with the same unit name. Although
2199 both units cannot appear in the same partition, the Ada Reference Manual
2200 allows (but does not require) the possibility of the two units coexisting
2201 in the same environment.
2202
2203 The file name translation works in the following steps:
2204
2205 @itemize @bullet
2206
2207 @item
2208 If there is a specific @code{Source_File_Name} pragma for the given unit,
2209 then this is always used, and any general pattern rules are ignored.
2210
2211 @item
2212 If there is a pattern type @code{Source_File_Name} pragma that applies to
2213 the unit, then the resulting file name will be used if the file exists. If
2214 more than one pattern matches, the latest one will be tried first, and the
2215 first attempt resulting in a reference to a file that exists will be used.
2216
2217 @item
2218 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2219 for which the corresponding file exists, then the standard GNAT default
2220 naming rules are used.
2221
2222 @end itemize
2223
2224 @noindent
2225 As an example of the use of this mechanism, consider a commonly used scheme
2226 in which file names are all lower case, with separating periods copied
2227 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2228 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2229 two pragmas appear:
2230
2231 @smallexample @c ada
2232 pragma Source_File_Name
2233   (Spec_File_Name => "*.1.ada");
2234 pragma Source_File_Name
2235   (Body_File_Name => "*.2.ada");
2236 @end smallexample
2237
2238 @noindent
2239 The default GNAT scheme is actually implemented by providing the following
2240 default pragmas internally:
2241
2242 @smallexample @c ada
2243 pragma Source_File_Name
2244   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2245 pragma Source_File_Name
2246   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2247 @end smallexample
2248
2249 @noindent
2250 Our final example implements a scheme typically used with one of the
2251 Ada 83 compilers, where the separator character for subunits was ``__''
2252 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2253 by adding @file{.ADA}, and subunits by
2254 adding @file{.SEP}. All file names were
2255 upper case. Child units were not present of course since this was an
2256 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2257 the same double underscore separator for child units.
2258
2259 @smallexample @c ada
2260 pragma Source_File_Name
2261   (Spec_File_Name => "*_.ADA",
2262    Dot_Replacement => "__",
2263    Casing = Uppercase);
2264 pragma Source_File_Name
2265   (Body_File_Name => "*.ADA",
2266    Dot_Replacement => "__",
2267    Casing = Uppercase);
2268 pragma Source_File_Name
2269   (Subunit_File_Name => "*.SEP",
2270    Dot_Replacement => "__",
2271    Casing = Uppercase);
2272 @end smallexample
2273
2274 @node Generating Object Files
2275 @section Generating Object Files
2276
2277 @noindent
2278 An Ada program consists of a set of source files, and the first step in
2279 compiling the program is to generate the corresponding object files.
2280 These are generated by compiling a subset of these source files.
2281 The files you need to compile are the following:
2282
2283 @itemize @bullet
2284 @item
2285 If a package spec has no body, compile the package spec to produce the
2286 object file for the package.
2287
2288 @item
2289 If a package has both a spec and a body, compile the body to produce the
2290 object file for the package. The source file for the package spec need
2291 not be compiled in this case because there is only one object file, which
2292 contains the code for both the spec and body of the package.
2293
2294 @item
2295 For a subprogram, compile the subprogram body to produce the object file
2296 for the subprogram. The spec, if one is present, is as usual in a
2297 separate file, and need not be compiled.
2298
2299 @item
2300 @cindex Subunits
2301 In the case of subunits, only compile the parent unit. A single object
2302 file is generated for the entire subunit tree, which includes all the
2303 subunits.
2304
2305 @item
2306 Compile child units independently of their parent units
2307 (though, of course, the spec of all the ancestor unit must be present in order
2308 to compile a child unit).
2309
2310 @item
2311 @cindex Generics
2312 Compile generic units in the same manner as any other units. The object
2313 files in this case are small dummy files that contain at most the
2314 flag used for elaboration checking. This is because GNAT always handles generic
2315 instantiation by means of macro expansion. However, it is still necessary to
2316 compile generic units, for dependency checking and elaboration purposes.
2317 @end itemize
2318
2319 @noindent
2320 The preceding rules describe the set of files that must be compiled to
2321 generate the object files for a program. Each object file has the same
2322 name as the corresponding source file, except that the extension is
2323 @file{.o} as usual.
2324
2325 You may wish to compile other files for the purpose of checking their
2326 syntactic and semantic correctness. For example, in the case where a
2327 package has a separate spec and body, you would not normally compile the
2328 spec. However, it is convenient in practice to compile the spec to make
2329 sure it is error-free before compiling clients of this spec, because such
2330 compilations will fail if there is an error in the spec.
2331
2332 GNAT provides an option for compiling such files purely for the
2333 purposes of checking correctness; such compilations are not required as
2334 part of the process of building a program. To compile a file in this
2335 checking mode, use the @option{-gnatc} switch.
2336
2337 @node Source Dependencies
2338 @section Source Dependencies
2339
2340 @noindent
2341 A given object file clearly depends on the source file which is compiled
2342 to produce it. Here we are using @dfn{depends} in the sense of a typical
2343 @code{make} utility; in other words, an object file depends on a source
2344 file if changes to the source file require the object file to be
2345 recompiled.
2346 In addition to this basic dependency, a given object may depend on
2347 additional source files as follows:
2348
2349 @itemize @bullet
2350 @item
2351 If a file being compiled @code{with}'s a unit @var{X}, the object file
2352 depends on the file containing the spec of unit @var{X}. This includes
2353 files that are @code{with}'ed implicitly either because they are parents
2354 of @code{with}'ed child units or they are run-time units required by the
2355 language constructs used in a particular unit.
2356
2357 @item
2358 If a file being compiled instantiates a library level generic unit, the
2359 object file depends on both the spec and body files for this generic
2360 unit.
2361
2362 @item
2363 If a file being compiled instantiates a generic unit defined within a
2364 package, the object file depends on the body file for the package as
2365 well as the spec file.
2366
2367 @item
2368 @findex Inline
2369 @cindex @option{-gnatn} switch
2370 If a file being compiled contains a call to a subprogram for which
2371 pragma @code{Inline} applies and inlining is activated with the
2372 @option{-gnatn} switch, the object file depends on the file containing the
2373 body of this subprogram as well as on the file containing the spec. Note
2374 that for inlining to actually occur as a result of the use of this switch,
2375 it is necessary to compile in optimizing mode.
2376
2377 @cindex @option{-gnatN} switch
2378 The use of @option{-gnatN} activates  inlining optimization
2379 that is performed by the front end of the compiler. This inlining does
2380 not require that the code generation be optimized. Like @option{-gnatn},
2381 the use of this switch generates additional dependencies.
2382
2383 When using a gcc-based back end (in practice this means using any version
2384 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2385 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2386 Historically front end inlining was more extensive than the gcc back end
2387 inlining, but that is no longer the case.
2388
2389 @item
2390 If an object file @file{O} depends on the proper body of a subunit through
2391 inlining or instantiation, it depends on the parent unit of the subunit.
2392 This means that any modification of the parent unit or one of its subunits
2393 affects the compilation of @file{O}.
2394
2395 @item
2396 The object file for a parent unit depends on all its subunit body files.
2397
2398 @item
2399 The previous two rules meant that for purposes of computing dependencies and
2400 recompilation, a body and all its subunits are treated as an indivisible whole.
2401
2402 @noindent
2403 These rules are applied transitively: if unit @code{A} @code{with}'s
2404 unit @code{B}, whose elaboration calls an inlined procedure in package
2405 @code{C}, the object file for unit @code{A} will depend on the body of
2406 @code{C}, in file @file{c.adb}.
2407
2408 The set of dependent files described by these rules includes all the
2409 files on which the unit is semantically dependent, as dictated by the
2410 Ada language standard. However, it is a superset of what the
2411 standard describes, because it includes generic, inline, and subunit
2412 dependencies.
2413
2414 An object file must be recreated by recompiling the corresponding source
2415 file if any of the source files on which it depends are modified. For
2416 example, if the @code{make} utility is used to control compilation,
2417 the rule for an Ada object file must mention all the source files on
2418 which the object file depends, according to the above definition.
2419 The determination of the necessary
2420 recompilations is done automatically when one uses @command{gnatmake}.
2421 @end itemize
2422
2423 @node The Ada Library Information Files
2424 @section The Ada Library Information Files
2425 @cindex Ada Library Information files
2426 @cindex @file{ALI} files
2427
2428 @noindent
2429 Each compilation actually generates two output files. The first of these
2430 is the normal object file that has a @file{.o} extension. The second is a
2431 text file containing full dependency information. It has the same
2432 name as the source file, but an @file{.ali} extension.
2433 This file is known as the Ada Library Information (@file{ALI}) file.
2434 The following information is contained in the @file{ALI} file.
2435
2436 @itemize @bullet
2437 @item
2438 Version information (indicates which version of GNAT was used to compile
2439 the unit(s) in question)
2440
2441 @item
2442 Main program information (including priority and time slice settings,
2443 as well as the wide character encoding used during compilation).
2444
2445 @item
2446 List of arguments used in the @command{gcc} command for the compilation
2447
2448 @item
2449 Attributes of the unit, including configuration pragmas used, an indication
2450 of whether the compilation was successful, exception model used etc.
2451
2452 @item
2453 A list of relevant restrictions applying to the unit (used for consistency)
2454 checking.
2455
2456 @item
2457 Categorization information (e.g.@: use of pragma @code{Pure}).
2458
2459 @item
2460 Information on all @code{with}'ed units, including presence of
2461 @code{Elaborate} or @code{Elaborate_All} pragmas.
2462
2463 @item
2464 Information from any @code{Linker_Options} pragmas used in the unit
2465
2466 @item
2467 Information on the use of @code{Body_Version} or @code{Version}
2468 attributes in the unit.
2469
2470 @item
2471 Dependency information. This is a list of files, together with
2472 time stamp and checksum information. These are files on which
2473 the unit depends in the sense that recompilation is required
2474 if any of these units are modified.
2475
2476 @item
2477 Cross-reference data. Contains information on all entities referenced
2478 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2479 provide cross-reference information.
2480
2481 @end itemize
2482
2483 @noindent
2484 For a full detailed description of the format of the @file{ALI} file,
2485 see the source of the body of unit @code{Lib.Writ}, contained in file
2486 @file{lib-writ.adb} in the GNAT compiler sources.
2487
2488 @node Binding an Ada Program
2489 @section Binding an Ada Program
2490
2491 @noindent
2492 When using languages such as C and C++, once the source files have been
2493 compiled the only remaining step in building an executable program
2494 is linking the object modules together. This means that it is possible to
2495 link an inconsistent version of a program, in which two units have
2496 included different versions of the same header.
2497
2498 The rules of Ada do not permit such an inconsistent program to be built.
2499 For example, if two clients have different versions of the same package,
2500 it is illegal to build a program containing these two clients.
2501 These rules are enforced by the GNAT binder, which also determines an
2502 elaboration order consistent with the Ada rules.
2503
2504 The GNAT binder is run after all the object files for a program have
2505 been created. It is given the name of the main program unit, and from
2506 this it determines the set of units required by the program, by reading the
2507 corresponding ALI files. It generates error messages if the program is
2508 inconsistent or if no valid order of elaboration exists.
2509
2510 If no errors are detected, the binder produces a main program, in Ada by
2511 default, that contains calls to the elaboration procedures of those
2512 compilation unit that require them, followed by
2513 a call to the main program. This Ada program is compiled to generate the
2514 object file for the main program. The name of
2515 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2516 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2517 main program unit.
2518
2519 Finally, the linker is used to build the resulting executable program,
2520 using the object from the main program from the bind step as well as the
2521 object files for the Ada units of the program.
2522
2523 @node Mixed Language Programming
2524 @section Mixed Language Programming
2525 @cindex Mixed Language Programming
2526
2527 @noindent
2528 This section describes how to develop a mixed-language program,
2529 specifically one that comprises units in both Ada and C.
2530
2531 @menu
2532 * Interfacing to C::
2533 * Calling Conventions::
2534 @end menu
2535
2536 @node Interfacing to C
2537 @subsection Interfacing to C
2538 @noindent
2539 Interfacing Ada with a foreign language such as C involves using
2540 compiler directives to import and/or export entity definitions in each
2541 language---using @code{extern} statements in C, for instance, and the
2542 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2543 A full treatment of these topics is provided in Appendix B, section 1
2544 of the Ada Reference Manual.
2545
2546 There are two ways to build a program using GNAT that contains some Ada
2547 sources and some foreign language sources, depending on whether or not
2548 the main subprogram is written in Ada.  Here is a source example with
2549 the main subprogram in Ada:
2550
2551 @smallexample
2552 /* file1.c */
2553 #include <stdio.h>
2554
2555 void print_num (int num)
2556 @{
2557   printf ("num is %d.\n", num);
2558   return;
2559 @}
2560
2561 /* file2.c */
2562
2563 /* num_from_Ada is declared in my_main.adb */
2564 extern int num_from_Ada;
2565
2566 int get_num (void)
2567 @{
2568   return num_from_Ada;
2569 @}
2570 @end smallexample
2571
2572 @smallexample @c ada
2573 --  my_main.adb
2574 procedure My_Main is
2575
2576    --  Declare then export an Integer entity called num_from_Ada
2577    My_Num : Integer := 10;
2578    pragma Export (C, My_Num, "num_from_Ada");
2579
2580    --  Declare an Ada function spec for Get_Num, then use
2581    --  C function get_num for the implementation.
2582    function Get_Num return Integer;
2583    pragma Import (C, Get_Num, "get_num");
2584
2585    --  Declare an Ada procedure spec for Print_Num, then use
2586    --  C function print_num for the implementation.
2587    procedure Print_Num (Num : Integer);
2588    pragma Import (C, Print_Num, "print_num");
2589
2590 begin
2591    Print_Num (Get_Num);
2592 end My_Main;
2593 @end smallexample
2594
2595 @enumerate
2596 @item
2597 To build this example, first compile the foreign language files to
2598 generate object files:
2599 @smallexample
2600 ^gcc -c file1.c^gcc -c FILE1.C^
2601 ^gcc -c file2.c^gcc -c FILE2.C^
2602 @end smallexample
2603
2604 @item
2605 Then, compile the Ada units to produce a set of object files and ALI
2606 files:
2607 @smallexample
2608 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2609 @end smallexample
2610
2611 @item
2612 Run the Ada binder on the Ada main program:
2613 @smallexample
2614 gnatbind my_main.ali
2615 @end smallexample
2616
2617 @item
2618 Link the Ada main program, the Ada objects and the other language
2619 objects:
2620 @smallexample
2621 gnatlink my_main.ali file1.o file2.o
2622 @end smallexample
2623 @end enumerate
2624
2625 The last three steps can be grouped in a single command:
2626 @smallexample
2627 gnatmake my_main.adb -largs file1.o file2.o
2628 @end smallexample
2629
2630 @cindex Binder output file
2631 @noindent
2632 If the main program is in a language other than Ada, then you may have
2633 more than one entry point into the Ada subsystem. You must use a special
2634 binder option to generate callable routines that initialize and
2635 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2636 Calls to the initialization and finalization routines must be inserted
2637 in the main program, or some other appropriate point in the code. The
2638 call to initialize the Ada units must occur before the first Ada
2639 subprogram is called, and the call to finalize the Ada units must occur
2640 after the last Ada subprogram returns. The binder will place the
2641 initialization and finalization subprograms into the
2642 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2643 sources.  To illustrate, we have the following example:
2644
2645 @smallexample
2646 /* main.c */
2647 extern void adainit (void);
2648 extern void adafinal (void);
2649 extern int add (int, int);
2650 extern int sub (int, int);
2651
2652 int main (int argc, char *argv[])
2653 @{
2654   int a = 21, b = 7;
2655
2656   adainit();
2657
2658   /* Should print "21 + 7 = 28" */
2659   printf ("%d + %d = %d\n", a, b, add (a, b));
2660   /* Should print "21 - 7 = 14" */
2661   printf ("%d - %d = %d\n", a, b, sub (a, b));
2662
2663   adafinal();
2664 @}
2665 @end smallexample
2666
2667 @smallexample @c ada
2668 --  unit1.ads
2669 package Unit1 is
2670    function Add (A, B : Integer) return Integer;
2671    pragma Export (C, Add, "add");
2672 end Unit1;
2673
2674 --  unit1.adb
2675 package body Unit1 is
2676    function Add (A, B : Integer) return Integer is
2677    begin
2678       return A + B;
2679    end Add;
2680 end Unit1;
2681
2682 --  unit2.ads
2683 package Unit2 is
2684    function Sub (A, B : Integer) return Integer;
2685    pragma Export (C, Sub, "sub");
2686 end Unit2;
2687
2688 --  unit2.adb
2689 package body Unit2 is
2690    function Sub (A, B : Integer) return Integer is
2691    begin
2692       return A - B;
2693    end Sub;
2694 end Unit2;
2695 @end smallexample
2696
2697 @enumerate
2698 @item
2699 The build procedure for this application is similar to the last
2700 example's.  First, compile the foreign language files to generate object
2701 files:
2702 @smallexample
2703 ^gcc -c main.c^gcc -c main.c^
2704 @end smallexample
2705
2706 @item
2707 Next, compile the Ada units to produce a set of object files and ALI
2708 files:
2709 @smallexample
2710 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2711 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2712 @end smallexample
2713
2714 @item
2715 Run the Ada binder on every generated ALI file.  Make sure to use the
2716 @option{-n} option to specify a foreign main program:
2717 @smallexample
2718 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2719 @end smallexample
2720
2721 @item
2722 Link the Ada main program, the Ada objects and the foreign language
2723 objects. You need only list the last ALI file here:
2724 @smallexample
2725 gnatlink unit2.ali main.o -o exec_file
2726 @end smallexample
2727
2728 This procedure yields a binary executable called @file{exec_file}.
2729 @end enumerate
2730
2731 @noindent
2732 Depending on the circumstances (for example when your non-Ada main object
2733 does not provide symbol @code{main}), you may also need to instruct the
2734 GNAT linker not to include the standard startup objects by passing the
2735 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2736
2737 @node Calling Conventions
2738 @subsection Calling Conventions
2739 @cindex Foreign Languages
2740 @cindex Calling Conventions
2741 GNAT follows standard calling sequence conventions and will thus interface
2742 to any other language that also follows these conventions. The following
2743 Convention identifiers are recognized by GNAT:
2744
2745 @table @code
2746 @cindex Interfacing to Ada
2747 @cindex Other Ada compilers
2748 @cindex Convention Ada
2749 @item Ada
2750 This indicates that the standard Ada calling sequence will be
2751 used and all Ada data items may be passed without any limitations in the
2752 case where GNAT is used to generate both the caller and callee. It is also
2753 possible to mix GNAT generated code and code generated by another Ada
2754 compiler. In this case, the data types should be restricted to simple
2755 cases, including primitive types. Whether complex data types can be passed
2756 depends on the situation. Probably it is safe to pass simple arrays, such
2757 as arrays of integers or floats. Records may or may not work, depending
2758 on whether both compilers lay them out identically. Complex structures
2759 involving variant records, access parameters, tasks, or protected types,
2760 are unlikely to be able to be passed.
2761
2762 Note that in the case of GNAT running
2763 on a platform that supports HP Ada 83, a higher degree of compatibility
2764 can be guaranteed, and in particular records are layed out in an identical
2765 manner in the two compilers. Note also that if output from two different
2766 compilers is mixed, the program is responsible for dealing with elaboration
2767 issues. Probably the safest approach is to write the main program in the
2768 version of Ada other than GNAT, so that it takes care of its own elaboration
2769 requirements, and then call the GNAT-generated adainit procedure to ensure
2770 elaboration of the GNAT components. Consult the documentation of the other
2771 Ada compiler for further details on elaboration.
2772
2773 However, it is not possible to mix the tasking run time of GNAT and
2774 HP Ada 83, All the tasking operations must either be entirely within
2775 GNAT compiled sections of the program, or entirely within HP Ada 83
2776 compiled sections of the program.
2777
2778 @cindex Interfacing to Assembly
2779 @cindex Convention Assembler
2780 @item Assembler
2781 Specifies assembler as the convention. In practice this has the
2782 same effect as convention Ada (but is not equivalent in the sense of being
2783 considered the same convention).
2784
2785 @cindex Convention Asm
2786 @findex Asm
2787 @item Asm
2788 Equivalent to Assembler.
2789
2790 @cindex Interfacing to COBOL
2791 @cindex Convention COBOL
2792 @findex COBOL
2793 @item COBOL
2794 Data will be passed according to the conventions described
2795 in section B.4 of the Ada Reference Manual.
2796
2797 @findex C
2798 @cindex Interfacing to C
2799 @cindex Convention C
2800 @item C
2801 Data will be passed according to the conventions described
2802 in section B.3 of the Ada Reference Manual.
2803
2804 A note on interfacing to a C ``varargs'' function:
2805 @findex C varargs function
2806 @cindex Interfacing to C varargs function
2807 @cindex varargs function interfaces
2808
2809 @itemize @bullet
2810 @item
2811 In C, @code{varargs} allows a function to take a variable number of
2812 arguments. There is no direct equivalent in this to Ada. One
2813 approach that can be used is to create a C wrapper for each
2814 different profile and then interface to this C wrapper. For
2815 example, to print an @code{int} value using @code{printf},
2816 create a C function @code{printfi} that takes two arguments, a
2817 pointer to a string and an int, and calls @code{printf}.
2818 Then in the Ada program, use pragma @code{Import} to
2819 interface to @code{printfi}.
2820
2821 @item
2822 It may work on some platforms to directly interface to
2823 a @code{varargs} function by providing a specific Ada profile
2824 for a particular call. However, this does not work on
2825 all platforms, since there is no guarantee that the
2826 calling sequence for a two argument normal C function
2827 is the same as for calling a @code{varargs} C function with
2828 the same two arguments.
2829 @end itemize
2830
2831 @cindex Convention Default
2832 @findex Default
2833 @item Default
2834 Equivalent to C.
2835
2836 @cindex Convention External
2837 @findex External
2838 @item External
2839 Equivalent to C.
2840
2841 @ifclear vms
2842 @findex C++
2843 @cindex Interfacing to C++
2844 @cindex Convention C++
2845 @item C_Plus_Plus (or CPP)
2846 This stands for C++. For most purposes this is identical to C.
2847 See the separate description of the specialized GNAT pragmas relating to
2848 C++ interfacing for further details.
2849 @end ifclear
2850
2851 @findex Fortran
2852 @cindex Interfacing to Fortran
2853 @cindex Convention Fortran
2854 @item Fortran
2855 Data will be passed according to the conventions described
2856 in section B.5 of the Ada Reference Manual.
2857
2858 @item Intrinsic
2859 This applies to an intrinsic operation, as defined in the Ada
2860 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2861 this means that the body of the subprogram is provided by the compiler itself,
2862 usually by means of an efficient code sequence, and that the user does not
2863 supply an explicit body for it. In an application program, the pragma may
2864 be applied to the following sets of names:
2865
2866 @itemize @bullet
2867 @item
2868 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2869 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2870 two formal parameters. The
2871 first one must be a signed integer type or a modular type with a binary
2872 modulus, and the second parameter must be of type Natural.
2873 The return type must be the same as the type of the first argument. The size
2874 of this type can only be 8, 16, 32, or 64.
2875
2876 @item
2877 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2878 The corresponding operator declaration must have parameters and result type
2879 that have the same root numeric type (for example, all three are long_float
2880 types). This simplifies the definition of operations that use type checking
2881 to perform dimensional checks:
2882
2883 @smallexample @c ada
2884 type Distance is new Long_Float;
2885 type Time     is new Long_Float;
2886 type Velocity is new Long_Float;
2887 function "/" (D : Distance; T : Time)
2888   return Velocity;
2889 pragma Import (Intrinsic, "/");
2890 @end smallexample
2891
2892 @noindent
2893 This common idiom is often programmed with a generic definition and an
2894 explicit body. The pragma makes it simpler to introduce such declarations.
2895 It incurs no overhead in compilation time or code size, because it is
2896 implemented as a single machine instruction.
2897
2898 @item
2899 General subprogram entities, to bind an Ada subprogram declaration to
2900 a compiler builtin by name with back-ends where such interfaces are
2901 available. A typical example is the set of ``__builtin'' functions
2902 exposed by the GCC back-end, as in the following example:
2903
2904 @smallexample @c ada
2905    function builtin_sqrt (F : Float) return Float;
2906    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2907 @end smallexample
2908
2909 Most of the GCC builtins are accessible this way, and as for other
2910 import conventions (e.g. C), it is the user's responsibility to ensure
2911 that the Ada subprogram profile matches the underlying builtin
2912 expectations.
2913 @end itemize
2914
2915 @noindent
2916
2917 @ifset unw
2918 @findex Stdcall
2919 @cindex Convention Stdcall
2920 @item Stdcall
2921 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2922 and specifies that the @code{Stdcall} calling sequence will be used,
2923 as defined by the NT API. Nevertheless, to ease building
2924 cross-platform bindings this convention will be handled as a @code{C} calling
2925 convention on non-Windows platforms.
2926
2927 @findex DLL
2928 @cindex Convention DLL
2929 @item DLL
2930 This is equivalent to @code{Stdcall}.
2931
2932 @findex Win32
2933 @cindex Convention Win32
2934 @item Win32
2935 This is equivalent to @code{Stdcall}.
2936 @end ifset
2937
2938 @findex Stubbed
2939 @cindex Convention Stubbed
2940 @item Stubbed
2941 This is a special convention that indicates that the compiler
2942 should provide a stub body that raises @code{Program_Error}.
2943 @end table
2944
2945 @noindent
2946 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2947 that can be used to parametrize conventions and allow additional synonyms
2948 to be specified. For example if you have legacy code in which the convention
2949 identifier Fortran77 was used for Fortran, you can use the configuration
2950 pragma:
2951
2952 @smallexample @c ada
2953 pragma Convention_Identifier (Fortran77, Fortran);
2954 @end smallexample
2955
2956 @noindent
2957 And from now on the identifier Fortran77 may be used as a convention
2958 identifier (for example in an @code{Import} pragma) with the same
2959 meaning as Fortran.
2960
2961 @ifclear vms
2962 @node Building Mixed Ada & C++ Programs
2963 @section Building Mixed Ada and C++ Programs
2964
2965 @noindent
2966 A programmer inexperienced with mixed-language development may find that
2967 building an application containing both Ada and C++ code can be a
2968 challenge.  This section gives a few
2969 hints that should make this task easier. The first section addresses
2970 the differences between interfacing with C and interfacing with C++.
2971 The second section
2972 looks into the delicate problem of linking the complete application from
2973 its Ada and C++ parts. The last section gives some hints on how the GNAT
2974 run-time library can be adapted in order to allow inter-language dispatching
2975 with a new C++ compiler.
2976
2977 @menu
2978 * Interfacing to C++::
2979 * Linking a Mixed C++ & Ada Program::
2980 * A Simple Example::
2981 * Interfacing with C++ constructors::
2982 * Interfacing with C++ at the Class Level::
2983 @end menu
2984
2985 @node Interfacing to C++
2986 @subsection Interfacing to C++
2987
2988 @noindent
2989 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2990 generating code that is compatible with the G++ Application Binary
2991 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2992
2993 @noindent
2994 Interfacing can be done at 3 levels: simple data, subprograms, and
2995 classes. In the first two cases, GNAT offers a specific @code{Convention
2996 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2997 Usually, C++ mangles the names of subprograms. To generate proper mangled
2998 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2999 This problem can also be addressed manually in two ways:
3000
3001 @itemize @bullet
3002 @item
3003 by modifying the C++ code in order to force a C convention using
3004 the @code{extern "C"} syntax.
3005
3006 @item
3007 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3008 Link_Name argument of the pragma import.
3009 @end itemize
3010
3011 @noindent
3012 Interfacing at the class level can be achieved by using the GNAT specific
3013 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3014 gnat_rm, GNAT Reference Manual}, for additional information.
3015
3016 @node Linking a Mixed C++ & Ada Program
3017 @subsection Linking a Mixed C++ & Ada Program
3018
3019 @noindent
3020 Usually the linker of the C++ development system must be used to link
3021 mixed applications because most C++ systems will resolve elaboration
3022 issues (such as calling constructors on global class instances)
3023 transparently during the link phase. GNAT has been adapted to ease the
3024 use of a foreign linker for the last phase. Three cases can be
3025 considered:
3026 @enumerate
3027
3028 @item
3029 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3030 The C++ linker can simply be called by using the C++ specific driver
3031 called @code{g++}.
3032
3033 Note that if the C++ code uses inline functions, you will need to
3034 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3035 order to provide an existing function implementation that the Ada code can
3036 link with.
3037
3038 @smallexample
3039 $ g++ -c -fkeep-inline-functions file1.C
3040 $ g++ -c -fkeep-inline-functions file2.C
3041 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3042 @end smallexample
3043
3044 @item
3045 Using GNAT and G++ from two different GCC installations: If both
3046 compilers are on the @env{PATH}, the previous method may be used. It is
3047 important to note that environment variables such as
3048 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3049 @env{GCC_ROOT} will affect both compilers
3050 at the same time and may make one of the two compilers operate
3051 improperly if set during invocation of the wrong compiler.  It is also
3052 very important that the linker uses the proper @file{libgcc.a} GCC
3053 library -- that is, the one from the C++ compiler installation. The
3054 implicit link command as suggested in the @command{gnatmake} command
3055 from the former example can be replaced by an explicit link command with
3056 the full-verbosity option in order to verify which library is used:
3057 @smallexample
3058 $ gnatbind ada_unit
3059 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3060 @end smallexample
3061 If there is a problem due to interfering environment variables, it can
3062 be worked around by using an intermediate script. The following example
3063 shows the proper script to use when GNAT has not been installed at its
3064 default location and g++ has been installed at its default location:
3065
3066 @smallexample
3067 $ cat ./my_script
3068 #!/bin/sh
3069 unset BINUTILS_ROOT
3070 unset GCC_ROOT
3071 c++ $*
3072 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3073 @end smallexample
3074
3075 @item
3076 Using a non-GNU C++ compiler: The commands previously described can be
3077 used to insure that the C++ linker is used. Nonetheless, you need to add
3078 a few more parameters to the link command line, depending on the exception
3079 mechanism used.
3080
3081 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3082 to the libgcc libraries are required:
3083
3084 @smallexample
3085 $ cat ./my_script
3086 #!/bin/sh
3087 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3088 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3089 @end smallexample
3090
3091 Where CC is the name of the non-GNU C++ compiler.
3092
3093 If the @code{zero cost} exception mechanism is used, and the platform
3094 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3095 paths to more objects are required:
3096
3097 @smallexample
3098 $ cat ./my_script
3099 #!/bin/sh
3100 CC `gcc -print-file-name=crtbegin.o` $* \
3101 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3102 `gcc -print-file-name=crtend.o`
3103 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3104 @end smallexample
3105
3106 If the @code{zero cost} exception mechanism is used, and the platform
3107 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3108 Tru64 or AIX), the simple approach described above will not work and
3109 a pre-linking phase using GNAT will be necessary.
3110
3111 @end enumerate
3112
3113 Another alternative is to use the @command{gprbuild} multi-language builder
3114 which has a large knowledge base and knows how to link Ada and C++ code
3115 together automatically in most cases.
3116
3117 @node A Simple Example
3118 @subsection  A Simple Example
3119 @noindent
3120 The following example, provided as part of the GNAT examples, shows how
3121 to achieve procedural interfacing between Ada and C++ in both
3122 directions. The C++ class A has two methods. The first method is exported
3123 to Ada by the means of an extern C wrapper function. The second method
3124 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3125 a limited record with a layout comparable to the C++ class. The Ada
3126 subprogram, in turn, calls the C++ method. So, starting from the C++
3127 main program, the process passes back and forth between the two
3128 languages.
3129
3130 @noindent
3131 Here are the compilation commands:
3132 @smallexample
3133 $ gnatmake -c simple_cpp_interface
3134 $ g++ -c cpp_main.C
3135 $ g++ -c ex7.C
3136 $ gnatbind -n simple_cpp_interface
3137 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3138       -lstdc++ ex7.o cpp_main.o
3139 @end smallexample
3140
3141 @noindent
3142 Here are the corresponding sources:
3143 @smallexample
3144
3145 //cpp_main.C
3146
3147 #include "ex7.h"
3148
3149 extern "C" @{
3150   void adainit (void);
3151   void adafinal (void);
3152   void method1 (A *t);
3153 @}
3154
3155 void method1 (A *t)
3156 @{
3157   t->method1 ();
3158 @}
3159
3160 int main ()
3161 @{
3162   A obj;
3163   adainit ();
3164   obj.method2 (3030);
3165   adafinal ();
3166 @}
3167
3168 //ex7.h
3169
3170 class Origin @{
3171  public:
3172   int o_value;
3173 @};
3174 class A : public Origin @{
3175  public:
3176   void method1 (void);
3177   void method2 (int v);
3178   A();
3179   int   a_value;
3180 @};
3181
3182 //ex7.C
3183
3184 #include "ex7.h"
3185 #include <stdio.h>
3186
3187 extern "C" @{ void ada_method2 (A *t, int v);@}
3188
3189 void A::method1 (void)
3190 @{
3191   a_value = 2020;
3192   printf ("in A::method1, a_value = %d \n",a_value);
3193
3194 @}
3195
3196 void A::method2 (int v)
3197 @{
3198    ada_method2 (this, v);
3199    printf ("in A::method2, a_value = %d \n",a_value);
3200
3201 @}
3202
3203 A::A(void)
3204 @{
3205    a_value = 1010;
3206   printf ("in A::A, a_value = %d \n",a_value);
3207 @}
3208 @end smallexample
3209
3210 @smallexample @c ada
3211 -- Ada sources
3212 package body Simple_Cpp_Interface is
3213
3214    procedure Ada_Method2 (This : in out A; V : Integer) is
3215    begin
3216       Method1 (This);
3217       This.A_Value := V;
3218    end Ada_Method2;
3219
3220 end Simple_Cpp_Interface;
3221
3222 with System;
3223 package Simple_Cpp_Interface is
3224    type A is limited
3225       record
3226          Vptr    : System.Address;
3227          O_Value : Integer;
3228          A_Value : Integer;
3229       end record;
3230    pragma Convention (C, A);
3231
3232    procedure Method1 (This : in out A);
3233    pragma Import (C, Method1);
3234
3235    procedure Ada_Method2 (This : in out A; V : Integer);
3236    pragma Export (C, Ada_Method2);
3237
3238 end Simple_Cpp_Interface;
3239 @end smallexample
3240
3241 @node Interfacing with C++ constructors
3242 @subsection Interfacing with C++ constructors
3243 @noindent
3244
3245 In order to interface with C++ constructors GNAT provides the
3246 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3247 gnat_rm, GNAT Reference Manual}, for additional information).
3248 In this section we present some common uses of C++ constructors
3249 in mixed-languages programs in GNAT.
3250
3251 Let us assume that we need to interface with the following
3252 C++ class:
3253
3254 @smallexample
3255 @b{class} Root @{
3256 @b{public}:
3257   int  a_value;
3258   int  b_value;
3259   @b{virtual} int Get_Value ();
3260   Root();              // Default constructor
3261   Root(int v);         // 1st non-default constructor
3262   Root(int v, int w);  // 2nd non-default constructor
3263 @};
3264 @end smallexample
3265
3266 For this purpose we can write the following package spec (further
3267 information on how to build this spec is available in
3268 @ref{Interfacing with C++ at the Class Level} and
3269 @ref{Generating Ada Bindings for C and C++ headers}).
3270
3271 @smallexample @c ada
3272 with Interfaces.C; use Interfaces.C;
3273 package Pkg_Root is
3274   type Root is tagged limited record
3275      A_Value : int;
3276      B_Value : int;
3277   end record;
3278   pragma Import (CPP, Root);
3279
3280   function Get_Value (Obj : Root) return int;
3281   pragma Import (CPP, Get_Value);
3282
3283   function Constructor return Root;
3284   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3285
3286   function Constructor (v : Integer) return Root;
3287   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3288
3289   function Constructor (v, w : Integer) return Root;
3290   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3291 end Pkg_Root;
3292 @end smallexample
3293
3294 On the Ada side the constructor is represented by a function (whose
3295 name is arbitrary) that returns the classwide type corresponding to
3296 the imported C++ class. Although the constructor is described as a
3297 function, it is typically a procedure with an extra implicit argument
3298 (the object being initialized) at the implementation level. GNAT
3299 issues the appropriate call, whatever it is, to get the object
3300 properly initialized.
3301
3302 Constructors can only appear in the following contexts:
3303
3304 @itemize @bullet
3305 @item
3306 On the right side of an initialization of an object of type @var{T}.
3307 @item
3308 On the right side of an initialization of a record component of type @var{T}.
3309 @item
3310 In an Ada 2005 limited aggregate.
3311 @item
3312 In an Ada 2005 nested limited aggregate.
3313 @item
3314 In an Ada 2005 limited aggregate that initializes an object built in
3315 place by an extended return statement.
3316 @end itemize
3317
3318 @noindent
3319 In a declaration of an object whose type is a class imported from C++,
3320 either the default C++ constructor is implicitly called by GNAT, or
3321 else the required C++ constructor must be explicitly called in the
3322 expression that initializes the object. For example:
3323
3324 @smallexample @c ada
3325   Obj1 : Root;
3326   Obj2 : Root := Constructor;
3327   Obj3 : Root := Constructor (v => 10);
3328   Obj4 : Root := Constructor (30, 40);
3329 @end smallexample
3330
3331 The first two declarations are equivalent: in both cases the default C++
3332 constructor is invoked (in the former case the call to the constructor is
3333 implicit, and in the latter case the call is explicit in the object
3334 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3335 that takes an integer argument, and @code{Obj4} is initialized by the
3336 non-default C++ constructor that takes two integers.
3337
3338 Let us derive the imported C++ class in the Ada side. For example:
3339
3340 @smallexample @c ada
3341   type DT is new Root with record
3342      C_Value : Natural := 2009;
3343   end record;
3344 @end smallexample
3345
3346 In this case the components DT inherited from the C++ side must be
3347 initialized by a C++ constructor, and the additional Ada components
3348 of type DT are initialized by GNAT. The initialization of such an
3349 object is done either by default, or by means of a function returning
3350 an aggregate of type DT, or by means of an extension aggregate.
3351
3352 @smallexample @c ada
3353   Obj5 : DT;
3354   Obj6 : DT := Function_Returning_DT (50);
3355   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3356 @end smallexample
3357
3358 The declaration of @code{Obj5} invokes the default constructors: the
3359 C++ default constructor of the parent type takes care of the initialization
3360 of the components inherited from Root, and GNAT takes care of the default
3361 initialization of the additional Ada components of type DT (that is,
3362 @code{C_Value} is initialized to value 2009). The order of invocation of
3363 the constructors is consistent with the order of elaboration required by
3364 Ada and C++. That is, the constructor of the parent type is always called
3365 before the constructor of the derived type.
3366
3367 Let us now consider a record that has components whose type is imported
3368 from C++. For example:
3369
3370 @smallexample @c ada
3371   type Rec1 is limited record
3372      Data1 : Root := Constructor (10);
3373      Value : Natural := 1000;
3374   end record;
3375
3376   type Rec2 (D : Integer := 20) is limited record
3377      Rec   : Rec1;
3378      Data2 : Root := Constructor (D, 30);
3379   end record;
3380 @end smallexample
3381
3382 The initialization of an object of type @code{Rec2} will call the
3383 non-default C++ constructors specified for the imported components.
3384 For example:
3385
3386 @smallexample @c ada
3387   Obj8 : Rec2 (40);
3388 @end smallexample
3389
3390 Using Ada 2005 we can use limited aggregates to initialize an object
3391 invoking C++ constructors that differ from those specified in the type
3392 declarations. For example:
3393
3394 @smallexample @c ada
3395   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3396                           others => <>),
3397                   others => <>);
3398 @end smallexample
3399
3400 The above declaration uses an Ada 2005 limited aggregate to
3401 initialize @code{Obj9}, and the C++ constructor that has two integer
3402 arguments is invoked to initialize the @code{Data1} component instead
3403 of the constructor specified in the declaration of type @code{Rec1}. In
3404 Ada 2005 the box in the aggregate indicates that unspecified components
3405 are initialized using the expression (if any) available in the component
3406 declaration. That is, in this case discriminant @code{D} is initialized
3407 to value @code{20}, @code{Value} is initialized to value 1000, and the
3408 non-default C++ constructor that handles two integers takes care of
3409 initializing component @code{Data2} with values @code{20,30}.
3410
3411 In Ada 2005 we can use the extended return statement to build the Ada
3412 equivalent to C++ non-default constructors. For example:
3413
3414 @smallexample @c ada
3415   function Constructor (V : Integer) return Rec2 is
3416   begin
3417      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3418                                    others => <>),
3419                            others => <>) do
3420         --  Further actions required for construction of
3421         --  objects of type Rec2
3422         ...
3423      end record;
3424   end Constructor;
3425 @end smallexample
3426
3427 In this example the extended return statement construct is used to
3428 build in place the returned object whose components are initialized
3429 by means of a limited aggregate. Any further action associated with
3430 the constructor can be placed inside the construct.
3431
3432 @node Interfacing with C++ at the Class Level
3433 @subsection Interfacing with C++ at the Class Level
3434 @noindent
3435 In this section we demonstrate the GNAT features for interfacing with
3436 C++ by means of an example making use of Ada 2005 abstract interface
3437 types. This example consists of a classification of animals; classes
3438 have been used to model our main classification of animals, and
3439 interfaces provide support for the management of secondary
3440 classifications. We first demonstrate a case in which the types and
3441 constructors are defined on the C++ side and imported from the Ada
3442 side, and latter the reverse case.
3443
3444 The root of our derivation will be the @code{Animal} class, with a
3445 single private attribute (the @code{Age} of the animal) and two public
3446 primitives to set and get the value of this attribute.
3447
3448 @smallexample
3449 @b{class} Animal @{
3450  @b{public}:
3451    @b{virtual} void Set_Age (int New_Age);
3452    @b{virtual} int Age ();
3453  @b{private}:
3454    int Age_Count;
3455 @};
3456 @end smallexample
3457
3458 Abstract interface types are defined in C++ by means of classes with pure
3459 virtual functions and no data members. In our example we will use two
3460 interfaces that provide support for the common management of @code{Carnivore}
3461 and @code{Domestic} animals:
3462
3463 @smallexample
3464 @b{class} Carnivore @{
3465 @b{public}:
3466    @b{virtual} int Number_Of_Teeth () = 0;
3467 @};
3468
3469 @b{class} Domestic @{
3470 @b{public}:
3471    @b{virtual void} Set_Owner (char* Name) = 0;
3472 @};
3473 @end smallexample
3474
3475 Using these declarations, we can now say that a @code{Dog} is an animal that is
3476 both Carnivore and Domestic, that is:
3477
3478 @smallexample
3479 @b{class} Dog : Animal, Carnivore, Domestic @{
3480  @b{public}:
3481    @b{virtual} int  Number_Of_Teeth ();
3482    @b{virtual} void Set_Owner (char* Name);
3483
3484    Dog(); // Constructor
3485  @b{private}:
3486    int  Tooth_Count;
3487    char *Owner;
3488 @};
3489 @end smallexample
3490
3491 In the following examples we will assume that the previous declarations are
3492 located in a file named @code{animals.h}. The following package demonstrates
3493 how to import these C++ declarations from the Ada side:
3494
3495 @smallexample @c ada
3496 with Interfaces.C.Strings; use Interfaces.C.Strings;
3497 package Animals is
3498   type Carnivore is interface;
3499   pragma Convention (C_Plus_Plus, Carnivore);
3500   function Number_Of_Teeth (X : Carnivore)
3501      return Natural is abstract;
3502
3503   type Domestic is interface;
3504   pragma Convention (C_Plus_Plus, Set_Owner);
3505   procedure Set_Owner
3506     (X    : in out Domestic;
3507      Name : Chars_Ptr) is abstract;
3508
3509   type Animal is tagged record
3510     Age : Natural := 0;
3511   end record;
3512   pragma Import (C_Plus_Plus, Animal);
3513
3514   procedure Set_Age (X : in out Animal; Age : Integer);
3515   pragma Import (C_Plus_Plus, Set_Age);
3516
3517   function Age (X : Animal) return Integer;
3518   pragma Import (C_Plus_Plus, Age);
3519
3520   type Dog is new Animal and Carnivore and Domestic with record
3521     Tooth_Count : Natural;
3522     Owner       : String (1 .. 30);
3523   end record;
3524   pragma Import (C_Plus_Plus, Dog);
3525
3526   function Number_Of_Teeth (A : Dog) return Integer;
3527   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3528
3529   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3530   pragma Import (C_Plus_Plus, Set_Owner);
3531
3532   function New_Dog return Dog;
3533   pragma CPP_Constructor (New_Dog);
3534   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3535 end Animals;
3536 @end smallexample
3537
3538 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3539 interfacing with these C++ classes is easy. The only requirement is that all
3540 the primitives and components must be declared exactly in the same order in
3541 the two languages.
3542
3543 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3544 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3545 the arguments to the called primitives will be the same as for C++. For the
3546 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3547 to indicate that they have been defined on the C++ side; this is required
3548 because the dispatch table associated with these tagged types will be built
3549 in the C++ side and therefore will not contain the predefined Ada primitives
3550 which Ada would otherwise expect.
3551
3552 As the reader can see there is no need to indicate the C++ mangled names
3553 associated with each subprogram because it is assumed that all the calls to
3554 these primitives will be dispatching calls. The only exception is the
3555 constructor, which must be registered with the compiler by means of
3556 @code{pragma CPP_Constructor} and needs to provide its associated C++
3557 mangled name because the Ada compiler generates direct calls to it.
3558
3559 With the above packages we can now declare objects of type Dog on the Ada side
3560 and dispatch calls to the corresponding subprograms on the C++ side. We can
3561 also extend the tagged type Dog with further fields and primitives, and
3562 override some of its C++ primitives on the Ada side. For example, here we have
3563 a type derivation defined on the Ada side that inherits all the dispatching
3564 primitives of the ancestor from the C++ side.
3565
3566 @smallexample
3567 @b{with} Animals; @b{use} Animals;
3568 @b{package} Vaccinated_Animals @b{is}
3569   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3570   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3571 @b{end} Vaccinated_Animals;
3572 @end smallexample
3573
3574 It is important to note that, because of the ABI compatibility, the programmer
3575 does not need to add any further information to indicate either the object
3576 layout or the dispatch table entry associated with each dispatching operation.
3577
3578 Now let us define all the types and constructors on the Ada side and export
3579 them to C++, using the same hierarchy of our previous example:
3580
3581 @smallexample @c ada
3582 with Interfaces.C.Strings;
3583 use Interfaces.C.Strings;
3584 package Animals is
3585   type Carnivore is interface;
3586   pragma Convention (C_Plus_Plus, Carnivore);
3587   function Number_Of_Teeth (X : Carnivore)
3588      return Natural is abstract;
3589
3590   type Domestic is interface;
3591   pragma Convention (C_Plus_Plus, Set_Owner);
3592   procedure Set_Owner
3593     (X    : in out Domestic;
3594      Name : Chars_Ptr) is abstract;
3595
3596   type Animal is tagged record
3597     Age : Natural := 0;
3598   end record;
3599   pragma Convention (C_Plus_Plus, Animal);
3600
3601   procedure Set_Age (X : in out Animal; Age : Integer);
3602   pragma Export (C_Plus_Plus, Set_Age);
3603
3604   function Age (X : Animal) return Integer;
3605   pragma Export (C_Plus_Plus, Age);
3606
3607   type Dog is new Animal and Carnivore and Domestic with record
3608     Tooth_Count : Natural;
3609     Owner       : String (1 .. 30);
3610   end record;
3611   pragma Convention (C_Plus_Plus, Dog);
3612
3613   function Number_Of_Teeth (A : Dog) return Integer;
3614   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3615
3616   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3617   pragma Export (C_Plus_Plus, Set_Owner);
3618
3619   function New_Dog return Dog'Class;
3620   pragma Export (C_Plus_Plus, New_Dog);
3621 end Animals;
3622 @end smallexample
3623
3624 Compared with our previous example the only difference is the use of
3625 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3626 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3627 nothing else to be done; as explained above, the only requirement is that all
3628 the primitives and components are declared in exactly the same order.
3629
3630 For completeness, let us see a brief C++ main program that uses the
3631 declarations available in @code{animals.h} (presented in our first example) to
3632 import and use the declarations from the Ada side, properly initializing and
3633 finalizing the Ada run-time system along the way:
3634
3635 @smallexample
3636 @b{#include} "animals.h"
3637 @b{#include} <iostream>
3638 @b{using namespace} std;
3639
3640 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3641 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3642 void Check_Animal (Animal *obj)       @{@dots{}@}
3643 void Check_Dog (Dog *obj)             @{@dots{}@}
3644
3645 @b{extern} "C" @{
3646   void adainit (void);
3647   void adafinal (void);
3648   Dog* new_dog ();
3649 @}
3650
3651 void test ()
3652 @{
3653   Dog *obj = new_dog();  // Ada constructor
3654   Check_Carnivore (obj); // Check secondary DT
3655   Check_Domestic (obj);  // Check secondary DT
3656   Check_Animal (obj);    // Check primary DT
3657   Check_Dog (obj);       // Check primary DT
3658 @}
3659
3660 int main ()
3661 @{
3662   adainit ();  test();  adafinal ();
3663   return 0;
3664 @}
3665 @end smallexample
3666
3667 @node Comparison between GNAT and C/C++ Compilation Models
3668 @section Comparison between GNAT and C/C++ Compilation Models
3669
3670 @noindent
3671 The GNAT model of compilation is close to the C and C++ models. You can
3672 think of Ada specs as corresponding to header files in C. As in C, you
3673 don't need to compile specs; they are compiled when they are used. The
3674 Ada @code{with} is similar in effect to the @code{#include} of a C
3675 header.
3676
3677 One notable difference is that, in Ada, you may compile specs separately
3678 to check them for semantic and syntactic accuracy. This is not always
3679 possible with C headers because they are fragments of programs that have
3680 less specific syntactic or semantic rules.
3681
3682 The other major difference is the requirement for running the binder,
3683 which performs two important functions. First, it checks for
3684 consistency. In C or C++, the only defense against assembling
3685 inconsistent programs lies outside the compiler, in a makefile, for
3686 example. The binder satisfies the Ada requirement that it be impossible
3687 to construct an inconsistent program when the compiler is used in normal
3688 mode.
3689
3690 @cindex Elaboration order control
3691 The other important function of the binder is to deal with elaboration
3692 issues. There are also elaboration issues in C++ that are handled
3693 automatically. This automatic handling has the advantage of being
3694 simpler to use, but the C++ programmer has no control over elaboration.
3695 Where @code{gnatbind} might complain there was no valid order of
3696 elaboration, a C++ compiler would simply construct a program that
3697 malfunctioned at run time.
3698 @end ifclear
3699
3700 @node Comparison between GNAT and Conventional Ada Library Models
3701 @section Comparison between GNAT and Conventional Ada Library Models
3702
3703 @noindent
3704 This section is intended for Ada programmers who have
3705 used an Ada compiler implementing the traditional Ada library
3706 model, as described in the Ada Reference Manual.
3707
3708 @cindex GNAT library
3709 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3710 source files themselves acts as the library. Compiling Ada programs does
3711 not generate any centralized information, but rather an object file and
3712 a ALI file, which are of interest only to the binder and linker.
3713 In a traditional system, the compiler reads information not only from
3714 the source file being compiled, but also from the centralized library.
3715 This means that the effect of a compilation depends on what has been
3716 previously compiled. In particular:
3717
3718 @itemize @bullet
3719 @item
3720 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3721 to the version of the unit most recently compiled into the library.
3722
3723 @item
3724 Inlining is effective only if the necessary body has already been
3725 compiled into the library.
3726
3727 @item
3728 Compiling a unit may obsolete other units in the library.
3729 @end itemize
3730
3731 @noindent
3732 In GNAT, compiling one unit never affects the compilation of any other
3733 units because the compiler reads only source files. Only changes to source
3734 files can affect the results of a compilation. In particular:
3735
3736 @itemize @bullet
3737 @item
3738 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3739 to the source version of the unit that is currently accessible to the
3740 compiler.
3741
3742 @item
3743 @cindex Inlining
3744 Inlining requires the appropriate source files for the package or
3745 subprogram bodies to be available to the compiler. Inlining is always
3746 effective, independent of the order in which units are complied.
3747
3748 @item
3749 Compiling a unit never affects any other compilations. The editing of
3750 sources may cause previous compilations to be out of date if they
3751 depended on the source file being modified.
3752 @end itemize
3753
3754 @noindent
3755 The most important result of these differences is that order of compilation
3756 is never significant in GNAT. There is no situation in which one is
3757 required to do one compilation before another. What shows up as order of
3758 compilation requirements in the traditional Ada library becomes, in
3759 GNAT, simple source dependencies; in other words, there is only a set
3760 of rules saying what source files must be present when a file is
3761 compiled.
3762
3763 @ifset vms
3764 @node Placement of temporary files
3765 @section Placement of temporary files
3766 @cindex Temporary files (user control over placement)
3767
3768 @noindent
3769 GNAT creates temporary files in the directory designated by the environment
3770 variable @env{TMPDIR}.
3771 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3772 for detailed information on how environment variables are resolved.
3773 For most users the easiest way to make use of this feature is to simply
3774 define @env{TMPDIR} as a job level logical name).
3775 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3776 for compiler temporary files, then you can include something like the
3777 following command in your @file{LOGIN.COM} file:
3778
3779 @smallexample
3780 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3781 @end smallexample
3782
3783 @noindent
3784 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3785 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3786 designated by @env{TEMP}.
3787 If none of these environment variables are defined then GNAT uses the
3788 directory designated by the logical name @code{SYS$SCRATCH:}
3789 (by default the user's home directory). If all else fails
3790 GNAT uses the current directory for temporary files.
3791 @end ifset
3792
3793 @c *************************
3794 @node Compiling Using gcc
3795 @chapter Compiling Using @command{gcc}
3796
3797 @noindent
3798 This chapter discusses how to compile Ada programs using the @command{gcc}
3799 command. It also describes the set of switches
3800 that can be used to control the behavior of the compiler.
3801 @menu
3802 * Compiling Programs::
3803 * Switches for gcc::
3804 * Search Paths and the Run-Time Library (RTL)::
3805 * Order of Compilation Issues::
3806 * Examples::
3807 @end menu
3808
3809 @node Compiling Programs
3810 @section Compiling Programs
3811
3812 @noindent
3813 The first step in creating an executable program is to compile the units
3814 of the program using the @command{gcc} command. You must compile the
3815 following files:
3816
3817 @itemize @bullet
3818 @item
3819 the body file (@file{.adb}) for a library level subprogram or generic
3820 subprogram
3821
3822 @item
3823 the spec file (@file{.ads}) for a library level package or generic
3824 package that has no body
3825
3826 @item
3827 the body file (@file{.adb}) for a library level package
3828 or generic package that has a body
3829
3830 @end itemize
3831
3832 @noindent
3833 You need @emph{not} compile the following files
3834
3835 @itemize @bullet
3836
3837 @item
3838 the spec of a library unit which has a body
3839
3840 @item
3841 subunits
3842 @end itemize
3843
3844 @noindent
3845 because they are compiled as part of compiling related units. GNAT
3846 package specs
3847 when the corresponding body is compiled, and subunits when the parent is
3848 compiled.
3849
3850 @cindex cannot generate code
3851 If you attempt to compile any of these files, you will get one of the
3852 following error messages (where @var{fff} is the name of the file you compiled):
3853
3854 @smallexample
3855 cannot generate code for file @var{fff} (package spec)
3856 to check package spec, use -gnatc
3857
3858 cannot generate code for file @var{fff} (missing subunits)
3859 to check parent unit, use -gnatc
3860
3861 cannot generate code for file @var{fff} (subprogram spec)
3862 to check subprogram spec, use -gnatc
3863
3864 cannot generate code for file @var{fff} (subunit)
3865 to check subunit, use -gnatc
3866 @end smallexample
3867
3868 @noindent
3869 As indicated by the above error messages, if you want to submit
3870 one of these files to the compiler to check for correct semantics
3871 without generating code, then use the @option{-gnatc} switch.
3872
3873 The basic command for compiling a file containing an Ada unit is
3874
3875 @smallexample
3876 $ gcc -c @ovar{switches} @file{file name}
3877 @end smallexample
3878
3879 @noindent
3880 where @var{file name} is the name of the Ada file (usually
3881 having an extension
3882 @file{.ads} for a spec or @file{.adb} for a body).
3883 @ifclear vms
3884 You specify the
3885 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3886 @end ifclear
3887 The result of a successful compilation is an object file, which has the
3888 same name as the source file but an extension of @file{.o} and an Ada
3889 Library Information (ALI) file, which also has the same name as the
3890 source file, but with @file{.ali} as the extension. GNAT creates these
3891 two output files in the current directory, but you may specify a source
3892 file in any directory using an absolute or relative path specification
3893 containing the directory information.
3894
3895 @findex gnat1
3896 @command{gcc} is actually a driver program that looks at the extensions of
3897 the file arguments and loads the appropriate compiler. For example, the
3898 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3899 These programs are in directories known to the driver program (in some
3900 configurations via environment variables you set), but need not be in
3901 your path. The @command{gcc} driver also calls the assembler and any other
3902 utilities needed to complete the generation of the required object
3903 files.
3904
3905 It is possible to supply several file names on the same @command{gcc}
3906 command. This causes @command{gcc} to call the appropriate compiler for
3907 each file. For example, the following command lists three separate
3908 files to be compiled:
3909
3910 @smallexample
3911 $ gcc -c x.adb y.adb z.c
3912 @end smallexample
3913
3914 @noindent
3915 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3916 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3917 The compiler generates three object files @file{x.o}, @file{y.o} and
3918 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3919 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3920 @ifclear vms
3921 except for
3922 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3923 @end ifclear
3924
3925 @node Switches for gcc
3926 @section Switches for @command{gcc}
3927
3928 @noindent
3929 The @command{gcc} command accepts switches that control the
3930 compilation process. These switches are fully described in this section.
3931 First we briefly list all the switches, in alphabetical order, then we
3932 describe the switches in more detail in functionally grouped sections.
3933
3934 More switches exist for GCC than those documented here, especially
3935 for specific targets. However, their use is not recommended as
3936 they may change code generation in ways that are incompatible with
3937 the Ada run-time library, or can cause inconsistencies between
3938 compilation units.
3939
3940 @menu
3941 * Output and Error Message Control::
3942 * Warning Message Control::
3943 * Debugging and Assertion Control::
3944 * Validity Checking::
3945 * Style Checking::
3946 * Run-Time Checks::
3947 * Using gcc for Syntax Checking::
3948 * Using gcc for Semantic Checking::
3949 * Compiling Different Versions of Ada::
3950 * Character Set Control::
3951 * File Naming Control::
3952 * Subprogram Inlining Control::
3953 * Auxiliary Output Control::
3954 * Debugging Control::
3955 * Exception Handling Control::
3956 * Units to Sources Mapping Files::
3957 * Integrated Preprocessing::
3958 * Code Generation Control::
3959 @ifset vms
3960 * Return Codes::
3961 @end ifset
3962 @end menu
3963
3964 @table @option
3965 @c !sort!
3966 @ifclear vms
3967 @cindex @option{-b} (@command{gcc})
3968 @item -b @var{target}
3969 Compile your program to run on @var{target}, which is the name of a
3970 system configuration. You must have a GNAT cross-compiler built if
3971 @var{target} is not the same as your host system.
3972
3973 @item -B@var{dir}
3974 @cindex @option{-B} (@command{gcc})
3975 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3976 from @var{dir} instead of the default location. Only use this switch
3977 when multiple versions of the GNAT compiler are available.
3978 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3979 GNU Compiler Collection (GCC)}, for further details. You would normally
3980 use the @option{-b} or @option{-V} switch instead.
3981
3982 @item -c
3983 @cindex @option{-c} (@command{gcc})
3984 Compile. Always use this switch when compiling Ada programs.
3985
3986 Note: for some other languages when using @command{gcc}, notably in
3987 the case of C and C++, it is possible to use
3988 use @command{gcc} without a @option{-c} switch to
3989 compile and link in one step. In the case of GNAT, you
3990 cannot use this approach, because the binder must be run
3991 and @command{gcc} cannot be used to run the GNAT binder.
3992 @end ifclear
3993
3994 @item -fno-inline
3995 @cindex @option{-fno-inline} (@command{gcc})
3996 Suppresses all back-end inlining, even if other optimization or inlining
3997 switches are set.
3998 This includes suppression of inlining that results
3999 from the use of the pragma @code{Inline_Always}.
4000 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4001 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4002 effect if this switch is present.
4003
4004 @item -fno-inline-functions
4005 @cindex @option{-fno-inline-functions} (@command{gcc})
4006 Suppresses automatic inlining of simple subprograms, which is enabled
4007 if @option{-O3} is used.
4008
4009 @item -fno-inline-small-functions
4010 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4011 Suppresses automatic inlining of small subprograms, which is enabled
4012 if @option{-O2} is used.
4013
4014 @item -fno-inline-functions-called-once
4015 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4016 Suppresses inlining of subprograms local to the unit and called once
4017 from within it, which is enabled if @option{-O1} is used.
4018
4019 @item -fno-ivopts
4020 @cindex @option{-fno-ivopts} (@command{gcc})
4021 Suppresses high-level loop induction variable optimizations, which are
4022 enabled if @option{-O1} is used. These optimizations are generally
4023 profitable but, for some specific cases of loops with numerous uses
4024 of the iteration variable that follow a common pattern, they may end
4025 up destroying the regularity that could be exploited at a lower level
4026 and thus producing inferior code.
4027
4028 @item -fno-strict-aliasing
4029 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4030 Causes the compiler to avoid assumptions regarding non-aliasing
4031 of objects of different types. See
4032 @ref{Optimization and Strict Aliasing} for details.
4033
4034 @item -fstack-check
4035 @cindex @option{-fstack-check} (@command{gcc})
4036 Activates stack checking.
4037 See @ref{Stack Overflow Checking} for details.
4038
4039 @item -fstack-usage
4040 @cindex @option{-fstack-usage} (@command{gcc})
4041 Makes the compiler output stack usage information for the program, on a
4042 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4043
4044 @item -fcallgraph-info@r{[}=su@r{]}
4045 @cindex @option{-fcallgraph-info} (@command{gcc})
4046 Makes the compiler output callgraph information for the program, on a
4047 per-file basis.  The information is generated in the VCG format.  It can
4048 be decorated with stack-usage per-node information.
4049
4050 @item ^-g^/DEBUG^
4051 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4052 Generate debugging information. This information is stored in the object
4053 file and copied from there to the final executable file by the linker,
4054 where it can be read by the debugger. You must use the
4055 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4056
4057 @item -gnat83
4058 @cindex @option{-gnat83} (@command{gcc})
4059 Enforce Ada 83 restrictions.
4060
4061 @item -gnat95
4062 @cindex @option{-gnat95} (@command{gcc})
4063 Enforce Ada 95 restrictions.
4064
4065 @item -gnat05
4066 @cindex @option{-gnat05} (@command{gcc})
4067 Allow full Ada 2005 features.
4068
4069 @item -gnata
4070 @cindex @option{-gnata} (@command{gcc})
4071 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4072 activated. Note that these pragmas can also be controlled using the
4073 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4074 It also activates pragmas @code{Check}, @code{Precondition}, and
4075 @code{Postcondition}. Note that these pragmas can also be controlled
4076 using the configuration pragma @code{Check_Policy}.
4077
4078 @item -gnatA
4079 @cindex @option{-gnatA} (@command{gcc})
4080 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4081 it will be ignored.
4082
4083 @item -gnatb
4084 @cindex @option{-gnatb} (@command{gcc})
4085 Generate brief messages to @file{stderr} even if verbose mode set.
4086
4087 @item -gnatB
4088 @cindex @option{-gnatB} (@command{gcc})
4089 Assume no invalid (bad) values except for 'Valid attribute use
4090 (@pxref{Validity Checking}).
4091
4092 @item -gnatc
4093 @cindex @option{-gnatc} (@command{gcc})
4094 Check syntax and semantics only (no code generation attempted).
4095
4096 @item -gnatC
4097 @cindex @option{-gnatC} (@command{gcc})
4098 Generate CodePeer information (no code generation attempted).
4099 This switch will generate an intermediate representation suitable for
4100 use by CodePeer (@file{.scil} files). This switch is not compatible with
4101 code generation (it will, among other things, disable some switches such
4102 as -gnatn, and enable others such as -gnata).
4103
4104 @item -gnatd
4105 @cindex @option{-gnatd} (@command{gcc})
4106 Specify debug options for the compiler. The string of characters after
4107 the @option{-gnatd} specify the specific debug options. The possible
4108 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4109 compiler source file @file{debug.adb} for details of the implemented
4110 debug options. Certain debug options are relevant to applications
4111 programmers, and these are documented at appropriate points in this
4112 users guide.
4113
4114 @ifclear vms
4115 @item -gnatD
4116 @cindex @option{-gnatD[nn]} (@command{gcc})
4117 @end ifclear
4118 @ifset vms
4119 @item /XDEBUG /LXDEBUG=nnn
4120 @end ifset
4121 Create expanded source files for source level debugging. This switch
4122 also suppress generation of cross-reference information
4123 (see @option{-gnatx}).
4124
4125 @item -gnatec=@var{path}
4126 @cindex @option{-gnatec} (@command{gcc})
4127 Specify a configuration pragma file
4128 @ifclear vms
4129 (the equal sign is optional)
4130 @end ifclear
4131 (@pxref{The Configuration Pragmas Files}).
4132
4133 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4134 @cindex @option{-gnateD} (@command{gcc})
4135 Defines a symbol, associated with @var{value}, for preprocessing.
4136 (@pxref{Integrated Preprocessing}).
4137
4138 @item -gnatef
4139 @cindex @option{-gnatef} (@command{gcc})
4140 Display full source path name in brief error messages.
4141
4142 @item -gnateG
4143 @cindex @option{-gnateG} (@command{gcc})
4144 Save result of preprocessing in a text file.
4145
4146 @item -gnatem=@var{path}
4147 @cindex @option{-gnatem} (@command{gcc})
4148 Specify a mapping file
4149 @ifclear vms
4150 (the equal sign is optional)
4151 @end ifclear
4152 (@pxref{Units to Sources Mapping Files}).
4153
4154 @item -gnatep=@var{file}
4155 @cindex @option{-gnatep} (@command{gcc})
4156 Specify a preprocessing data file
4157 @ifclear vms
4158 (the equal sign is optional)
4159 @end ifclear
4160 (@pxref{Integrated Preprocessing}).
4161
4162 @item -gnateS
4163 @cindex @option{-gnateS} (@command{gcc})
4164 Generate SCO (Source Coverage Obligation) information in the ALI
4165 file. This information is used by advanced coverage tools. See
4166 unit @file{SCOs} in the compiler sources for details in files
4167 @file{scos.ads} and @file{scos.adb}.
4168
4169 @item -gnatE
4170 @cindex @option{-gnatE} (@command{gcc})
4171 Full dynamic elaboration checks.
4172
4173 @item -gnatf
4174 @cindex @option{-gnatf} (@command{gcc})
4175 Full errors. Multiple errors per line, all undefined references, do not
4176 attempt to suppress cascaded errors.
4177
4178 @item -gnatF
4179 @cindex @option{-gnatF} (@command{gcc})
4180 Externals names are folded to all uppercase.
4181
4182 @item ^-gnatg^/GNAT_INTERNAL^
4183 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4184 Internal GNAT implementation mode. This should not be used for
4185 applications programs, it is intended only for use by the compiler
4186 and its run-time library. For documentation, see the GNAT sources.
4187 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4188 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4189 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4190 so that all standard warnings and all standard style options are turned on.
4191 All warnings and style error messages are treated as errors.
4192
4193 @ifclear vms
4194 @item -gnatG=nn
4195 @cindex @option{-gnatG[nn]} (@command{gcc})
4196 @end ifclear
4197 @ifset vms
4198 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4199 @end ifset
4200 List generated expanded code in source form.
4201
4202 @item ^-gnath^/HELP^
4203 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4204 Output usage information. The output is written to @file{stdout}.
4205
4206 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4207 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4208 Identifier character set
4209 @ifclear vms
4210 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4211 @end ifclear
4212 For details of the possible selections for @var{c},
4213 see @ref{Character Set Control}.
4214
4215 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4216 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4217 Ignore representation clauses. When this switch is used,
4218 representation clauses are treated as comments. This is useful
4219 when initially porting code where you want to ignore rep clause
4220 problems, and also for compiling foreign code (particularly
4221 for use with ASIS). The representation clauses that are ignored
4222 are: enumeration_representation_clause, record_representation_clause,
4223 and attribute_definition_clause for the following attributes:
4224 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4225 Object_Size, Size, Small, Stream_Size, and Value_Size.
4226 Note that this option should be used only for compiling -- the
4227 code is likely to malfunction at run time.
4228
4229 @item -gnatjnn
4230 @cindex @option{-gnatjnn} (@command{gcc})
4231 Reformat error messages to fit on nn character lines
4232
4233 @item -gnatk=@var{n}
4234 @cindex @option{-gnatk} (@command{gcc})
4235 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4236
4237 @item -gnatl
4238 @cindex @option{-gnatl} (@command{gcc})
4239 Output full source listing with embedded error messages.
4240
4241 @item -gnatL
4242 @cindex @option{-gnatL} (@command{gcc})
4243 Used in conjunction with -gnatG or -gnatD to intersperse original
4244 source lines (as comment lines with line numbers) in the expanded
4245 source output.
4246
4247 @item -gnatm=@var{n}
4248 @cindex @option{-gnatm} (@command{gcc})
4249 Limit number of detected error or warning messages to @var{n}
4250 where @var{n} is in the range 1..999999. The default setting if
4251 no switch is given is 9999. If the number of warnings reaches this
4252 limit, then a message is output and further warnings are suppressed,
4253 but the compilation is continued. If the number of error messages
4254 reaches this limit, then a message is output and the compilation
4255 is abandoned. The equal sign here is optional. A value of zero
4256 means that no limit applies.
4257
4258 @item -gnatn
4259 @cindex @option{-gnatn} (@command{gcc})
4260 Activate inlining for subprograms for which
4261 pragma @code{inline} is specified. This inlining is performed
4262 by the GCC back-end.
4263
4264 @item -gnatN
4265 @cindex @option{-gnatN} (@command{gcc})
4266 Activate front end inlining for subprograms for which
4267 pragma @code{Inline} is specified. This inlining is performed
4268 by the front end and will be visible in the
4269 @option{-gnatG} output.
4270
4271 When using a gcc-based back end (in practice this means using any version
4272 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4273 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4274 Historically front end inlining was more extensive than the gcc back end
4275 inlining, but that is no longer the case.
4276
4277 @item -gnato
4278 @cindex @option{-gnato} (@command{gcc})
4279 Enable numeric overflow checking (which is not normally enabled by
4280 default). Note that division by zero is a separate check that is not
4281 controlled by this switch (division by zero checking is on by default).
4282
4283 @item -gnatp
4284 @cindex @option{-gnatp} (@command{gcc})
4285 Suppress all checks. See @ref{Run-Time Checks} for details.
4286
4287 @item -gnatP
4288 @cindex @option{-gnatP} (@command{gcc})
4289 Enable polling. This is required on some systems (notably Windows NT) to
4290 obtain asynchronous abort and asynchronous transfer of control capability.
4291 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4292 details.
4293
4294 @item -gnatq
4295 @cindex @option{-gnatq} (@command{gcc})
4296 Don't quit. Try semantics, even if parse errors.
4297
4298 @item -gnatQ
4299 @cindex @option{-gnatQ} (@command{gcc})
4300 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4301
4302 @item -gnatr
4303 @cindex @option{-gnatr} (@command{gcc})
4304 Treat pragma Restrictions as Restriction_Warnings.
4305
4306 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4307 @cindex @option{-gnatR} (@command{gcc})
4308 Output representation information for declared types and objects.
4309
4310 @item -gnats
4311 @cindex @option{-gnats} (@command{gcc})
4312 Syntax check only.
4313
4314 @item -gnatS
4315 @cindex @option{-gnatS} (@command{gcc})
4316 Print package Standard.
4317
4318 @item -gnatt
4319 @cindex @option{-gnatt} (@command{gcc})
4320 Generate tree output file.
4321
4322 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4323 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4324 All compiler tables start at @var{nnn} times usual starting size.
4325
4326 @item -gnatu
4327 @cindex @option{-gnatu} (@command{gcc})
4328 List units for this compilation.
4329
4330 @item -gnatU
4331 @cindex @option{-gnatU} (@command{gcc})
4332 Tag all error messages with the unique string ``error:''
4333
4334 @item -gnatv
4335 @cindex @option{-gnatv} (@command{gcc})
4336 Verbose mode. Full error output with source lines to @file{stdout}.
4337
4338 @item -gnatV
4339 @cindex @option{-gnatV} (@command{gcc})
4340 Control level of validity checking (@pxref{Validity Checking}).
4341
4342 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4343 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4344 Warning mode where
4345 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4346 the exact warnings that
4347 are enabled or disabled (@pxref{Warning Message Control}).
4348
4349 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4350 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4351 Wide character encoding method
4352 @ifclear vms
4353 (@var{e}=n/h/u/s/e/8).
4354 @end ifclear
4355 @ifset vms
4356 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4357 @end ifset
4358
4359 @item -gnatx
4360 @cindex @option{-gnatx} (@command{gcc})
4361 Suppress generation of cross-reference information.
4362
4363 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4364 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4365 Enable built-in style checks (@pxref{Style Checking}).
4366
4367 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4368 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4369 Distribution stub generation and compilation
4370 @ifclear vms
4371 (@var{m}=r/c for receiver/caller stubs).
4372 @end ifclear
4373 @ifset vms
4374 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4375 to be generated and compiled).
4376 @end ifset
4377
4378 @item ^-I^/SEARCH=^@var{dir}
4379 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4380 @cindex RTL
4381 Direct GNAT to search the @var{dir} directory for source files needed by
4382 the current compilation
4383 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4384
4385 @item ^-I-^/NOCURRENT_DIRECTORY^
4386 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4387 @cindex RTL
4388 Except for the source file named in the command line, do not look for source
4389 files in the directory containing the source file named in the command line
4390 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4391
4392 @ifclear vms
4393 @item -mbig-switch
4394 @cindex @option{-mbig-switch} (@command{gcc})
4395 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4396 This standard gcc switch causes the compiler to use larger offsets in its
4397 jump table representation for @code{case} statements.
4398 This may result in less efficient code, but is sometimes necessary
4399 (for example on HP-UX targets)
4400 @cindex HP-UX and @option{-mbig-switch} option
4401 in order to compile large and/or nested @code{case} statements.
4402
4403 @item -o @var{file}
4404 @cindex @option{-o} (@command{gcc})
4405 This switch is used in @command{gcc} to redirect the generated object file
4406 and its associated ALI file. Beware of this switch with GNAT, because it may
4407 cause the object file and ALI file to have different names which in turn
4408 may confuse the binder and the linker.
4409 @end ifclear
4410
4411 @item -nostdinc
4412 @cindex @option{-nostdinc} (@command{gcc})
4413 Inhibit the search of the default location for the GNAT Run Time
4414 Library (RTL) source files.
4415
4416 @item -nostdlib
4417 @cindex @option{-nostdlib} (@command{gcc})
4418 Inhibit the search of the default location for the GNAT Run Time
4419 Library (RTL) ALI files.
4420
4421 @ifclear vms
4422 @item -O@ovar{n}
4423 @cindex @option{-O} (@command{gcc})
4424 @var{n} controls the optimization level.
4425
4426 @table @asis
4427 @item n = 0
4428 No optimization, the default setting if no @option{-O} appears
4429
4430 @item n = 1
4431 Normal optimization, the default if you specify @option{-O} without
4432 an operand. A good compromise between code quality and compilation
4433 time.
4434
4435 @item n = 2
4436 Extensive optimization, may improve execution time, possibly at the cost of
4437 substantially increased compilation time.
4438
4439 @item n = 3
4440 Same as @option{-O2}, and also includes inline expansion for small subprograms
4441 in the same unit.
4442
4443 @item n = s
4444 Optimize space usage
4445 @end table
4446
4447 @noindent
4448 See also @ref{Optimization Levels}.
4449 @end ifclear
4450
4451 @ifset vms
4452 @item  /NOOPTIMIZE
4453 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4454 Equivalent to @option{/OPTIMIZE=NONE}.
4455 This is the default behavior in the absence of an @option{/OPTIMIZE}
4456 qualifier.
4457
4458 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4459 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4460 Selects the level of optimization for your program. The supported
4461 keywords are as follows:
4462 @table @code
4463 @item   ALL
4464 Perform most optimizations, including those that
4465 are expensive.
4466 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4467 without keyword options.
4468
4469 @item   NONE
4470 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4471
4472 @item SOME
4473 Perform some optimizations, but omit ones that are costly.
4474
4475 @item   DEVELOPMENT
4476 Same as @code{SOME}.
4477
4478 @item INLINING
4479 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4480 automatic inlining of small subprograms within a unit
4481
4482 @item   UNROLL_LOOPS
4483 Try to unroll loops. This keyword may be specified together with
4484 any keyword above other than @code{NONE}. Loop unrolling
4485 usually, but not always, improves the performance of programs.
4486
4487 @item SPACE
4488 Optimize space usage
4489 @end table
4490
4491 @noindent
4492 See also @ref{Optimization Levels}.
4493 @end ifset
4494
4495 @ifclear vms
4496 @item -pass-exit-codes
4497 @cindex @option{-pass-exit-codes} (@command{gcc})
4498 Catch exit codes from the compiler and use the most meaningful as
4499 exit status.
4500 @end ifclear
4501
4502 @item --RTS=@var{rts-path}
4503 @cindex @option{--RTS} (@command{gcc})
4504 Specifies the default location of the runtime library. Same meaning as the
4505 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4506
4507 @item ^-S^/ASM^
4508 @cindex @option{^-S^/ASM^} (@command{gcc})
4509 ^Used in place of @option{-c} to^Used to^
4510 cause the assembler source file to be
4511 generated, using @file{^.s^.S^} as the extension,
4512 instead of the object file.
4513 This may be useful if you need to examine the generated assembly code.
4514
4515 @item ^-fverbose-asm^/VERBOSE_ASM^
4516 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4517 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4518 to cause the generated assembly code file to be annotated with variable
4519 names, making it significantly easier to follow.
4520
4521 @item ^-v^/VERBOSE^
4522 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4523 Show commands generated by the @command{gcc} driver. Normally used only for
4524 debugging purposes or if you need to be sure what version of the
4525 compiler you are executing.
4526
4527 @ifclear vms
4528 @item -V @var{ver}
4529 @cindex @option{-V} (@command{gcc})
4530 Execute @var{ver} version of the compiler. This is the @command{gcc}
4531 version, not the GNAT version.
4532 @end ifclear
4533
4534 @item ^-w^/NO_BACK_END_WARNINGS^
4535 @cindex @option{-w} (@command{gcc})
4536 Turn off warnings generated by the back end of the compiler. Use of
4537 this switch also causes the default for front end warnings to be set
4538 to suppress (as though @option{-gnatws} had appeared at the start of
4539 the options).
4540
4541 @end table
4542
4543 @ifclear vms
4544 @c Combining qualifiers does not work on VMS
4545 You may combine a sequence of GNAT switches into a single switch. For
4546 example, the combined switch
4547
4548 @cindex Combining GNAT switches
4549 @smallexample
4550 -gnatofi3
4551 @end smallexample
4552
4553 @noindent
4554 is equivalent to specifying the following sequence of switches:
4555
4556 @smallexample
4557 -gnato -gnatf -gnati3
4558 @end smallexample
4559 @end ifclear
4560
4561 @noindent
4562 The following restrictions apply to the combination of switches
4563 in this manner:
4564
4565 @itemize @bullet
4566 @item
4567 The switch @option{-gnatc} if combined with other switches must come
4568 first in the string.
4569
4570 @item
4571 The switch @option{-gnats} if combined with other switches must come
4572 first in the string.
4573
4574 @item
4575 The switches
4576 ^^@option{/DISTRIBUTION_STUBS=},^
4577 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4578 switches, and only one of them may appear in the command line.
4579
4580 @ifclear vms
4581 @item
4582 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4583 switch), then all further characters in the switch are interpreted
4584 as style modifiers (see description of @option{-gnaty}).
4585
4586 @item
4587 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4588 switch), then all further characters in the switch are interpreted
4589 as debug flags (see description of @option{-gnatd}).
4590
4591 @item
4592 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4593 switch), then all further characters in the switch are interpreted
4594 as warning mode modifiers (see description of @option{-gnatw}).
4595
4596 @item
4597 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4598 switch), then all further characters in the switch are interpreted
4599 as validity checking options (@pxref{Validity Checking}).
4600
4601 @item
4602 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4603 a combined list of options.
4604 @end ifclear
4605 @end itemize
4606
4607 @node Output and Error Message Control
4608 @subsection Output and Error Message Control
4609 @findex stderr
4610
4611 @noindent
4612 The standard default format for error messages is called ``brief format''.
4613 Brief format messages are written to @file{stderr} (the standard error
4614 file) and have the following form:
4615
4616 @smallexample
4617 e.adb:3:04: Incorrect spelling of keyword "function"
4618 e.adb:4:20: ";" should be "is"
4619 @end smallexample
4620
4621 @noindent
4622 The first integer after the file name is the line number in the file,
4623 and the second integer is the column number within the line.
4624 @ifclear vms
4625 @code{GPS} can parse the error messages
4626 and point to the referenced character.
4627 @end ifclear
4628 The following switches provide control over the error message
4629 format:
4630
4631 @table @option
4632 @c !sort!
4633 @item -gnatv
4634 @cindex @option{-gnatv} (@command{gcc})
4635 @findex stdout
4636 @ifclear vms
4637 The v stands for verbose.
4638 @end ifclear
4639 The effect of this setting is to write long-format error
4640 messages to @file{stdout} (the standard output file.
4641 The same program compiled with the
4642 @option{-gnatv} switch would generate:
4643
4644 @smallexample
4645 @cartouche
4646 3. funcion X (Q : Integer)
4647    |
4648 >>> Incorrect spelling of keyword "function"
4649 4. return Integer;
4650                  |
4651 >>> ";" should be "is"
4652 @end cartouche
4653 @end smallexample
4654
4655 @noindent
4656 The vertical bar indicates the location of the error, and the @samp{>>>}
4657 prefix can be used to search for error messages. When this switch is
4658 used the only source lines output are those with errors.
4659
4660 @item -gnatl
4661 @cindex @option{-gnatl} (@command{gcc})
4662 @ifclear vms
4663 The @code{l} stands for list.
4664 @end ifclear
4665 This switch causes a full listing of
4666 the file to be generated. In the case where a body is
4667 compiled, the corresponding spec is also listed, along
4668 with any subunits. Typical output from compiling a package
4669 body @file{p.adb} might look like:
4670
4671 @smallexample @c ada
4672 @cartouche
4673  Compiling: p.adb
4674
4675      1. package body p is
4676      2.    procedure a;
4677      3.    procedure a is separate;
4678      4. begin
4679      5.    null
4680                |
4681         >>> missing ";"
4682
4683      6. end;
4684
4685 Compiling: p.ads
4686
4687      1. package p is
4688      2.    pragma Elaborate_Body
4689                                 |
4690         >>> missing ";"
4691
4692      3. end p;
4693
4694 Compiling: p-a.adb
4695
4696      1. separate p
4697                 |
4698         >>> missing "("
4699
4700      2. procedure a is
4701      3. begin
4702      4.    null
4703                |
4704         >>> missing ";"
4705
4706      5. end;
4707 @end cartouche
4708 @end smallexample
4709
4710 @noindent
4711 @findex stderr
4712 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4713 standard output is redirected, a brief summary is written to
4714 @file{stderr} (standard error) giving the number of error messages and
4715 warning messages generated.
4716
4717 @item -^gnatl^OUTPUT_FILE^=file
4718 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4719 This has the same effect as @option{-gnatl} except that the output is
4720 written to a file instead of to standard output. If the given name
4721 @file{fname} does not start with a period, then it is the full name
4722 of the file to be written. If @file{fname} is an extension, it is
4723 appended to the name of the file being compiled. For example, if
4724 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4725 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4726
4727 @item -gnatU
4728 @cindex @option{-gnatU} (@command{gcc})
4729 This switch forces all error messages to be preceded by the unique
4730 string ``error:''. This means that error messages take a few more
4731 characters in space, but allows easy searching for and identification
4732 of error messages.
4733
4734 @item -gnatb
4735 @cindex @option{-gnatb} (@command{gcc})
4736 @ifclear vms
4737 The @code{b} stands for brief.
4738 @end ifclear
4739 This switch causes GNAT to generate the
4740 brief format error messages to @file{stderr} (the standard error
4741 file) as well as the verbose
4742 format message or full listing (which as usual is written to
4743 @file{stdout} (the standard output file).
4744
4745 @item -gnatm=@var{n}
4746 @cindex @option{-gnatm} (@command{gcc})
4747 @ifclear vms
4748 The @code{m} stands for maximum.
4749 @end ifclear
4750 @var{n} is a decimal integer in the
4751 range of 1 to 999999 and limits the number of error or warning
4752 messages to be generated. For example, using
4753 @option{-gnatm2} might yield
4754
4755 @smallexample
4756 e.adb:3:04: Incorrect spelling of keyword "function"
4757 e.adb:5:35: missing ".."
4758 fatal error: maximum number of errors detected
4759 compilation abandoned
4760 @end smallexample
4761
4762 @noindent
4763 The default setting if
4764 no switch is given is 9999. If the number of warnings reaches this
4765 limit, then a message is output and further warnings are suppressed,
4766 but the compilation is continued. If the number of error messages
4767 reaches this limit, then a message is output and the compilation
4768 is abandoned. A value of zero means that no limit applies.
4769
4770 @noindent
4771 Note that the equal sign is optional, so the switches
4772 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4773
4774 @item -gnatf
4775 @cindex @option{-gnatf} (@command{gcc})
4776 @cindex Error messages, suppressing
4777 @ifclear vms
4778 The @code{f} stands for full.
4779 @end ifclear
4780 Normally, the compiler suppresses error messages that are likely to be
4781 redundant. This switch causes all error
4782 messages to be generated. In particular, in the case of
4783 references to undefined variables. If a given variable is referenced
4784 several times, the normal format of messages is
4785 @smallexample
4786 e.adb:7:07: "V" is undefined (more references follow)
4787 @end smallexample
4788
4789 @noindent
4790 where the parenthetical comment warns that there are additional
4791 references to the variable @code{V}. Compiling the same program with the
4792 @option{-gnatf} switch yields
4793
4794 @smallexample
4795 e.adb:7:07: "V" is undefined
4796 e.adb:8:07: "V" is undefined
4797 e.adb:8:12: "V" is undefined
4798 e.adb:8:16: "V" is undefined
4799 e.adb:9:07: "V" is undefined
4800 e.adb:9:12: "V" is undefined
4801 @end smallexample
4802
4803 @noindent
4804 The @option{-gnatf} switch also generates additional information for
4805 some error messages.  Some examples are:
4806
4807 @itemize @bullet
4808 @item
4809 Details on possibly non-portable unchecked conversion
4810 @item
4811 List possible interpretations for ambiguous calls
4812 @item
4813 Additional details on incorrect parameters
4814 @end itemize
4815
4816 @item -gnatjnn
4817 @cindex @option{-gnatjnn} (@command{gcc})
4818 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4819 with continuation lines are treated as though the continuation lines were
4820 separate messages (and so a warning with two continuation lines counts as
4821 three warnings, and is listed as three separate messages).
4822
4823 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4824 messages are output in a different manner. A message and all its continuation
4825 lines are treated as a unit, and count as only one warning or message in the
4826 statistics totals. Furthermore, the message is reformatted so that no line
4827 is longer than nn characters.
4828
4829 @item -gnatq
4830 @cindex @option{-gnatq} (@command{gcc})
4831 @ifclear vms
4832 The @code{q} stands for quit (really ``don't quit'').
4833 @end ifclear
4834 In normal operation mode, the compiler first parses the program and
4835 determines if there are any syntax errors. If there are, appropriate
4836 error messages are generated and compilation is immediately terminated.
4837 This switch tells
4838 GNAT to continue with semantic analysis even if syntax errors have been
4839 found. This may enable the detection of more errors in a single run. On
4840 the other hand, the semantic analyzer is more likely to encounter some
4841 internal fatal error when given a syntactically invalid tree.
4842
4843 @item -gnatQ
4844 @cindex @option{-gnatQ} (@command{gcc})
4845 In normal operation mode, the @file{ALI} file is not generated if any
4846 illegalities are detected in the program. The use of @option{-gnatQ} forces
4847 generation of the @file{ALI} file. This file is marked as being in
4848 error, so it cannot be used for binding purposes, but it does contain
4849 reasonably complete cross-reference information, and thus may be useful
4850 for use by tools (e.g., semantic browsing tools or integrated development
4851 environments) that are driven from the @file{ALI} file. This switch
4852 implies @option{-gnatq}, since the semantic phase must be run to get a
4853 meaningful ALI file.
4854
4855 In addition, if @option{-gnatt} is also specified, then the tree file is
4856 generated even if there are illegalities. It may be useful in this case
4857 to also specify @option{-gnatq} to ensure that full semantic processing
4858 occurs. The resulting tree file can be processed by ASIS, for the purpose
4859 of providing partial information about illegal units, but if the error
4860 causes the tree to be badly malformed, then ASIS may crash during the
4861 analysis.
4862
4863 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4864 being in error, @command{gnatmake} will attempt to recompile the source when it
4865 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4866
4867 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4868 since ALI files are never generated if @option{-gnats} is set.
4869
4870 @end table
4871
4872 @node Warning Message Control
4873 @subsection Warning Message Control
4874 @cindex Warning messages
4875 @noindent
4876 In addition to error messages, which correspond to illegalities as defined
4877 in the Ada Reference Manual, the compiler detects two kinds of warning
4878 situations.
4879
4880 First, the compiler considers some constructs suspicious and generates a
4881 warning message to alert you to a possible error. Second, if the
4882 compiler detects a situation that is sure to raise an exception at
4883 run time, it generates a warning message. The following shows an example
4884 of warning messages:
4885 @smallexample
4886 e.adb:4:24: warning: creation of object may raise Storage_Error
4887 e.adb:10:17: warning: static value out of range
4888 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4889 @end smallexample
4890
4891 @noindent
4892 GNAT considers a large number of situations as appropriate
4893 for the generation of warning messages. As always, warnings are not
4894 definite indications of errors. For example, if you do an out-of-range
4895 assignment with the deliberate intention of raising a
4896 @code{Constraint_Error} exception, then the warning that may be
4897 issued does not indicate an error. Some of the situations for which GNAT
4898 issues warnings (at least some of the time) are given in the following
4899 list. This list is not complete, and new warnings are often added to
4900 subsequent versions of GNAT. The list is intended to give a general idea
4901 of the kinds of warnings that are generated.
4902
4903 @itemize @bullet
4904 @item
4905 Possible infinitely recursive calls
4906
4907 @item
4908 Out-of-range values being assigned
4909
4910 @item
4911 Possible order of elaboration problems
4912
4913 @item
4914 Assertions (pragma Assert) that are sure to fail
4915
4916 @item
4917 Unreachable code
4918
4919 @item
4920 Address clauses with possibly unaligned values, or where an attempt is
4921 made to overlay a smaller variable with a larger one.
4922
4923 @item
4924 Fixed-point type declarations with a null range
4925
4926 @item
4927 Direct_IO or Sequential_IO instantiated with a type that has access values
4928
4929 @item
4930 Variables that are never assigned a value
4931
4932 @item
4933 Variables that are referenced before being initialized
4934
4935 @item
4936 Task entries with no corresponding @code{accept} statement
4937
4938 @item
4939 Duplicate accepts for the same task entry in a @code{select}
4940
4941 @item
4942 Objects that take too much storage
4943
4944 @item
4945 Unchecked conversion between types of differing sizes
4946
4947 @item
4948 Missing @code{return} statement along some execution path in a function
4949
4950 @item
4951 Incorrect (unrecognized) pragmas
4952
4953 @item
4954 Incorrect external names
4955
4956 @item
4957 Allocation from empty storage pool
4958
4959 @item
4960 Potentially blocking operation in protected type
4961
4962 @item
4963 Suspicious parenthesization of expressions
4964
4965 @item
4966 Mismatching bounds in an aggregate
4967
4968 @item
4969 Attempt to return local value by reference
4970
4971 @item
4972 Premature instantiation of a generic body
4973
4974 @item
4975 Attempt to pack aliased components
4976
4977 @item
4978 Out of bounds array subscripts
4979
4980 @item
4981 Wrong length on string assignment
4982
4983 @item
4984 Violations of style rules if style checking is enabled
4985
4986 @item
4987 Unused @code{with} clauses
4988
4989 @item
4990 @code{Bit_Order} usage that does not have any effect
4991
4992 @item
4993 @code{Standard.Duration} used to resolve universal fixed expression
4994
4995 @item
4996 Dereference of possibly null value
4997
4998 @item
4999 Declaration that is likely to cause storage error
5000
5001 @item
5002 Internal GNAT unit @code{with}'ed by application unit
5003
5004 @item
5005 Values known to be out of range at compile time
5006
5007 @item
5008 Unreferenced labels and variables
5009
5010 @item
5011 Address overlays that could clobber memory
5012
5013 @item
5014 Unexpected initialization when address clause present
5015
5016 @item
5017 Bad alignment for address clause
5018
5019 @item
5020 Useless type conversions
5021
5022 @item
5023 Redundant assignment statements and other redundant constructs
5024
5025 @item
5026 Useless exception handlers
5027
5028 @item
5029 Accidental hiding of name by child unit
5030
5031 @item
5032 Access before elaboration detected at compile time
5033
5034 @item
5035 A range in a @code{for} loop that is known to be null or might be null
5036
5037 @end itemize
5038
5039 @noindent
5040 The following section lists compiler switches that are available
5041 to control the handling of warning messages. It is also possible
5042 to exercise much finer control over what warnings are issued and
5043 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5044 gnat_rm, GNAT Reference manual}.
5045
5046 @table @option
5047 @c !sort!
5048 @item -gnatwa
5049 @emph{Activate all optional errors.}
5050 @cindex @option{-gnatwa} (@command{gcc})
5051 This switch activates most optional warning messages, see remaining list
5052 in this section for details on optional warning messages that can be
5053 individually controlled.  The warnings that are not turned on by this
5054 switch are
5055 @option{-gnatwd} (implicit dereferencing),
5056 @option{-gnatwh} (hiding),
5057 @option{-gnatwl} (elaboration warnings),
5058 @option{-gnatw.o} (warn on values set by out parameters ignored)
5059 and @option{-gnatwt} (tracking of deleted conditional code).
5060 All other optional warnings are turned on.
5061
5062 @item -gnatwA
5063 @emph{Suppress all optional errors.}
5064 @cindex @option{-gnatwA} (@command{gcc})
5065 This switch suppresses all optional warning messages, see remaining list
5066 in this section for details on optional warning messages that can be
5067 individually controlled.
5068
5069 @item -gnatw.a
5070 @emph{Activate warnings on failing assertions.}
5071 @cindex @option{-gnatw.a} (@command{gcc})
5072 @cindex Assert failures
5073 This switch activates warnings for assertions where the compiler can tell at
5074 compile time that the assertion will fail. Note that this warning is given
5075 even if assertions are disabled. The default is that such warnings are
5076 generated.
5077
5078 @item -gnatw.A
5079 @emph{Suppress warnings on failing assertions.}
5080 @cindex @option{-gnatw.A} (@command{gcc})
5081 @cindex Assert failures
5082 This switch suppresses warnings for assertions where the compiler can tell at
5083 compile time that the assertion will fail.
5084
5085 @item -gnatwb
5086 @emph{Activate warnings on bad fixed values.}
5087 @cindex @option{-gnatwb} (@command{gcc})
5088 @cindex Bad fixed values
5089 @cindex Fixed-point Small value
5090 @cindex Small value
5091 This switch activates warnings for static fixed-point expressions whose
5092 value is not an exact multiple of Small. Such values are implementation
5093 dependent, since an implementation is free to choose either of the multiples
5094 that surround the value. GNAT always chooses the closer one, but this is not
5095 required behavior, and it is better to specify a value that is an exact
5096 multiple, ensuring predictable execution. The default is that such warnings
5097 are not generated.
5098
5099 @item -gnatwB
5100 @emph{Suppress warnings on bad fixed values.}
5101 @cindex @option{-gnatwB} (@command{gcc})
5102 This switch suppresses warnings for static fixed-point expressions whose
5103 value is not an exact multiple of Small.
5104
5105 @item -gnatw.b
5106 @emph{Activate warnings on biased representation.}
5107 @cindex @option{-gnatw.b} (@command{gcc})
5108 @cindex Biased representation
5109 This switch activates warnings when a size clause, value size clause, component
5110 clause, or component size clause forces the use of biased representation for an
5111 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5112 to represent 10/11). The default is that such warnings are generated.
5113
5114 @item -gnatw.B
5115 @emph{Suppress warnings on biased representation.}
5116 @cindex @option{-gnatwB} (@command{gcc})
5117 This switch suppresses warnings for representation clauses that force the use
5118 of biased representation.
5119
5120 @item -gnatwc
5121 @emph{Activate warnings on conditionals.}
5122 @cindex @option{-gnatwc} (@command{gcc})
5123 @cindex Conditionals, constant
5124 This switch activates warnings for conditional expressions used in
5125 tests that are known to be True or False at compile time. The default
5126 is that such warnings are not generated.
5127 Note that this warning does
5128 not get issued for the use of boolean variables or constants whose
5129 values are known at compile time, since this is a standard technique
5130 for conditional compilation in Ada, and this would generate too many
5131 false positive warnings.
5132
5133 This warning option also activates a special test for comparisons using
5134 the operators ``>='' and`` <=''.
5135 If the compiler can tell that only the equality condition is possible,
5136 then it will warn that the ``>'' or ``<'' part of the test
5137 is useless and that the operator could be replaced by ``=''.
5138 An example would be comparing a @code{Natural} variable <= 0.
5139
5140 This warning option also generates warnings if
5141 one or both tests is optimized away in a membership test for integer
5142 values if the result can be determined at compile time. Range tests on
5143 enumeration types are not included, since it is common for such tests
5144 to include an end point.
5145
5146 This warning can also be turned on using @option{-gnatwa}.
5147
5148 @item -gnatwC
5149 @emph{Suppress warnings on conditionals.}
5150 @cindex @option{-gnatwC} (@command{gcc})
5151 This switch suppresses warnings for conditional expressions used in
5152 tests that are known to be True or False at compile time.
5153
5154 @item -gnatw.c
5155 @emph{Activate warnings on missing component clauses.}
5156 @cindex @option{-gnatw.c} (@command{gcc})
5157 @cindex Component clause, missing
5158 This switch activates warnings for record components where a record
5159 representation clause is present and has component clauses for the
5160 majority, but not all, of the components. A warning is given for each
5161 component for which no component clause is present.
5162
5163 This warning can also be turned on using @option{-gnatwa}.
5164
5165 @item -gnatw.C
5166 @emph{Suppress warnings on missing component clauses.}
5167 @cindex @option{-gnatwC} (@command{gcc})
5168 This switch suppresses warnings for record components that are
5169 missing a component clause in the situation described above.
5170
5171 @item -gnatwd
5172 @emph{Activate warnings on implicit dereferencing.}
5173 @cindex @option{-gnatwd} (@command{gcc})
5174 If this switch is set, then the use of a prefix of an access type
5175 in an indexed component, slice, or selected component without an
5176 explicit @code{.all} will generate a warning. With this warning
5177 enabled, access checks occur only at points where an explicit
5178 @code{.all} appears in the source code (assuming no warnings are
5179 generated as a result of this switch). The default is that such
5180 warnings are not generated.
5181 Note that @option{-gnatwa} does not affect the setting of
5182 this warning option.
5183
5184 @item -gnatwD
5185 @emph{Suppress warnings on implicit dereferencing.}
5186 @cindex @option{-gnatwD} (@command{gcc})
5187 @cindex Implicit dereferencing
5188 @cindex Dereferencing, implicit
5189 This switch suppresses warnings for implicit dereferences in
5190 indexed components, slices, and selected components.
5191
5192 @item -gnatwe
5193 @emph{Treat warnings as errors.}
5194 @cindex @option{-gnatwe} (@command{gcc})
5195 @cindex Warnings, treat as error
5196 This switch causes warning messages to be treated as errors.
5197 The warning string still appears, but the warning messages are counted
5198 as errors, and prevent the generation of an object file.
5199
5200 @item -gnatw.e
5201 @emph{Activate every optional warning}
5202 @cindex @option{-gnatw.e} (@command{gcc})
5203 @cindex Warnings, activate every optional warning
5204 This switch activates all optional warnings, including those which
5205 are not activated by @code{-gnatwa}.
5206
5207 @item -gnatwf
5208 @emph{Activate warnings on unreferenced formals.}
5209 @cindex @option{-gnatwf} (@command{gcc})
5210 @cindex Formals, unreferenced
5211 This switch causes a warning to be generated if a formal parameter
5212 is not referenced in the body of the subprogram. This warning can
5213 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5214 default is that these warnings are not generated.
5215
5216 @item -gnatwF
5217 @emph{Suppress warnings on unreferenced formals.}
5218 @cindex @option{-gnatwF} (@command{gcc})
5219 This switch suppresses warnings for unreferenced formal
5220 parameters. Note that the
5221 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5222 effect of warning on unreferenced entities other than subprogram
5223 formals.
5224
5225 @item -gnatwg
5226 @emph{Activate warnings on unrecognized pragmas.}
5227 @cindex @option{-gnatwg} (@command{gcc})
5228 @cindex Pragmas, unrecognized
5229 This switch causes a warning to be generated if an unrecognized
5230 pragma is encountered. Apart from issuing this warning, the
5231 pragma is ignored and has no effect. This warning can
5232 also be turned on using @option{-gnatwa}. The default
5233 is that such warnings are issued (satisfying the Ada Reference
5234 Manual requirement that such warnings appear).
5235
5236 @item -gnatwG
5237 @emph{Suppress warnings on unrecognized pragmas.}
5238 @cindex @option{-gnatwG} (@command{gcc})
5239 This switch suppresses warnings for unrecognized pragmas.
5240
5241 @item -gnatwh
5242 @emph{Activate warnings on hiding.}
5243 @cindex @option{-gnatwh} (@command{gcc})
5244 @cindex Hiding of Declarations
5245 This switch activates warnings on hiding declarations.
5246 A declaration is considered hiding
5247 if it is for a non-overloadable entity, and it declares an entity with the
5248 same name as some other entity that is directly or use-visible. The default
5249 is that such warnings are not generated.
5250 Note that @option{-gnatwa} does not affect the setting of this warning option.
5251
5252 @item -gnatwH
5253 @emph{Suppress warnings on hiding.}
5254 @cindex @option{-gnatwH} (@command{gcc})
5255 This switch suppresses warnings on hiding declarations.
5256
5257 @item -gnatwi
5258 @emph{Activate warnings on implementation units.}
5259 @cindex @option{-gnatwi} (@command{gcc})
5260 This switch activates warnings for a @code{with} of an internal GNAT
5261 implementation unit, defined as any unit from the @code{Ada},
5262 @code{Interfaces}, @code{GNAT},
5263 ^^@code{DEC},^ or @code{System}
5264 hierarchies that is not
5265 documented in either the Ada Reference Manual or the GNAT
5266 Programmer's Reference Manual. Such units are intended only
5267 for internal implementation purposes and should not be @code{with}'ed
5268 by user programs. The default is that such warnings are generated
5269 This warning can also be turned on using @option{-gnatwa}.
5270
5271 @item -gnatwI
5272 @emph{Disable warnings on implementation units.}
5273 @cindex @option{-gnatwI} (@command{gcc})
5274 This switch disables warnings for a @code{with} of an internal GNAT
5275 implementation unit.
5276
5277 @item -gnatw.i
5278 @emph{Activate warnings on overlapping actuals.}
5279 @cindex @option{-gnatw.i} (@command{gcc})
5280 This switch enables a warning on statically detectable overlapping actuals in
5281 a subprogram call, when one of the actuals is an in-out parameter, and the
5282 types of the actuals are not by-copy types. The warning is off by default,
5283 and is not included under -gnatwa.
5284
5285 @item -gnatw.I
5286 @emph{Disable warnings on overlapping actuals.}
5287 @cindex @option{-gnatw.I} (@command{gcc})
5288 This switch disables warnings on overlapping actuals in a call..
5289
5290 @item -gnatwj
5291 @emph{Activate warnings on obsolescent features (Annex J).}
5292 @cindex @option{-gnatwj} (@command{gcc})
5293 @cindex Features, obsolescent
5294 @cindex Obsolescent features
5295 If this warning option is activated, then warnings are generated for
5296 calls to subprograms marked with @code{pragma Obsolescent} and
5297 for use of features in Annex J of the Ada Reference Manual. In the
5298 case of Annex J, not all features are flagged. In particular use
5299 of the renamed packages (like @code{Text_IO}) and use of package
5300 @code{ASCII} are not flagged, since these are very common and
5301 would generate many annoying positive warnings. The default is that
5302 such warnings are not generated. This warning is also turned on by
5303 the use of @option{-gnatwa}.
5304
5305 In addition to the above cases, warnings are also generated for
5306 GNAT features that have been provided in past versions but which
5307 have been superseded (typically by features in the new Ada standard).
5308 For example, @code{pragma Ravenscar} will be flagged since its
5309 function is replaced by @code{pragma Profile(Ravenscar)}.
5310
5311 Note that this warning option functions differently from the
5312 restriction @code{No_Obsolescent_Features} in two respects.
5313 First, the restriction applies only to annex J features.
5314 Second, the restriction does flag uses of package @code{ASCII}.
5315
5316 @item -gnatwJ
5317 @emph{Suppress warnings on obsolescent features (Annex J).}
5318 @cindex @option{-gnatwJ} (@command{gcc})
5319 This switch disables warnings on use of obsolescent features.
5320
5321 @item -gnatwk
5322 @emph{Activate warnings on variables that could be constants.}
5323 @cindex @option{-gnatwk} (@command{gcc})
5324 This switch activates warnings for variables that are initialized but
5325 never modified, and then could be declared constants. The default is that
5326 such warnings are not given.
5327 This warning can also be turned on using @option{-gnatwa}.
5328
5329 @item -gnatwK
5330 @emph{Suppress warnings on variables that could be constants.}
5331 @cindex @option{-gnatwK} (@command{gcc})
5332 This switch disables warnings on variables that could be declared constants.
5333
5334 @item -gnatwl
5335 @emph{Activate warnings for elaboration pragmas.}
5336 @cindex @option{-gnatwl} (@command{gcc})
5337 @cindex Elaboration, warnings
5338 This switch activates warnings on missing
5339 @code{Elaborate_All} and @code{Elaborate} pragmas.
5340 See the section in this guide on elaboration checking for details on
5341 when such pragmas should be used. In dynamic elaboration mode, this switch
5342 generations warnings about the need to add elaboration pragmas. Note however,
5343 that if you blindly follow these warnings, and add @code{Elaborate_All}
5344 warnings wherever they are recommended, you basically end up with the
5345 equivalent of the static elaboration model, which may not be what you want for
5346 legacy code for which the static model does not work.
5347
5348 For the static model, the messages generated are labeled "info:" (for
5349 information messages). They are not warnings to add elaboration pragmas,
5350 merely informational messages showing what implicit elaboration pragmas
5351 have been added, for use in analyzing elaboration circularity problems.
5352
5353 Warnings are also generated if you
5354 are using the static mode of elaboration, and a @code{pragma Elaborate}
5355 is encountered. The default is that such warnings
5356 are not generated.
5357 This warning is not automatically turned on by the use of @option{-gnatwa}.
5358
5359 @item -gnatwL
5360 @emph{Suppress warnings for elaboration pragmas.}
5361 @cindex @option{-gnatwL} (@command{gcc})
5362 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5363 See the section in this guide on elaboration checking for details on
5364 when such pragmas should be used.
5365
5366 @item -gnatwm
5367 @emph{Activate warnings on modified but unreferenced variables.}
5368 @cindex @option{-gnatwm} (@command{gcc})
5369 This switch activates warnings for variables that are assigned (using
5370 an initialization value or with one or more assignment statements) but
5371 whose value is never read. The warning is suppressed for volatile
5372 variables and also for variables that are renamings of other variables
5373 or for which an address clause is given.
5374 This warning can also be turned on using @option{-gnatwa}.
5375 The default is that these warnings are not given.
5376
5377 @item -gnatwM
5378 @emph{Disable warnings on modified but unreferenced variables.}
5379 @cindex @option{-gnatwM} (@command{gcc})
5380 This switch disables warnings for variables that are assigned or
5381 initialized, but never read.
5382
5383 @item -gnatw.m
5384 @emph{Activate warnings on suspicious modulus values.}
5385 @cindex @option{-gnatw.m} (@command{gcc})
5386 This switch activates warnings for modulus values that seem suspicious.
5387 The cases caught are where the size is the same as the modulus (e.g.
5388 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5389 with no size clause. The guess in both cases is that 2**x was intended
5390 rather than x. The default is that these warnings are given.
5391
5392 @item -gnatw.M
5393 @emph{Disable warnings on suspicious modulus values.}
5394 @cindex @option{-gnatw.M} (@command{gcc})
5395 This switch disables warnings for suspicious modulus values.
5396
5397 @item -gnatwn
5398 @emph{Set normal warnings mode.}
5399 @cindex @option{-gnatwn} (@command{gcc})
5400 This switch sets normal warning mode, in which enabled warnings are
5401 issued and treated as warnings rather than errors. This is the default
5402 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5403 an explicit @option{-gnatws} or
5404 @option{-gnatwe}. It also cancels the effect of the
5405 implicit @option{-gnatwe} that is activated by the
5406 use of @option{-gnatg}.
5407
5408 @item -gnatwo
5409 @emph{Activate warnings on address clause overlays.}
5410 @cindex @option{-gnatwo} (@command{gcc})
5411 @cindex Address Clauses, warnings
5412 This switch activates warnings for possibly unintended initialization
5413 effects of defining address clauses that cause one variable to overlap
5414 another. The default is that such warnings are generated.
5415 This warning can also be turned on using @option{-gnatwa}.
5416
5417 @item -gnatwO
5418 @emph{Suppress warnings on address clause overlays.}
5419 @cindex @option{-gnatwO} (@command{gcc})
5420 This switch suppresses warnings on possibly unintended initialization
5421 effects of defining address clauses that cause one variable to overlap
5422 another.
5423
5424 @item -gnatw.o
5425 @emph{Activate warnings on modified but unreferenced out parameters.}
5426 @cindex @option{-gnatw.o} (@command{gcc})
5427 This switch activates warnings for variables that are modified by using
5428 them as actuals for a call to a procedure with an out mode formal, where
5429 the resulting assigned value is never read. It is applicable in the case
5430 where there is more than one out mode formal. If there is only one out
5431 mode formal, the warning is issued by default (controlled by -gnatwu).
5432 The warning is suppressed for volatile
5433 variables and also for variables that are renamings of other variables
5434 or for which an address clause is given.
5435 The default is that these warnings are not given. Note that this warning
5436 is not included in -gnatwa, it must be activated explicitly.
5437
5438 @item -gnatw.O
5439 @emph{Disable warnings on modified but unreferenced out parameters.}
5440 @cindex @option{-gnatw.O} (@command{gcc})
5441 This switch suppresses warnings for variables that are modified by using
5442 them as actuals for a call to a procedure with an out mode formal, where
5443 the resulting assigned value is never read.
5444
5445 @item -gnatwp
5446 @emph{Activate warnings on ineffective pragma Inlines.}
5447 @cindex @option{-gnatwp} (@command{gcc})
5448 @cindex Inlining, warnings
5449 This switch activates warnings for failure of front end inlining
5450 (activated by @option{-gnatN}) to inline a particular call. There are
5451 many reasons for not being able to inline a call, including most
5452 commonly that the call is too complex to inline. The default is
5453 that such warnings are not given.
5454 This warning can also be turned on using @option{-gnatwa}.
5455 Warnings on ineffective inlining by the gcc back-end can be activated
5456 separately, using the gcc switch -Winline.
5457
5458 @item -gnatwP
5459 @emph{Suppress warnings on ineffective pragma Inlines.}
5460 @cindex @option{-gnatwP} (@command{gcc})
5461 This switch suppresses warnings on ineffective pragma Inlines. If the
5462 inlining mechanism cannot inline a call, it will simply ignore the
5463 request silently.
5464
5465 @item -gnatw.p
5466 @emph{Activate warnings on parameter ordering.}
5467 @cindex @option{-gnatw.p} (@command{gcc})
5468 @cindex Parameter order, warnings
5469 This switch activates warnings for cases of suspicious parameter
5470 ordering when the list of arguments are all simple identifiers that
5471 match the names of the formals, but are in a different order. The
5472 warning is suppressed if any use of named parameter notation is used,
5473 so this is the appropriate way to suppress a false positive (and
5474 serves to emphasize that the "misordering" is deliberate). The
5475 default is
5476 that such warnings are not given.
5477 This warning can also be turned on using @option{-gnatwa}.
5478
5479 @item -gnatw.P
5480 @emph{Suppress warnings on parameter ordering.}
5481 @cindex @option{-gnatw.P} (@command{gcc})
5482 This switch suppresses warnings on cases of suspicious parameter
5483 ordering.
5484
5485 @item -gnatwq
5486 @emph{Activate warnings on questionable missing parentheses.}
5487 @cindex @option{-gnatwq} (@command{gcc})
5488 @cindex Parentheses, warnings
5489 This switch activates warnings for cases where parentheses are not used and
5490 the result is potential ambiguity from a readers point of view. For example
5491 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5492 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5493 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5494 follow the rule of always parenthesizing to make the association clear, and
5495 this warning switch warns if such parentheses are not present. The default
5496 is that these warnings are given.
5497 This warning can also be turned on using @option{-gnatwa}.
5498
5499 @item -gnatwQ
5500 @emph{Suppress warnings on questionable missing parentheses.}
5501 @cindex @option{-gnatwQ} (@command{gcc})
5502 This switch suppresses warnings for cases where the association is not
5503 clear and the use of parentheses is preferred.
5504
5505 @item -gnatwr
5506 @emph{Activate warnings on redundant constructs.}
5507 @cindex @option{-gnatwr} (@command{gcc})
5508 This switch activates warnings for redundant constructs. The following
5509 is the current list of constructs regarded as redundant:
5510
5511 @itemize @bullet
5512 @item
5513 Assignment of an item to itself.
5514 @item
5515 Type conversion that converts an expression to its own type.
5516 @item
5517 Use of the attribute @code{Base} where @code{typ'Base} is the same
5518 as @code{typ}.
5519 @item
5520 Use of pragma @code{Pack} when all components are placed by a record
5521 representation clause.
5522 @item
5523 Exception handler containing only a reraise statement (raise with no
5524 operand) which has no effect.
5525 @item
5526 Use of the operator abs on an operand that is known at compile time
5527 to be non-negative
5528 @item
5529 Comparison of boolean expressions to an explicit True value.
5530 @end itemize
5531
5532 This warning can also be turned on using @option{-gnatwa}.
5533 The default is that warnings for redundant constructs are not given.
5534
5535 @item -gnatwR
5536 @emph{Suppress warnings on redundant constructs.}
5537 @cindex @option{-gnatwR} (@command{gcc})
5538 This switch suppresses warnings for redundant constructs.
5539
5540 @item -gnatw.r
5541 @emph{Activate warnings for object renaming function.}
5542 @cindex @option{-gnatw.r} (@command{gcc})
5543 This switch activates warnings for an object renaming that renames a
5544 function call, which is equivalent to a constant declaration (as
5545 opposed to renaming the function itself).  The default is that these
5546 warnings are given.  This warning can also be turned on using
5547 @option{-gnatwa}.
5548
5549 @item -gnatw.R
5550 @emph{Suppress warnings for object renaming function.}
5551 @cindex @option{-gnatwT} (@command{gcc})
5552 This switch suppresses warnings for object renaming function.
5553
5554 @item -gnatws
5555 @emph{Suppress all warnings.}
5556 @cindex @option{-gnatws} (@command{gcc})
5557 This switch completely suppresses the
5558 output of all warning messages from the GNAT front end.
5559 Note that it does not suppress warnings from the @command{gcc} back end.
5560 To suppress these back end warnings as well, use the switch @option{-w}
5561 in addition to @option{-gnatws}.
5562
5563 @item -gnatwt
5564 @emph{Activate warnings for tracking of deleted conditional code.}
5565 @cindex @option{-gnatwt} (@command{gcc})
5566 @cindex Deactivated code, warnings
5567 @cindex Deleted code, warnings
5568 This switch activates warnings for tracking of code in conditionals (IF and
5569 CASE statements) that is detected to be dead code which cannot be executed, and
5570 which is removed by the front end. This warning is off by default, and is not
5571 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5572 useful for detecting deactivated code in certified applications.
5573
5574 @item -gnatwT
5575 @emph{Suppress warnings for tracking of deleted conditional code.}
5576 @cindex @option{-gnatwT} (@command{gcc})
5577 This switch suppresses warnings for tracking of deleted conditional code.
5578
5579 @item -gnatwu
5580 @emph{Activate warnings on unused entities.}
5581 @cindex @option{-gnatwu} (@command{gcc})
5582 This switch activates warnings to be generated for entities that
5583 are declared but not referenced, and for units that are @code{with}'ed
5584 and not
5585 referenced. In the case of packages, a warning is also generated if
5586 no entities in the package are referenced. This means that if the package
5587 is referenced but the only references are in @code{use}
5588 clauses or @code{renames}
5589 declarations, a warning is still generated. A warning is also generated
5590 for a generic package that is @code{with}'ed but never instantiated.
5591 In the case where a package or subprogram body is compiled, and there
5592 is a @code{with} on the corresponding spec
5593 that is only referenced in the body,
5594 a warning is also generated, noting that the
5595 @code{with} can be moved to the body. The default is that
5596 such warnings are not generated.
5597 This switch also activates warnings on unreferenced formals
5598 (it includes the effect of @option{-gnatwf}).
5599 This warning can also be turned on using @option{-gnatwa}.
5600
5601 @item -gnatwU
5602 @emph{Suppress warnings on unused entities.}
5603 @cindex @option{-gnatwU} (@command{gcc})
5604 This switch suppresses warnings for unused entities and packages.
5605 It also turns off warnings on unreferenced formals (and thus includes
5606 the effect of @option{-gnatwF}).
5607
5608 @item -gnatwv
5609 @emph{Activate warnings on unassigned variables.}
5610 @cindex @option{-gnatwv} (@command{gcc})
5611 @cindex Unassigned variable warnings
5612 This switch activates warnings for access to variables which
5613 may not be properly initialized. The default is that
5614 such warnings are generated.
5615 This warning can also be turned on using @option{-gnatwa}.
5616
5617 @item -gnatwV
5618 @emph{Suppress warnings on unassigned variables.}
5619 @cindex @option{-gnatwV} (@command{gcc})
5620 This switch suppresses warnings for access to variables which
5621 may not be properly initialized.
5622 For variables of a composite type, the warning can also be suppressed in
5623 Ada 2005 by using a default initialization with a box. For example, if
5624 Table is an array of records whose components are only partially uninitialized,
5625 then the following code:
5626
5627 @smallexample @c ada
5628    Tab : Table := (others => <>);
5629 @end smallexample
5630
5631 will suppress warnings on subsequent statements that access components
5632 of variable Tab.
5633
5634 @item -gnatww
5635 @emph{Activate warnings on wrong low bound assumption.}
5636 @cindex @option{-gnatww} (@command{gcc})
5637 @cindex String indexing warnings
5638 This switch activates warnings for indexing an unconstrained string parameter
5639 with a literal or S'Length. This is a case where the code is assuming that the
5640 low bound is one, which is in general not true (for example when a slice is
5641 passed). The default is that such warnings are generated.
5642 This warning can also be turned on using @option{-gnatwa}.
5643
5644 @item -gnatwW
5645 @emph{Suppress warnings on wrong low bound assumption.}
5646 @cindex @option{-gnatwW} (@command{gcc})
5647 This switch suppresses warnings for indexing an unconstrained string parameter
5648 with a literal or S'Length. Note that this warning can also be suppressed
5649 in a particular case by adding an
5650 assertion that the lower bound is 1,
5651 as shown in the following example.
5652
5653 @smallexample @c ada
5654    procedure K (S : String) is
5655       pragma Assert (S'First = 1);
5656       @dots{}
5657 @end smallexample
5658
5659 @item -gnatw.w
5660 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5661 @cindex @option{-gnatw.w} (@command{gcc})
5662 @cindex Warnings Off control
5663 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5664 where either the pragma is entirely useless (because it suppresses no
5665 warnings), or it could be replaced by @code{pragma Unreferenced} or
5666 @code{pragma Unmodified}.The default is that these warnings are not given.
5667 Note that this warning is not included in -gnatwa, it must be
5668 activated explicitly.
5669
5670 @item -gnatw.W
5671 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5672 @cindex @option{-gnatw.W} (@command{gcc})
5673 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5674
5675 @item -gnatwx
5676 @emph{Activate warnings on Export/Import pragmas.}
5677 @cindex @option{-gnatwx} (@command{gcc})
5678 @cindex Export/Import pragma warnings
5679 This switch activates warnings on Export/Import pragmas when
5680 the compiler detects a possible conflict between the Ada and
5681 foreign language calling sequences. For example, the use of
5682 default parameters in a convention C procedure is dubious
5683 because the C compiler cannot supply the proper default, so
5684 a warning is issued. The default is that such warnings are
5685 generated.
5686 This warning can also be turned on using @option{-gnatwa}.
5687
5688 @item -gnatwX
5689 @emph{Suppress warnings on Export/Import pragmas.}
5690 @cindex @option{-gnatwX} (@command{gcc})
5691 This switch suppresses warnings on Export/Import pragmas.
5692 The sense of this is that you are telling the compiler that
5693 you know what you are doing in writing the pragma, and it
5694 should not complain at you.
5695
5696 @item -gnatw.x
5697 @emph{Activate warnings for No_Exception_Propagation mode.}
5698 @cindex @option{-gnatwm} (@command{gcc})
5699 This switch activates warnings for exception usage when pragma Restrictions
5700 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5701 explicit exception raises which are not covered by a local handler, and for
5702 exception handlers which do not cover a local raise. The default is that these
5703 warnings are not given.
5704
5705 @item -gnatw.X
5706 @emph{Disable warnings for No_Exception_Propagation mode.}
5707 This switch disables warnings for exception usage when pragma Restrictions
5708 (No_Exception_Propagation) is in effect.
5709
5710 @item -gnatwy
5711 @emph{Activate warnings for Ada 2005 compatibility issues.}
5712 @cindex @option{-gnatwy} (@command{gcc})
5713 @cindex Ada 2005 compatibility issues warnings
5714 For the most part Ada 2005 is upwards compatible with Ada 95,
5715 but there are some exceptions (for example the fact that
5716 @code{interface} is now a reserved word in Ada 2005). This
5717 switch activates several warnings to help in identifying
5718 and correcting such incompatibilities. The default is that
5719 these warnings are generated. Note that at one point Ada 2005
5720 was called Ada 0Y, hence the choice of character.
5721 This warning can also be turned on using @option{-gnatwa}.
5722
5723 @item -gnatwY
5724 @emph{Disable warnings for Ada 2005 compatibility issues.}
5725 @cindex @option{-gnatwY} (@command{gcc})
5726 @cindex Ada 2005 compatibility issues warnings
5727 This switch suppresses several warnings intended to help in identifying
5728 incompatibilities between Ada 95 and Ada 2005.
5729
5730 @item -gnatwz
5731 @emph{Activate warnings on unchecked conversions.}
5732 @cindex @option{-gnatwz} (@command{gcc})
5733 @cindex Unchecked_Conversion warnings
5734 This switch activates warnings for unchecked conversions
5735 where the types are known at compile time to have different
5736 sizes. The default
5737 is that such warnings are generated. Warnings are also
5738 generated for subprogram pointers with different conventions,
5739 and, on VMS only, for data pointers with different conventions.
5740 This warning can also be turned on using @option{-gnatwa}.
5741
5742 @item -gnatwZ
5743 @emph{Suppress warnings on unchecked conversions.}
5744 @cindex @option{-gnatwZ} (@command{gcc})
5745 This switch suppresses warnings for unchecked conversions
5746 where the types are known at compile time to have different
5747 sizes or conventions.
5748
5749 @item ^-Wunused^WARNINGS=UNUSED^
5750 @cindex @option{-Wunused}
5751 The warnings controlled by the @option{-gnatw} switch are generated by
5752 the front end of the compiler. The @option{GCC} back end can provide
5753 additional warnings and they are controlled by the @option{-W} switch.
5754 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5755 warnings for entities that are declared but not referenced.
5756
5757 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5758 @cindex @option{-Wuninitialized}
5759 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5760 the back end warning for uninitialized variables. This switch must be
5761 used in conjunction with an optimization level greater than zero.
5762
5763 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5764 @cindex @option{-Wall}
5765 This switch enables all the above warnings from the @option{GCC} back end.
5766 The code generator detects a number of warning situations that are missed
5767 by the @option{GNAT} front end, and this switch can be used to activate them.
5768 The use of this switch also sets the default front end warning mode to
5769 @option{-gnatwa}, that is, most front end warnings activated as well.
5770
5771 @item ^-w^/NO_BACK_END_WARNINGS^
5772 @cindex @option{-w}
5773 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5774 The use of this switch also sets the default front end warning mode to
5775 @option{-gnatws}, that is, front end warnings suppressed as well.
5776
5777 @end table
5778
5779 @noindent
5780 @ifclear vms
5781 A string of warning parameters can be used in the same parameter. For example:
5782
5783 @smallexample
5784 -gnatwaLe
5785 @end smallexample
5786
5787 @noindent
5788 will turn on all optional warnings except for elaboration pragma warnings,
5789 and also specify that warnings should be treated as errors.
5790 @end ifclear
5791 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5792
5793 @table @option
5794 @c !sort!
5795 @item -gnatwC
5796 @item -gnatwD
5797 @item -gnatwF
5798 @item -gnatwg
5799 @item -gnatwH
5800 @item -gnatwi
5801 @item -gnatwJ
5802 @item -gnatwK
5803 @item -gnatwL
5804 @item -gnatwM
5805 @item -gnatwn
5806 @item -gnatwo
5807 @item -gnatwP
5808 @item -gnatwR
5809 @item -gnatwU
5810 @item -gnatwv
5811 @item -gnatwz
5812 @item -gnatwx
5813
5814 @end table
5815
5816 @node Debugging and Assertion Control
5817 @subsection Debugging and Assertion Control
5818
5819 @table @option
5820 @item -gnata
5821 @cindex @option{-gnata} (@command{gcc})
5822 @findex Assert
5823 @findex Debug
5824 @cindex Assertions
5825
5826 @noindent
5827 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5828 are ignored. This switch, where @samp{a} stands for assert, causes
5829 @code{Assert} and @code{Debug} pragmas to be activated.
5830
5831 The pragmas have the form:
5832
5833 @smallexample
5834 @cartouche
5835    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5836                       @var{static-string-expression}@r{]})
5837    @b{pragma} Debug (@var{procedure call})
5838 @end cartouche
5839 @end smallexample
5840
5841 @noindent
5842 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5843 If the result is @code{True}, the pragma has no effect (other than
5844 possible side effects from evaluating the expression). If the result is
5845 @code{False}, the exception @code{Assert_Failure} declared in the package
5846 @code{System.Assertions} is
5847 raised (passing @var{static-string-expression}, if present, as the
5848 message associated with the exception). If no string expression is
5849 given the default is a string giving the file name and line number
5850 of the pragma.
5851
5852 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5853 @code{pragma Debug} may appear within a declaration sequence, allowing
5854 debugging procedures to be called between declarations.
5855
5856 @ifset vms
5857 @item /DEBUG@r{[}=debug-level@r{]}
5858 @itemx  /NODEBUG
5859 Specifies how much debugging information is to be included in
5860 the resulting object file where 'debug-level' is one of the following:
5861 @table @code
5862 @item   TRACEBACK
5863 Include both debugger symbol records and traceback
5864 the object file.
5865 This is the default setting.
5866 @item   ALL
5867 Include both debugger symbol records and traceback in
5868 object file.
5869 @item   NONE
5870 Excludes both debugger symbol records and traceback
5871 the object file. Same as /NODEBUG.
5872 @item   SYMBOLS
5873 Includes only debugger symbol records in the object
5874 file. Note that this doesn't include traceback information.
5875 @end table
5876 @end ifset
5877 @end table
5878
5879 @node Validity Checking
5880 @subsection Validity Checking
5881 @findex Validity Checking
5882
5883 @noindent
5884 The Ada Reference Manual defines the concept of invalid values (see
5885 RM 13.9.1). The primary source of invalid values is uninitialized
5886 variables. A scalar variable that is left uninitialized may contain
5887 an invalid value; the concept of invalid does not apply to access or
5888 composite types.
5889
5890 It is an error to read an invalid value, but the RM does not require
5891 run-time checks to detect such errors, except for some minimal
5892 checking to prevent erroneous execution (i.e. unpredictable
5893 behavior). This corresponds to the @option{-gnatVd} switch below,
5894 which is the default. For example, by default, if the expression of a
5895 case statement is invalid, it will raise Constraint_Error rather than
5896 causing a wild jump, and if an array index on the left-hand side of an
5897 assignment is invalid, it will raise Constraint_Error rather than
5898 overwriting an arbitrary memory location.
5899
5900 The @option{-gnatVa} may be used to enable additional validity checks,
5901 which are not required by the RM. These checks are often very
5902 expensive (which is why the RM does not require them). These checks
5903 are useful in tracking down uninitialized variables, but they are
5904 not usually recommended for production builds.
5905
5906 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5907 control; you can enable whichever validity checks you desire. However,
5908 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5909 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5910 sufficient for non-debugging use.
5911
5912 The @option{-gnatB} switch tells the compiler to assume that all
5913 values are valid (that is, within their declared subtype range)
5914 except in the context of a use of the Valid attribute. This means
5915 the compiler can generate more efficient code, since the range
5916 of values is better known at compile time. However, an uninitialized
5917 variable can cause wild jumps and memory corruption in this mode.
5918
5919 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5920 checking mode as described below.
5921 @ifclear vms
5922 The @code{x} argument is a string of letters that
5923 indicate validity checks that are performed or not performed in addition
5924 to the default checks required by Ada as described above.
5925 @end ifclear
5926 @ifset vms
5927 The options allowed for this qualifier
5928 indicate validity checks that are performed or not performed in addition
5929 to the default checks required by Ada as described above.
5930 @end ifset
5931
5932 @table @option
5933 @c !sort!
5934 @item -gnatVa
5935 @emph{All validity checks.}
5936 @cindex @option{-gnatVa} (@command{gcc})
5937 All validity checks are turned on.
5938 @ifclear vms
5939 That is, @option{-gnatVa} is
5940 equivalent to @option{gnatVcdfimorst}.
5941 @end ifclear
5942
5943 @item -gnatVc
5944 @emph{Validity checks for copies.}
5945 @cindex @option{-gnatVc} (@command{gcc})
5946 The right hand side of assignments, and the initializing values of
5947 object declarations are validity checked.
5948
5949 @item -gnatVd
5950 @emph{Default (RM) validity checks.}
5951 @cindex @option{-gnatVd} (@command{gcc})
5952 Some validity checks are done by default following normal Ada semantics
5953 (RM 13.9.1 (9-11)).
5954 A check is done in case statements that the expression is within the range
5955 of the subtype. If it is not, Constraint_Error is raised.
5956 For assignments to array components, a check is done that the expression used
5957 as index is within the range. If it is not, Constraint_Error is raised.
5958 Both these validity checks may be turned off using switch @option{-gnatVD}.
5959 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5960 switch @option{-gnatVd} will leave the checks turned on.
5961 Switch @option{-gnatVD} should be used only if you are sure that all such
5962 expressions have valid values. If you use this switch and invalid values
5963 are present, then the program is erroneous, and wild jumps or memory
5964 overwriting may occur.
5965
5966 @item -gnatVe
5967 @emph{Validity checks for elementary components.}
5968 @cindex @option{-gnatVe} (@command{gcc})
5969 In the absence of this switch, assignments to record or array components are
5970 not validity checked, even if validity checks for assignments generally
5971 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5972 require valid data, but assignment of individual components does. So for
5973 example, there is a difference between copying the elements of an array with a
5974 slice assignment, compared to assigning element by element in a loop. This
5975 switch allows you to turn off validity checking for components, even when they
5976 are assigned component by component.
5977
5978 @item -gnatVf
5979 @emph{Validity checks for floating-point values.}
5980 @cindex @option{-gnatVf} (@command{gcc})
5981 In the absence of this switch, validity checking occurs only for discrete
5982 values. If @option{-gnatVf} is specified, then validity checking also applies
5983 for floating-point values, and NaNs and infinities are considered invalid,
5984 as well as out of range values for constrained types. Note that this means
5985 that standard IEEE infinity mode is not allowed. The exact contexts
5986 in which floating-point values are checked depends on the setting of other
5987 options. For example,
5988 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5989 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5990 (the order does not matter) specifies that floating-point parameters of mode
5991 @code{in} should be validity checked.
5992
5993 @item -gnatVi
5994 @emph{Validity checks for @code{in} mode parameters}
5995 @cindex @option{-gnatVi} (@command{gcc})
5996 Arguments for parameters of mode @code{in} are validity checked in function
5997 and procedure calls at the point of call.
5998
5999 @item -gnatVm
6000 @emph{Validity checks for @code{in out} mode parameters.}
6001 @cindex @option{-gnatVm} (@command{gcc})
6002 Arguments for parameters of mode @code{in out} are validity checked in
6003 procedure calls at the point of call. The @code{'m'} here stands for
6004 modify, since this concerns parameters that can be modified by the call.
6005 Note that there is no specific option to test @code{out} parameters,
6006 but any reference within the subprogram will be tested in the usual
6007 manner, and if an invalid value is copied back, any reference to it
6008 will be subject to validity checking.
6009
6010 @item -gnatVn
6011 @emph{No validity checks.}
6012 @cindex @option{-gnatVn} (@command{gcc})
6013 This switch turns off all validity checking, including the default checking
6014 for case statements and left hand side subscripts. Note that the use of
6015 the switch @option{-gnatp} suppresses all run-time checks, including
6016 validity checks, and thus implies @option{-gnatVn}. When this switch
6017 is used, it cancels any other @option{-gnatV} previously issued.
6018
6019 @item -gnatVo
6020 @emph{Validity checks for operator and attribute operands.}
6021 @cindex @option{-gnatVo} (@command{gcc})
6022 Arguments for predefined operators and attributes are validity checked.
6023 This includes all operators in package @code{Standard},
6024 the shift operators defined as intrinsic in package @code{Interfaces}
6025 and operands for attributes such as @code{Pos}. Checks are also made
6026 on individual component values for composite comparisons, and on the
6027 expressions in type conversions and qualified expressions. Checks are
6028 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6029
6030 @item -gnatVp
6031 @emph{Validity checks for parameters.}
6032 @cindex @option{-gnatVp} (@command{gcc})
6033 This controls the treatment of parameters within a subprogram (as opposed
6034 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6035 of parameters on a call. If either of these call options is used, then
6036 normally an assumption is made within a subprogram that the input arguments
6037 have been validity checking at the point of call, and do not need checking
6038 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6039 is not made, and parameters are not assumed to be valid, so their validity
6040 will be checked (or rechecked) within the subprogram.
6041
6042 @item -gnatVr
6043 @emph{Validity checks for function returns.}
6044 @cindex @option{-gnatVr} (@command{gcc})
6045 The expression in @code{return} statements in functions is validity
6046 checked.
6047
6048 @item -gnatVs
6049 @emph{Validity checks for subscripts.}
6050 @cindex @option{-gnatVs} (@command{gcc})
6051 All subscripts expressions are checked for validity, whether they appear
6052 on the right side or left side (in default mode only left side subscripts
6053 are validity checked).
6054
6055 @item -gnatVt
6056 @emph{Validity checks for tests.}
6057 @cindex @option{-gnatVt} (@command{gcc})
6058 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6059 statements are checked, as well as guard expressions in entry calls.
6060
6061 @end table
6062
6063 @noindent
6064 The @option{-gnatV} switch may be followed by
6065 ^a string of letters^a list of options^
6066 to turn on a series of validity checking options.
6067 For example,
6068 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6069 specifies that in addition to the default validity checking, copies and
6070 function return expressions are to be validity checked.
6071 In order to make it easier
6072 to specify the desired combination of effects,
6073 @ifclear vms
6074 the upper case letters @code{CDFIMORST} may
6075 be used to turn off the corresponding lower case option.
6076 @end ifclear
6077 @ifset vms
6078 the prefix @code{NO} on an option turns off the corresponding validity
6079 checking:
6080 @itemize @bullet
6081 @item @code{NOCOPIES}
6082 @item @code{NODEFAULT}
6083 @item @code{NOFLOATS}
6084 @item @code{NOIN_PARAMS}
6085 @item @code{NOMOD_PARAMS}
6086 @item @code{NOOPERANDS}
6087 @item @code{NORETURNS}
6088 @item @code{NOSUBSCRIPTS}
6089 @item @code{NOTESTS}
6090 @end itemize
6091 @end ifset
6092 Thus
6093 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6094 turns on all validity checking options except for
6095 checking of @code{@b{in out}} procedure arguments.
6096
6097 The specification of additional validity checking generates extra code (and
6098 in the case of @option{-gnatVa} the code expansion can be substantial).
6099 However, these additional checks can be very useful in detecting
6100 uninitialized variables, incorrect use of unchecked conversion, and other
6101 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6102 is useful in conjunction with the extra validity checking, since this
6103 ensures that wherever possible uninitialized variables have invalid values.
6104
6105 See also the pragma @code{Validity_Checks} which allows modification of
6106 the validity checking mode at the program source level, and also allows for
6107 temporary disabling of validity checks.
6108
6109 @node Style Checking
6110 @subsection Style Checking
6111 @findex Style checking
6112
6113 @noindent
6114 The @option{-gnaty^x^(option,option,@dots{})^} switch
6115 @cindex @option{-gnaty} (@command{gcc})
6116 causes the compiler to
6117 enforce specified style rules. A limited set of style rules has been used
6118 in writing the GNAT sources themselves. This switch allows user programs
6119 to activate all or some of these checks. If the source program fails a
6120 specified style check, an appropriate warning message is given, preceded by
6121 the character sequence ``(style)''.
6122 @ifset vms
6123 @code{(option,option,@dots{})} is a sequence of keywords
6124 @end ifset
6125 @ifclear vms
6126 The string @var{x} is a sequence of letters or digits
6127 @end ifclear
6128 indicating the particular style
6129 checks to be performed. The following checks are defined:
6130
6131 @table @option
6132 @c !sort!
6133 @item 0-9
6134 @emph{Specify indentation level.}
6135 If a digit from 1-9 appears
6136 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6137 then proper indentation is checked, with the digit indicating the
6138 indentation level required. A value of zero turns off this style check.
6139 The general style of required indentation is as specified by
6140 the examples in the Ada Reference Manual. Full line comments must be
6141 aligned with the @code{--} starting on a column that is a multiple of
6142 the alignment level, or they may be aligned the same way as the following
6143 non-blank line (this is useful when full line comments appear in the middle
6144 of a statement.
6145
6146 @item ^a^ATTRIBUTE^
6147 @emph{Check attribute casing.}
6148 Attribute names, including the case of keywords such as @code{digits}
6149 used as attributes names, must be written in mixed case, that is, the
6150 initial letter and any letter following an underscore must be uppercase.
6151 All other letters must be lowercase.
6152
6153 @item ^A^ARRAY_INDEXES^
6154 @emph{Use of array index numbers in array attributes.}
6155 When using the array attributes First, Last, Range,
6156 or Length, the index number must be omitted for one-dimensional arrays
6157 and is required for multi-dimensional arrays.
6158
6159 @item ^b^BLANKS^
6160 @emph{Blanks not allowed at statement end.}
6161 Trailing blanks are not allowed at the end of statements. The purpose of this
6162 rule, together with h (no horizontal tabs), is to enforce a canonical format
6163 for the use of blanks to separate source tokens.
6164
6165 @item ^B^BOOLEAN_OPERATORS^
6166 @emph{Check Boolean operators.}
6167 The use of AND/OR operators is not permitted except in the cases of modular
6168 operands, array operands, and simple stand-alone boolean variables or
6169 boolean constants. In all other cases AND THEN/OR ELSE are required.
6170
6171 @item ^c^COMMENTS^
6172 @emph{Check comments.}
6173 Comments must meet the following set of rules:
6174
6175 @itemize @bullet
6176
6177 @item
6178 The ``@code{--}'' that starts the column must either start in column one,
6179 or else at least one blank must precede this sequence.
6180
6181 @item
6182 Comments that follow other tokens on a line must have at least one blank
6183 following the ``@code{--}'' at the start of the comment.
6184
6185 @item
6186 Full line comments must have two blanks following the ``@code{--}'' that
6187 starts the comment, with the following exceptions.
6188
6189 @item
6190 A line consisting only of the ``@code{--}'' characters, possibly preceded
6191 by blanks is permitted.
6192
6193 @item
6194 A comment starting with ``@code{--x}'' where @code{x} is a special character
6195 is permitted.
6196 This allows proper processing of the output generated by specialized tools
6197 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6198 annotation
6199 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6200 special character is defined as being in one of the ASCII ranges
6201 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6202 Note that this usage is not permitted
6203 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6204
6205 @item
6206 A line consisting entirely of minus signs, possibly preceded by blanks, is
6207 permitted. This allows the construction of box comments where lines of minus
6208 signs are used to form the top and bottom of the box.
6209
6210 @item
6211 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6212 least one blank follows the initial ``@code{--}''. Together with the preceding
6213 rule, this allows the construction of box comments, as shown in the following
6214 example:
6215 @smallexample
6216 ---------------------------
6217 -- This is a box comment --
6218 -- with two text lines.  --
6219 ---------------------------
6220 @end smallexample
6221 @end itemize
6222
6223 @item ^d^DOS_LINE_ENDINGS^
6224 @emph{Check no DOS line terminators present.}
6225 All lines must be terminated by a single ASCII.LF
6226 character (in particular the DOS line terminator sequence CR/LF is not
6227 allowed).
6228
6229 @item ^e^END^
6230 @emph{Check end/exit labels.}
6231 Optional labels on @code{end} statements ending subprograms and on
6232 @code{exit} statements exiting named loops, are required to be present.
6233
6234 @item ^f^VTABS^
6235 @emph{No form feeds or vertical tabs.}
6236 Neither form feeds nor vertical tab characters are permitted
6237 in the source text.
6238
6239 @item ^g^GNAT^
6240 @emph{GNAT style mode}
6241 The set of style check switches is set to match that used by the GNAT sources.
6242 This may be useful when developing code that is eventually intended to be
6243 incorporated into GNAT. For further details, see GNAT sources.
6244
6245 @item ^h^HTABS^
6246 @emph{No horizontal tabs.}
6247 Horizontal tab characters are not permitted in the source text.
6248 Together with the b (no blanks at end of line) check, this
6249 enforces a canonical form for the use of blanks to separate
6250 source tokens.
6251
6252 @item ^i^IF_THEN^
6253 @emph{Check if-then layout.}
6254 The keyword @code{then} must appear either on the same
6255 line as corresponding @code{if}, or on a line on its own, lined
6256 up under the @code{if} with at least one non-blank line in between
6257 containing all or part of the condition to be tested.
6258
6259 @item ^I^IN_MODE^
6260 @emph{check mode IN keywords}
6261 Mode @code{in} (the default mode) is not
6262 allowed to be given explicitly. @code{in out} is fine,
6263 but not @code{in} on its own.
6264
6265 @item ^k^KEYWORD^
6266 @emph{Check keyword casing.}
6267 All keywords must be in lower case (with the exception of keywords
6268 such as @code{digits} used as attribute names to which this check
6269 does not apply).
6270
6271 @item ^l^LAYOUT^
6272 @emph{Check layout.}
6273 Layout of statement and declaration constructs must follow the
6274 recommendations in the Ada Reference Manual, as indicated by the
6275 form of the syntax rules. For example an @code{else} keyword must
6276 be lined up with the corresponding @code{if} keyword.
6277
6278 There are two respects in which the style rule enforced by this check
6279 option are more liberal than those in the Ada Reference Manual. First
6280 in the case of record declarations, it is permissible to put the
6281 @code{record} keyword on the same line as the @code{type} keyword, and
6282 then the @code{end} in @code{end record} must line up under @code{type}.
6283 This is also permitted when the type declaration is split on two lines.
6284 For example, any of the following three layouts is acceptable:
6285
6286 @smallexample @c ada
6287 @cartouche
6288 type q is record
6289    a : integer;
6290    b : integer;
6291 end record;
6292
6293 type q is
6294    record
6295       a : integer;
6296       b : integer;
6297    end record;
6298
6299 type q is
6300    record
6301       a : integer;
6302       b : integer;
6303 end record;
6304
6305 @end cartouche
6306 @end smallexample
6307
6308 @noindent
6309 Second, in the case of a block statement, a permitted alternative
6310 is to put the block label on the same line as the @code{declare} or
6311 @code{begin} keyword, and then line the @code{end} keyword up under
6312 the block label. For example both the following are permitted:
6313
6314 @smallexample @c ada
6315 @cartouche
6316 Block : declare
6317    A : Integer := 3;
6318 begin
6319    Proc (A, A);
6320 end Block;
6321
6322 Block :
6323    declare
6324       A : Integer := 3;
6325    begin
6326       Proc (A, A);
6327    end Block;
6328 @end cartouche
6329 @end smallexample
6330
6331 @noindent
6332 The same alternative format is allowed for loops. For example, both of
6333 the following are permitted:
6334
6335 @smallexample @c ada
6336 @cartouche
6337 Clear : while J < 10 loop
6338    A (J) := 0;
6339 end loop Clear;
6340
6341 Clear :
6342    while J < 10 loop
6343       A (J) := 0;
6344    end loop Clear;
6345 @end cartouche
6346 @end smallexample
6347
6348 @item ^Lnnn^MAX_NESTING=nnn^
6349 @emph{Set maximum nesting level}
6350 The maximum level of nesting of constructs (including subprograms, loops,
6351 blocks, packages, and conditionals) may not exceed the given value
6352 @option{nnn}. A value of zero disconnects this style check.
6353
6354 @item ^m^LINE_LENGTH^
6355 @emph{Check maximum line length.}
6356 The length of source lines must not exceed 79 characters, including
6357 any trailing blanks. The value of 79 allows convenient display on an
6358 80 character wide device or window, allowing for possible special
6359 treatment of 80 character lines. Note that this count is of
6360 characters in the source text. This means that a tab character counts
6361 as one character in this count but a wide character sequence counts as
6362 a single character (however many bytes are needed in the encoding).
6363
6364 @item ^Mnnn^MAX_LENGTH=nnn^
6365 @emph{Set maximum line length.}
6366 The length of lines must not exceed the
6367 given value @option{nnn}. The maximum value that can be specified is 32767.
6368
6369 @item ^n^STANDARD_CASING^
6370 @emph{Check casing of entities in Standard.}
6371 Any identifier from Standard must be cased
6372 to match the presentation in the Ada Reference Manual (for example,
6373 @code{Integer} and @code{ASCII.NUL}).
6374
6375 @item ^N^NONE^
6376 @emph{Turn off all style checks}
6377 All style check options are turned off.
6378
6379 @item ^o^ORDERED_SUBPROGRAMS^
6380 @emph{Check order of subprogram bodies.}
6381 All subprogram bodies in a given scope
6382 (e.g.@: a package body) must be in alphabetical order. The ordering
6383 rule uses normal Ada rules for comparing strings, ignoring casing
6384 of letters, except that if there is a trailing numeric suffix, then
6385 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6386 before Junk10).
6387
6388 @item ^O^OVERRIDING_INDICATORS^
6389 @emph{Check that overriding subprograms are explicitly marked as such.}
6390 The declaration of a primitive operation of a type extension that overrides
6391 an inherited operation must carry an overriding indicator.
6392
6393 @item ^p^PRAGMA^
6394 @emph{Check pragma casing.}
6395 Pragma names must be written in mixed case, that is, the
6396 initial letter and any letter following an underscore must be uppercase.
6397 All other letters must be lowercase.
6398
6399 @item ^r^REFERENCES^
6400 @emph{Check references.}
6401 All identifier references must be cased in the same way as the
6402 corresponding declaration. No specific casing style is imposed on
6403 identifiers. The only requirement is for consistency of references
6404 with declarations.
6405
6406 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6407 @emph{Check no statements after THEN/ELSE.}
6408 No statements are allowed
6409 on the same line as a THEN or ELSE keyword following the
6410 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6411 and a special exception allows a pragma to appear after ELSE.
6412
6413 @item ^s^SPECS^
6414 @emph{Check separate specs.}
6415 Separate declarations (``specs'') are required for subprograms (a
6416 body is not allowed to serve as its own declaration). The only
6417 exception is that parameterless library level procedures are
6418 not required to have a separate declaration. This exception covers
6419 the most frequent form of main program procedures.
6420
6421 @item ^t^TOKEN^
6422 @emph{Check token spacing.}
6423 The following token spacing rules are enforced:
6424
6425 @itemize @bullet
6426
6427 @item
6428 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6429
6430 @item
6431 The token @code{=>} must be surrounded by spaces.
6432
6433 @item
6434 The token @code{<>} must be preceded by a space or a left parenthesis.
6435
6436 @item
6437 Binary operators other than @code{**} must be surrounded by spaces.
6438 There is no restriction on the layout of the @code{**} binary operator.
6439
6440 @item
6441 Colon must be surrounded by spaces.
6442
6443 @item
6444 Colon-equal (assignment, initialization) must be surrounded by spaces.
6445
6446 @item
6447 Comma must be the first non-blank character on the line, or be
6448 immediately preceded by a non-blank character, and must be followed
6449 by a space.
6450
6451 @item
6452 If the token preceding a left parenthesis ends with a letter or digit, then
6453 a space must separate the two tokens.
6454
6455 @item
6456 if the token following a right parenthesis starts with a letter or digit, then
6457 a space must separate the two tokens.
6458
6459 @item
6460 A right parenthesis must either be the first non-blank character on
6461 a line, or it must be preceded by a non-blank character.
6462
6463 @item
6464 A semicolon must not be preceded by a space, and must not be followed by
6465 a non-blank character.
6466
6467 @item
6468 A unary plus or minus may not be followed by a space.
6469
6470 @item
6471 A vertical bar must be surrounded by spaces.
6472 @end itemize
6473
6474 @item ^u^UNNECESSARY_BLANK_LINES^
6475 @emph{Check unnecessary blank lines.}
6476 Unnecessary blank lines are not allowed. A blank line is considered
6477 unnecessary if it appears at the end of the file, or if more than
6478 one blank line occurs in sequence.
6479
6480 @item ^x^XTRA_PARENS^
6481 @emph{Check extra parentheses.}
6482 Unnecessary extra level of parentheses (C-style) are not allowed
6483 around conditions in @code{if} statements, @code{while} statements and
6484 @code{exit} statements.
6485
6486 @item ^y^ALL_BUILTIN^
6487 @emph{Set all standard style check options}
6488 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6489 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6490 @option{-gnatyS}, @option{-gnatyLnnn},
6491 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6492
6493 @ifclear vms
6494 @item -
6495 @emph{Remove style check options}
6496 This causes any subsequent options in the string to act as canceling the
6497 corresponding style check option. To cancel maximum nesting level control,
6498 use @option{L} parameter witout any integer value after that, because any
6499 digit following @option{-} in the parameter string of the @option{-gnaty}
6500 option will be threated as canceling indentation check. The same is true
6501 for @option{M} parameter. @option{y} and @option{N} parameters are not
6502 allowed after @option{-}.
6503
6504 @item +
6505 This causes any subsequent options in the string to enable the corresponding
6506 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6507 if any.
6508 @end ifclear
6509
6510 @ifset vms
6511 @item NOxxx
6512 @emph{Removing style check options}
6513 If the name of a style check is preceded by @option{NO} then the corresponding
6514 style check is turned off. For example @option{NOCOMMENTS} turns off style
6515 checking for comments.
6516 @end ifset
6517 @end table
6518
6519 @noindent
6520 In the above rules, appearing in column one is always permitted, that is,
6521 counts as meeting either a requirement for a required preceding space,
6522 or as meeting a requirement for no preceding space.
6523
6524 Appearing at the end of a line is also always permitted, that is, counts
6525 as meeting either a requirement for a following space, or as meeting
6526 a requirement for no following space.
6527
6528 @noindent
6529 If any of these style rules is violated, a message is generated giving
6530 details on the violation. The initial characters of such messages are
6531 always ``@code{(style)}''. Note that these messages are treated as warning
6532 messages, so they normally do not prevent the generation of an object
6533 file. The @option{-gnatwe} switch can be used to treat warning messages,
6534 including style messages, as fatal errors.
6535
6536 The switch
6537 @ifclear vms
6538 @option{-gnaty} on its own (that is not
6539 followed by any letters or digits), then the effect is equivalent
6540 to the use of @option{-gnatyy}, as described above, that is all
6541 built-in standard style check options are enabled.
6542
6543 @end ifclear
6544 @ifset vms
6545 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6546 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6547 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6548 @end ifset
6549
6550 The switch
6551 @ifclear vms
6552 @option{-gnatyN}
6553 @end ifclear
6554 @ifset vms
6555 /STYLE_CHECKS=NONE
6556 @end ifset
6557 clears any previously set style checks.
6558
6559 @node Run-Time Checks
6560 @subsection Run-Time Checks
6561 @cindex Division by zero
6562 @cindex Access before elaboration
6563 @cindex Checks, division by zero
6564 @cindex Checks, access before elaboration
6565 @cindex Checks, stack overflow checking
6566
6567 @noindent
6568 By default, the following checks are suppressed: integer overflow
6569 checks, stack overflow checks, and checks for access before
6570 elaboration on subprogram calls. All other checks, including range
6571 checks and array bounds checks, are turned on by default. The
6572 following @command{gcc} switches refine this default behavior.
6573
6574 @table @option
6575 @c !sort!
6576 @item -gnatp
6577 @cindex @option{-gnatp} (@command{gcc})
6578 @cindex Suppressing checks
6579 @cindex Checks, suppressing
6580 @findex Suppress
6581 This switch causes the unit to be compiled
6582 as though @code{pragma Suppress (All_checks)}
6583 had been present in the source. Validity checks are also eliminated (in
6584 other words @option{-gnatp} also implies @option{-gnatVn}.
6585 Use this switch to improve the performance
6586 of the code at the expense of safety in the presence of invalid data or
6587 program bugs.
6588
6589 Note that when checks are suppressed, the compiler is allowed, but not
6590 required, to omit the checking code. If the run-time cost of the
6591 checking code is zero or near-zero, the compiler will generate it even
6592 if checks are suppressed. In particular, if the compiler can prove
6593 that a certain check will necessarily fail, it will generate code to
6594 do an unconditional ``raise'', even if checks are suppressed. The
6595 compiler warns in this case. Another case in which checks may not be
6596 eliminated is when they are embedded in certain run time routines such
6597 as math library routines.
6598
6599 Of course, run-time checks are omitted whenever the compiler can prove
6600 that they will not fail, whether or not checks are suppressed.
6601
6602 Note that if you suppress a check that would have failed, program
6603 execution is erroneous, which means the behavior is totally
6604 unpredictable. The program might crash, or print wrong answers, or
6605 do anything else. It might even do exactly what you wanted it to do
6606 (and then it might start failing mysteriously next week or next
6607 year). The compiler will generate code based on the assumption that
6608 the condition being checked is true, which can result in disaster if
6609 that assumption is wrong.
6610
6611 @item -gnato
6612 @cindex @option{-gnato} (@command{gcc})
6613 @cindex Overflow checks
6614 @cindex Check, overflow
6615 Enables overflow checking for integer operations.
6616 This causes GNAT to generate slower and larger executable
6617 programs by adding code to check for overflow (resulting in raising
6618 @code{Constraint_Error} as required by standard Ada
6619 semantics). These overflow checks correspond to situations in which
6620 the true value of the result of an operation may be outside the base
6621 range of the result type. The following example shows the distinction:
6622
6623 @smallexample @c ada
6624 X1 : Integer := "Integer'Last";
6625 X2 : Integer range 1 .. 5 := "5";
6626 X3 : Integer := "Integer'Last";
6627 X4 : Integer range 1 .. 5 := "5";
6628 F  : Float := "2.0E+20";
6629 @dots{}
6630 X1 := X1 + 1;
6631 X2 := X2 + 1;
6632 X3 := Integer (F);
6633 X4 := Integer (F);
6634 @end smallexample
6635
6636 @noindent
6637 Note that if explicit values are assigned at compile time, the
6638 compiler may be able to detect overflow at compile time, in which case
6639 no actual run-time checking code is required, and Constraint_Error
6640 will be raised unconditionally, with or without
6641 @option{-gnato}. That's why the assigned values in the above fragment
6642 are in quotes, the meaning is "assign a value not known to the
6643 compiler that happens to be equal to ...". The remaining discussion
6644 assumes that the compiler cannot detect the values at compile time.
6645
6646 Here the first addition results in a value that is outside the base range
6647 of Integer, and hence requires an overflow check for detection of the
6648 constraint error. Thus the first assignment to @code{X1} raises a
6649 @code{Constraint_Error} exception only if @option{-gnato} is set.
6650
6651 The second increment operation results in a violation of the explicit
6652 range constraint; such range checks are performed by default, and are
6653 unaffected by @option{-gnato}.
6654
6655 The two conversions of @code{F} both result in values that are outside
6656 the base range of type @code{Integer} and thus will raise
6657 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6658 The fact that the result of the second conversion is assigned to
6659 variable @code{X4} with a restricted range is irrelevant, since the problem
6660 is in the conversion, not the assignment.
6661
6662 Basically the rule is that in the default mode (@option{-gnato} not
6663 used), the generated code assures that all integer variables stay
6664 within their declared ranges, or within the base range if there is
6665 no declared range. This prevents any serious problems like indexes
6666 out of range for array operations.
6667
6668 What is not checked in default mode is an overflow that results in
6669 an in-range, but incorrect value. In the above example, the assignments
6670 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6671 range of the target variable, but the result is wrong in the sense that
6672 it is too large to be represented correctly. Typically the assignment
6673 to @code{X1} will result in wrap around to the largest negative number.
6674 The conversions of @code{F} will result in some @code{Integer} value
6675 and if that integer value is out of the @code{X4} range then the
6676 subsequent assignment would generate an exception.
6677
6678 @findex Machine_Overflows
6679 Note that the @option{-gnato} switch does not affect the code generated
6680 for any floating-point operations; it applies only to integer
6681 semantics).
6682 For floating-point, GNAT has the @code{Machine_Overflows}
6683 attribute set to @code{False} and the normal mode of operation is to
6684 generate IEEE NaN and infinite values on overflow or invalid operations
6685 (such as dividing 0.0 by 0.0).
6686
6687 The reason that we distinguish overflow checking from other kinds of
6688 range constraint checking is that a failure of an overflow check, unlike
6689 for example the failure of a range check, can result in an incorrect
6690 value, but cannot cause random memory destruction (like an out of range
6691 subscript), or a wild jump (from an out of range case value). Overflow
6692 checking is also quite expensive in time and space, since in general it
6693 requires the use of double length arithmetic.
6694
6695 Note again that @option{-gnato} is off by default, so overflow checking is
6696 not performed in default mode. This means that out of the box, with the
6697 default settings, GNAT does not do all the checks expected from the
6698 language description in the Ada Reference Manual. If you want all constraint
6699 checks to be performed, as described in this Manual, then you must
6700 explicitly use the -gnato switch either on the @command{gnatmake} or
6701 @command{gcc} command.
6702
6703 @item -gnatE
6704 @cindex @option{-gnatE} (@command{gcc})
6705 @cindex Elaboration checks
6706 @cindex Check, elaboration
6707 Enables dynamic checks for access-before-elaboration
6708 on subprogram calls and generic instantiations.
6709 Note that @option{-gnatE} is not necessary for safety, because in the
6710 default mode, GNAT ensures statically that the checks would not fail.
6711 For full details of the effect and use of this switch,
6712 @xref{Compiling Using gcc}.
6713
6714 @item -fstack-check
6715 @cindex @option{-fstack-check} (@command{gcc})
6716 @cindex Stack Overflow Checking
6717 @cindex Checks, stack overflow checking
6718 Activates stack overflow checking. For full details of the effect and use of
6719 this switch see @ref{Stack Overflow Checking}.
6720 @end table
6721
6722 @findex Unsuppress
6723 @noindent
6724 The setting of these switches only controls the default setting of the
6725 checks. You may modify them using either @code{Suppress} (to remove
6726 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6727 the program source.
6728
6729 @node Using gcc for Syntax Checking
6730 @subsection Using @command{gcc} for Syntax Checking
6731 @table @option
6732 @item -gnats
6733 @cindex @option{-gnats} (@command{gcc})
6734 @ifclear vms
6735
6736 @noindent
6737 The @code{s} stands for ``syntax''.
6738 @end ifclear
6739
6740 Run GNAT in syntax checking only mode. For
6741 example, the command
6742
6743 @smallexample
6744 $ gcc -c -gnats x.adb
6745 @end smallexample
6746
6747 @noindent
6748 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6749 series of files in a single command
6750 @ifclear vms
6751 , and can use wild cards to specify such a group of files.
6752 Note that you must specify the @option{-c} (compile
6753 only) flag in addition to the @option{-gnats} flag.
6754 @end ifclear
6755 .
6756 You may use other switches in conjunction with @option{-gnats}. In
6757 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6758 format of any generated error messages.
6759
6760 When the source file is empty or contains only empty lines and/or comments,
6761 the output is a warning:
6762
6763 @smallexample
6764 $ gcc -c -gnats -x ada toto.txt
6765 toto.txt:1:01: warning: empty file, contains no compilation units
6766 $
6767 @end smallexample
6768
6769 Otherwise, the output is simply the error messages, if any. No object file or
6770 ALI file is generated by a syntax-only compilation. Also, no units other
6771 than the one specified are accessed. For example, if a unit @code{X}
6772 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6773 check only mode does not access the source file containing unit
6774 @code{Y}.
6775
6776 @cindex Multiple units, syntax checking
6777 Normally, GNAT allows only a single unit in a source file. However, this
6778 restriction does not apply in syntax-check-only mode, and it is possible
6779 to check a file containing multiple compilation units concatenated
6780 together. This is primarily used by the @code{gnatchop} utility
6781 (@pxref{Renaming Files Using gnatchop}).
6782 @end table
6783
6784 @node Using gcc for Semantic Checking
6785 @subsection Using @command{gcc} for Semantic Checking
6786 @table @option
6787 @item -gnatc
6788 @cindex @option{-gnatc} (@command{gcc})
6789
6790 @ifclear vms
6791 @noindent
6792 The @code{c} stands for ``check''.
6793 @end ifclear
6794 Causes the compiler to operate in semantic check mode,
6795 with full checking for all illegalities specified in the
6796 Ada Reference Manual, but without generation of any object code
6797 (no object file is generated).
6798
6799 Because dependent files must be accessed, you must follow the GNAT
6800 semantic restrictions on file structuring to operate in this mode:
6801
6802 @itemize @bullet
6803 @item
6804 The needed source files must be accessible
6805 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6806
6807 @item
6808 Each file must contain only one compilation unit.
6809
6810 @item
6811 The file name and unit name must match (@pxref{File Naming Rules}).
6812 @end itemize
6813
6814 The output consists of error messages as appropriate. No object file is
6815 generated. An @file{ALI} file is generated for use in the context of
6816 cross-reference tools, but this file is marked as not being suitable
6817 for binding (since no object file is generated).
6818 The checking corresponds exactly to the notion of
6819 legality in the Ada Reference Manual.
6820
6821 Any unit can be compiled in semantics-checking-only mode, including
6822 units that would not normally be compiled (subunits,
6823 and specifications where a separate body is present).
6824 @end table
6825
6826 @node Compiling Different Versions of Ada
6827 @subsection Compiling Different Versions of Ada
6828
6829 @noindent
6830 The switches described in this section allow you to explicitly specify
6831 the version of the Ada language that your programs are written in.
6832 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6833 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6834 indicate Ada 83 compatibility mode.
6835
6836 @table @option
6837 @cindex Compatibility with Ada 83
6838
6839 @item -gnat83 (Ada 83 Compatibility Mode)
6840 @cindex @option{-gnat83} (@command{gcc})
6841 @cindex ACVC, Ada 83 tests
6842 @cindex Ada 83 mode
6843
6844 @noindent
6845 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6846 specifies that the program is to be compiled in Ada 83 mode. With
6847 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6848 semantics where this can be done easily.
6849 It is not possible to guarantee this switch does a perfect
6850 job; some subtle tests, such as are
6851 found in earlier ACVC tests (and that have been removed from the ACATS suite
6852 for Ada 95), might not compile correctly.
6853 Nevertheless, this switch may be useful in some circumstances, for example
6854 where, due to contractual reasons, existing code needs to be maintained
6855 using only Ada 83 features.
6856
6857 With few exceptions (most notably the need to use @code{<>} on
6858 @cindex Generic formal parameters
6859 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6860 reserved words, and the use of packages
6861 with optional bodies), it is not necessary to specify the
6862 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6863 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6864 a correct Ada 83 program is usually also a correct program
6865 in these later versions of the language standard.
6866 For further information, please refer to @ref{Compatibility and Porting Guide}.
6867
6868 @item -gnat95 (Ada 95 mode)
6869 @cindex @option{-gnat95} (@command{gcc})
6870 @cindex Ada 95 mode
6871
6872 @noindent
6873 This switch directs the compiler to implement the Ada 95 version of the
6874 language.
6875 Since Ada 95 is almost completely upwards
6876 compatible with Ada 83, Ada 83 programs may generally be compiled using
6877 this switch (see the description of the @option{-gnat83} switch for further
6878 information about Ada 83 mode).
6879 If an Ada 2005 program is compiled in Ada 95 mode,
6880 uses of the new Ada 2005 features will cause error
6881 messages or warnings.
6882
6883 This switch also can be used to cancel the effect of a previous
6884 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6885
6886 @item -gnat05 (Ada 2005 mode)
6887 @cindex @option{-gnat05} (@command{gcc})
6888 @cindex Ada 2005 mode
6889
6890 @noindent
6891 This switch directs the compiler to implement the Ada 2005 version of the
6892 language.
6893 Since Ada 2005 is almost completely upwards
6894 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6895 may generally be compiled using this switch (see the description of the
6896 @option{-gnat83} and @option{-gnat95} switches for further
6897 information).
6898
6899 For information about the approved ``Ada Issues'' that have been incorporated
6900 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6901 Included with GNAT releases is a file @file{features-ada0y} that describes
6902 the set of implemented Ada 2005 features.
6903 @end table
6904
6905
6906 @node Character Set Control
6907 @subsection Character Set Control
6908 @table @option
6909 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6910 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6911
6912 @noindent
6913 Normally GNAT recognizes the Latin-1 character set in source program
6914 identifiers, as described in the Ada Reference Manual.
6915 This switch causes
6916 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6917 single character ^^or word^ indicating the character set, as follows:
6918
6919 @table @code
6920 @item 1
6921 ISO 8859-1 (Latin-1) identifiers
6922
6923 @item 2
6924 ISO 8859-2 (Latin-2) letters allowed in identifiers
6925
6926 @item 3
6927 ISO 8859-3 (Latin-3) letters allowed in identifiers
6928
6929 @item 4
6930 ISO 8859-4 (Latin-4) letters allowed in identifiers
6931
6932 @item 5
6933 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6934
6935 @item 9
6936 ISO 8859-15 (Latin-9) letters allowed in identifiers
6937
6938 @item ^p^PC^
6939 IBM PC letters (code page 437) allowed in identifiers
6940
6941 @item ^8^PC850^
6942 IBM PC letters (code page 850) allowed in identifiers
6943
6944 @item ^f^FULL_UPPER^
6945 Full upper-half codes allowed in identifiers
6946
6947 @item ^n^NO_UPPER^
6948 No upper-half codes allowed in identifiers
6949
6950 @item ^w^WIDE^
6951 Wide-character codes (that is, codes greater than 255)
6952 allowed in identifiers
6953 @end table
6954
6955 @xref{Foreign Language Representation}, for full details on the
6956 implementation of these character sets.
6957
6958 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6959 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6960 Specify the method of encoding for wide characters.
6961 @var{e} is one of the following:
6962
6963 @table @code
6964
6965 @item ^h^HEX^
6966 Hex encoding (brackets coding also recognized)
6967
6968 @item ^u^UPPER^
6969 Upper half encoding (brackets encoding also recognized)
6970
6971 @item ^s^SHIFT_JIS^
6972 Shift/JIS encoding (brackets encoding also recognized)
6973
6974 @item ^e^EUC^
6975 EUC encoding (brackets encoding also recognized)
6976
6977 @item ^8^UTF8^
6978 UTF-8 encoding (brackets encoding also recognized)
6979
6980 @item ^b^BRACKETS^
6981 Brackets encoding only (default value)
6982 @end table
6983 For full details on these encoding
6984 methods see @ref{Wide Character Encodings}.
6985 Note that brackets coding is always accepted, even if one of the other
6986 options is specified, so for example @option{-gnatW8} specifies that both
6987 brackets and UTF-8 encodings will be recognized. The units that are
6988 with'ed directly or indirectly will be scanned using the specified
6989 representation scheme, and so if one of the non-brackets scheme is
6990 used, it must be used consistently throughout the program. However,
6991 since brackets encoding is always recognized, it may be conveniently
6992 used in standard libraries, allowing these libraries to be used with
6993 any of the available coding schemes.
6994 scheme.
6995
6996 If no @option{-gnatW?} parameter is present, then the default
6997 representation is normally Brackets encoding only. However, if the
6998 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6999 byte order mark or BOM for UTF-8), then these three characters are
7000 skipped and the default representation for the file is set to UTF-8.
7001
7002 Note that the wide character representation that is specified (explicitly
7003 or by default) for the main program also acts as the default encoding used
7004 for Wide_Text_IO files if not specifically overridden by a WCEM form
7005 parameter.
7006
7007 @end table
7008 @node File Naming Control
7009 @subsection File Naming Control
7010
7011 @table @option
7012 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7013 @cindex @option{-gnatk} (@command{gcc})
7014 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7015 1-999, indicates the maximum allowable length of a file name (not
7016 including the @file{.ads} or @file{.adb} extension). The default is not
7017 to enable file name krunching.
7018
7019 For the source file naming rules, @xref{File Naming Rules}.
7020 @end table
7021
7022 @node Subprogram Inlining Control
7023 @subsection Subprogram Inlining Control
7024
7025 @table @option
7026 @c !sort!
7027 @item -gnatn
7028 @cindex @option{-gnatn} (@command{gcc})
7029 @ifclear vms
7030 The @code{n} here is intended to suggest the first syllable of the
7031 word ``inline''.
7032 @end ifclear
7033 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7034 inlining to actually occur, optimization must be enabled. To enable
7035 inlining of subprograms specified by pragma @code{Inline},
7036 you must also specify this switch.
7037 In the absence of this switch, GNAT does not attempt
7038 inlining and does not need to access the bodies of
7039 subprograms for which @code{pragma Inline} is specified if they are not
7040 in the current unit.
7041
7042 If you specify this switch the compiler will access these bodies,
7043 creating an extra source dependency for the resulting object file, and
7044 where possible, the call will be inlined.
7045 For further details on when inlining is possible
7046 see @ref{Inlining of Subprograms}.
7047
7048 @item -gnatN
7049 @cindex @option{-gnatN} (@command{gcc})
7050 This switch activates front-end inlining which also
7051 generates additional dependencies.
7052
7053 When using a gcc-based back end (in practice this means using any version
7054 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7055 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7056 Historically front end inlining was more extensive than the gcc back end
7057 inlining, but that is no longer the case.
7058 @end table
7059
7060 @node Auxiliary Output Control
7061 @subsection Auxiliary Output Control
7062
7063 @table @option
7064 @item -gnatt
7065 @cindex @option{-gnatt} (@command{gcc})
7066 @cindex Writing internal trees
7067 @cindex Internal trees, writing to file
7068 Causes GNAT to write the internal tree for a unit to a file (with the
7069 extension @file{.adt}.
7070 This not normally required, but is used by separate analysis tools.
7071 Typically
7072 these tools do the necessary compilations automatically, so you should
7073 not have to specify this switch in normal operation.
7074 Note that the combination of switches @option{-gnatct}
7075 generates a tree in the form required by ASIS applications.
7076
7077 @item -gnatu
7078 @cindex @option{-gnatu} (@command{gcc})
7079 Print a list of units required by this compilation on @file{stdout}.
7080 The listing includes all units on which the unit being compiled depends
7081 either directly or indirectly.
7082
7083 @ifclear vms
7084 @item -pass-exit-codes
7085 @cindex @option{-pass-exit-codes} (@command{gcc})
7086 If this switch is not used, the exit code returned by @command{gcc} when
7087 compiling multiple files indicates whether all source files have
7088 been successfully used to generate object files or not.
7089
7090 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7091 exit status and allows an integrated development environment to better
7092 react to a compilation failure. Those exit status are:
7093
7094 @table @asis
7095 @item 5
7096 There was an error in at least one source file.
7097 @item 3
7098 At least one source file did not generate an object file.
7099 @item 2
7100 The compiler died unexpectedly (internal error for example).
7101 @item 0
7102 An object file has been generated for every source file.
7103 @end table
7104 @end ifclear
7105 @end table
7106
7107 @node Debugging Control
7108 @subsection Debugging Control
7109
7110 @table @option
7111 @c !sort!
7112 @cindex Debugging options
7113 @ifclear vms
7114 @item -gnatd@var{x}
7115 @cindex @option{-gnatd} (@command{gcc})
7116 Activate internal debugging switches. @var{x} is a letter or digit, or
7117 string of letters or digits, which specifies the type of debugging
7118 outputs desired. Normally these are used only for internal development
7119 or system debugging purposes. You can find full documentation for these
7120 switches in the body of the @code{Debug} unit in the compiler source
7121 file @file{debug.adb}.
7122 @end ifclear
7123
7124 @item -gnatG[=nn]
7125 @cindex @option{-gnatG} (@command{gcc})
7126 This switch causes the compiler to generate auxiliary output containing
7127 a pseudo-source listing of the generated expanded code. Like most Ada
7128 compilers, GNAT works by first transforming the high level Ada code into
7129 lower level constructs. For example, tasking operations are transformed
7130 into calls to the tasking run-time routines. A unique capability of GNAT
7131 is to list this expanded code in a form very close to normal Ada source.
7132 This is very useful in understanding the implications of various Ada
7133 usage on the efficiency of the generated code. There are many cases in
7134 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7135 generate a lot of run-time code. By using @option{-gnatG} you can identify
7136 these cases, and consider whether it may be desirable to modify the coding
7137 approach to improve efficiency.
7138
7139 The optional parameter @code{nn} if present after -gnatG specifies an
7140 alternative maximum line length that overrides the normal default of 72.
7141 This value is in the range 40-999999, values less than 40 being silently
7142 reset to 40. The equal sign is optional.
7143
7144 The format of the output is very similar to standard Ada source, and is
7145 easily understood by an Ada programmer. The following special syntactic
7146 additions correspond to low level features used in the generated code that
7147 do not have any exact analogies in pure Ada source form. The following
7148 is a partial list of these special constructions. See the spec
7149 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7150
7151 If the switch @option{-gnatL} is used in conjunction with
7152 @cindex @option{-gnatL} (@command{gcc})
7153 @option{-gnatG}, then the original source lines are interspersed
7154 in the expanded source (as comment lines with the original line number).
7155
7156 @table @code
7157 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7158 Shows the storage pool being used for an allocator.
7159
7160 @item at end @var{procedure-name};
7161 Shows the finalization (cleanup) procedure for a scope.
7162
7163 @item (if @var{expr} then @var{expr} else @var{expr})
7164 Conditional expression equivalent to the @code{x?y:z} construction in C.
7165
7166 @item @var{target}^^^(@var{source})
7167 A conversion with floating-point truncation instead of rounding.
7168
7169 @item @var{target}?(@var{source})
7170 A conversion that bypasses normal Ada semantic checking. In particular
7171 enumeration types and fixed-point types are treated simply as integers.
7172
7173 @item @var{target}?^^^(@var{source})
7174 Combines the above two cases.
7175
7176 @item @var{x} #/ @var{y}
7177 @itemx @var{x} #mod @var{y}
7178 @itemx @var{x} #* @var{y}
7179 @itemx @var{x} #rem @var{y}
7180 A division or multiplication of fixed-point values which are treated as
7181 integers without any kind of scaling.
7182
7183 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7184 Shows the storage pool associated with a @code{free} statement.
7185
7186 @item [subtype or type declaration]
7187 Used to list an equivalent declaration for an internally generated
7188 type that is referenced elsewhere in the listing.
7189
7190 @item freeze @var{type-name} @ovar{actions}
7191 Shows the point at which @var{type-name} is frozen, with possible
7192 associated actions to be performed at the freeze point.
7193
7194 @item reference @var{itype}
7195 Reference (and hence definition) to internal type @var{itype}.
7196
7197 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7198 Intrinsic function call.
7199
7200 @item @var{label-name} : label
7201 Declaration of label @var{labelname}.
7202
7203 @item #$ @var{subprogram-name}
7204 An implicit call to a run-time support routine
7205 (to meet the requirement of H.3.1(9) in a
7206 convenient manner).
7207
7208 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7209 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7210 @var{expr}, but handled more efficiently).
7211
7212 @item [constraint_error]
7213 Raise the @code{Constraint_Error} exception.
7214
7215 @item @var{expression}'reference
7216 A pointer to the result of evaluating @var{expression}.
7217
7218 @item @var{target-type}!(@var{source-expression})
7219 An unchecked conversion of @var{source-expression} to @var{target-type}.
7220
7221 @item [@var{numerator}/@var{denominator}]
7222 Used to represent internal real literals (that) have no exact
7223 representation in base 2-16 (for example, the result of compile time
7224 evaluation of the expression 1.0/27.0).
7225 @end table
7226
7227 @item -gnatD[=nn]
7228 @cindex @option{-gnatD} (@command{gcc})
7229 When used in conjunction with @option{-gnatG}, this switch causes
7230 the expanded source, as described above for
7231 @option{-gnatG} to be written to files with names
7232 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7233 instead of to the standard output file. For
7234 example, if the source file name is @file{hello.adb}, then a file
7235 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7236 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7237 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7238 you to do source level debugging using the generated code which is
7239 sometimes useful for complex code, for example to find out exactly
7240 which part of a complex construction raised an exception. This switch
7241 also suppress generation of cross-reference information (see
7242 @option{-gnatx}) since otherwise the cross-reference information
7243 would refer to the @file{^.dg^.DG^} file, which would cause
7244 confusion since this is not the original source file.
7245
7246 Note that @option{-gnatD} actually implies @option{-gnatG}
7247 automatically, so it is not necessary to give both options.
7248 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7249
7250 If the switch @option{-gnatL} is used in conjunction with
7251 @cindex @option{-gnatL} (@command{gcc})
7252 @option{-gnatDG}, then the original source lines are interspersed
7253 in the expanded source (as comment lines with the original line number).
7254
7255 The optional parameter @code{nn} if present after -gnatD specifies an
7256 alternative maximum line length that overrides the normal default of 72.
7257 This value is in the range 40-999999, values less than 40 being silently
7258 reset to 40. The equal sign is optional.
7259
7260 @item -gnatr
7261 @cindex @option{-gnatr} (@command{gcc})
7262 @cindex pragma Restrictions
7263 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7264 so that violation of restrictions causes warnings rather than illegalities.
7265 This is useful during the development process when new restrictions are added
7266 or investigated. The switch also causes pragma Profile to be treated as
7267 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7268 restriction warnings rather than restrictions.
7269
7270 @ifclear vms
7271 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7272 @cindex @option{-gnatR} (@command{gcc})
7273 This switch controls output from the compiler of a listing showing
7274 representation information for declared types and objects. For
7275 @option{-gnatR0}, no information is output (equivalent to omitting
7276 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7277 so @option{-gnatR} with no parameter has the same effect), size and alignment
7278 information is listed for declared array and record types. For
7279 @option{-gnatR2}, size and alignment information is listed for all
7280 declared types and objects. Finally @option{-gnatR3} includes symbolic
7281 expressions for values that are computed at run time for
7282 variant records. These symbolic expressions have a mostly obvious
7283 format with #n being used to represent the value of the n'th
7284 discriminant. See source files @file{repinfo.ads/adb} in the
7285 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7286 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7287 the output is to a file with the name @file{^file.rep^file_REP^} where
7288 file is the name of the corresponding source file.
7289 @end ifclear
7290 @ifset vms
7291 @item /REPRESENTATION_INFO
7292 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7293 This qualifier controls output from the compiler of a listing showing
7294 representation information for declared types and objects. For
7295 @option{/REPRESENTATION_INFO=NONE}, no information is output
7296 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7297 @option{/REPRESENTATION_INFO} without option is equivalent to
7298 @option{/REPRESENTATION_INFO=ARRAYS}.
7299 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7300 information is listed for declared array and record types. For
7301 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7302 is listed for all expression information for values that are computed
7303 at run time for variant records. These symbolic expressions have a mostly
7304 obvious format with #n being used to represent the value of the n'th
7305 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7306 @code{GNAT} sources for full details on the format of
7307 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7308 If _FILE is added at the end of an option
7309 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7310 then the output is to a file with the name @file{file_REP} where
7311 file is the name of the corresponding source file.
7312 @end ifset
7313 Note that it is possible for record components to have zero size. In
7314 this case, the component clause uses an obvious extension of permitted
7315 Ada syntax, for example @code{at 0 range 0 .. -1}.
7316
7317 Representation information requires that code be generated (since it is the
7318 code generator that lays out complex data structures). If an attempt is made
7319 to output representation information when no code is generated, for example
7320 when a subunit is compiled on its own, then no information can be generated
7321 and the compiler outputs a message to this effect.
7322
7323 @item -gnatS
7324 @cindex @option{-gnatS} (@command{gcc})
7325 The use of the switch @option{-gnatS} for an
7326 Ada compilation will cause the compiler to output a
7327 representation of package Standard in a form very
7328 close to standard Ada. It is not quite possible to
7329 do this entirely in standard Ada (since new
7330 numeric base types cannot be created in standard
7331 Ada), but the output is easily
7332 readable to any Ada programmer, and is useful to
7333 determine the characteristics of target dependent
7334 types in package Standard.
7335
7336 @item -gnatx
7337 @cindex @option{-gnatx} (@command{gcc})
7338 Normally the compiler generates full cross-referencing information in
7339 the @file{ALI} file. This information is used by a number of tools,
7340 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7341 suppresses this information. This saves some space and may slightly
7342 speed up compilation, but means that these tools cannot be used.
7343 @end table
7344
7345 @node Exception Handling Control
7346 @subsection Exception Handling Control
7347
7348 @noindent
7349 GNAT uses two methods for handling exceptions at run-time. The
7350 @code{setjmp/longjmp} method saves the context when entering
7351 a frame with an exception handler. Then when an exception is
7352 raised, the context can be restored immediately, without the
7353 need for tracing stack frames. This method provides very fast
7354 exception propagation, but introduces significant overhead for
7355 the use of exception handlers, even if no exception is raised.
7356
7357 The other approach is called ``zero cost'' exception handling.
7358 With this method, the compiler builds static tables to describe
7359 the exception ranges. No dynamic code is required when entering
7360 a frame containing an exception handler. When an exception is
7361 raised, the tables are used to control a back trace of the
7362 subprogram invocation stack to locate the required exception
7363 handler. This method has considerably poorer performance for
7364 the propagation of exceptions, but there is no overhead for
7365 exception handlers if no exception is raised. Note that in this
7366 mode and in the context of mixed Ada and C/C++ programming,
7367 to propagate an exception through a C/C++ code, the C/C++ code
7368 must be compiled with the @option{-funwind-tables} GCC's
7369 option.
7370
7371 The following switches may be used to control which of the
7372 two exception handling methods is used.
7373
7374 @table @option
7375 @c !sort!
7376
7377 @item --RTS=sjlj
7378 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7379 This switch causes the setjmp/longjmp run-time (when available) to be used
7380 for exception handling. If the default
7381 mechanism for the target is zero cost exceptions, then
7382 this switch can be used to modify this default, and must be
7383 used for all units in the partition.
7384 This option is rarely used. One case in which it may be
7385 advantageous is if you have an application where exception
7386 raising is common and the overall performance of the
7387 application is improved by favoring exception propagation.
7388
7389 @item --RTS=zcx
7390 @cindex @option{--RTS=zcx} (@command{gnatmake})
7391 @cindex Zero Cost Exceptions
7392 This switch causes the zero cost approach to be used
7393 for exception handling. If this is the default mechanism for the
7394 target (see below), then this switch is unneeded. If the default
7395 mechanism for the target is setjmp/longjmp exceptions, then
7396 this switch can be used to modify this default, and must be
7397 used for all units in the partition.
7398 This option can only be used if the zero cost approach
7399 is available for the target in use, otherwise it will generate an error.
7400 @end table
7401
7402 @noindent
7403 The same option @option{--RTS} must be used both for @command{gcc}
7404 and @command{gnatbind}. Passing this option to @command{gnatmake}
7405 (@pxref{Switches for gnatmake}) will ensure the required consistency
7406 through the compilation and binding steps.
7407
7408 @node Units to Sources Mapping Files
7409 @subsection Units to Sources Mapping Files
7410
7411 @table @option
7412
7413 @item -gnatem=@var{path}
7414 @cindex @option{-gnatem} (@command{gcc})
7415 A mapping file is a way to communicate to the compiler two mappings:
7416 from unit names to file names (without any directory information) and from
7417 file names to path names (with full directory information). These mappings
7418 are used by the compiler to short-circuit the path search.
7419
7420 The use of mapping files is not required for correct operation of the
7421 compiler, but mapping files can improve efficiency, particularly when
7422 sources are read over a slow network connection. In normal operation,
7423 you need not be concerned with the format or use of mapping files,
7424 and the @option{-gnatem} switch is not a switch that you would use
7425 explicitly. It is intended primarily for use by automatic tools such as
7426 @command{gnatmake} running under the project file facility. The
7427 description here of the format of mapping files is provided
7428 for completeness and for possible use by other tools.
7429
7430 A mapping file is a sequence of sets of three lines. In each set, the
7431 first line is the unit name, in lower case, with @code{%s} appended
7432 for specs and @code{%b} appended for bodies; the second line is the
7433 file name; and the third line is the path name.
7434
7435 Example:
7436 @smallexample
7437    main%b
7438    main.2.ada
7439    /gnat/project1/sources/main.2.ada
7440 @end smallexample
7441
7442 When the switch @option{-gnatem} is specified, the compiler will
7443 create in memory the two mappings from the specified file. If there is
7444 any problem (nonexistent file, truncated file or duplicate entries),
7445 no mapping will be created.
7446
7447 Several @option{-gnatem} switches may be specified; however, only the
7448 last one on the command line will be taken into account.
7449
7450 When using a project file, @command{gnatmake} creates a temporary
7451 mapping file and communicates it to the compiler using this switch.
7452
7453 @end table
7454
7455 @node Integrated Preprocessing
7456 @subsection Integrated Preprocessing
7457
7458 @noindent
7459 GNAT sources may be preprocessed immediately before compilation.
7460 In this case, the actual
7461 text of the source is not the text of the source file, but is derived from it
7462 through a process called preprocessing. Integrated preprocessing is specified
7463 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7464 indicates, through a text file, the preprocessing data to be used.
7465 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7466
7467 @noindent
7468 Note that when integrated preprocessing is used, the output from the
7469 preprocessor is not written to any external file. Instead it is passed
7470 internally to the compiler. If you need to preserve the result of
7471 preprocessing in a file, then you should use @command{gnatprep}
7472 to perform the desired preprocessing in stand-alone mode.
7473
7474 @noindent
7475 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7476 used when Integrated Preprocessing is used. The reason is that preprocessing
7477 with another Preprocessing Data file without changing the sources will
7478 not trigger recompilation without this switch.
7479
7480 @noindent
7481 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7482 always trigger recompilation for sources that are preprocessed,
7483 because @command{gnatmake} cannot compute the checksum of the source after
7484 preprocessing.
7485
7486 @noindent
7487 The actual preprocessing function is described in details in section
7488 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7489 preprocessing is triggered and parameterized.
7490
7491 @table @code
7492
7493 @item -gnatep=@var{file}
7494 @cindex @option{-gnatep} (@command{gcc})
7495 This switch indicates to the compiler the file name (without directory
7496 information) of the preprocessor data file to use. The preprocessor data file
7497 should be found in the source directories.
7498
7499 @noindent
7500 A preprocessing data file is a text file with significant lines indicating
7501 how should be preprocessed either a specific source or all sources not
7502 mentioned in other lines. A significant line is a nonempty, non-comment line.
7503 Comments are similar to Ada comments.
7504
7505 @noindent
7506 Each significant line starts with either a literal string or the character '*'.
7507 A literal string is the file name (without directory information) of the source
7508 to preprocess. A character '*' indicates the preprocessing for all the sources
7509 that are not specified explicitly on other lines (order of the lines is not
7510 significant). It is an error to have two lines with the same file name or two
7511 lines starting with the character '*'.
7512
7513 @noindent
7514 After the file name or the character '*', another optional literal string
7515 indicating the file name of the definition file to be used for preprocessing
7516 (@pxref{Form of Definitions File}). The definition files are found by the
7517 compiler in one of the source directories. In some cases, when compiling
7518 a source in a directory other than the current directory, if the definition
7519 file is in the current directory, it may be necessary to add the current
7520 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7521 the compiler would not find the definition file.
7522
7523 @noindent
7524 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7525 be found. Those ^switches^switches^ are:
7526
7527 @table @code
7528
7529 @item -b
7530 Causes both preprocessor lines and the lines deleted by
7531 preprocessing to be replaced by blank lines, preserving the line number.
7532 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7533 it cancels the effect of @option{-c}.
7534
7535 @item -c
7536 Causes both preprocessor lines and the lines deleted
7537 by preprocessing to be retained as comments marked
7538 with the special string ``@code{--! }''.
7539
7540 @item -Dsymbol=value
7541 Define or redefine a symbol, associated with value. A symbol is an Ada
7542 identifier, or an Ada reserved word, with the exception of @code{if},
7543 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7544 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7545 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7546 same name defined in a definition file.
7547
7548 @item -s
7549 Causes a sorted list of symbol names and values to be
7550 listed on the standard output file.
7551
7552 @item -u
7553 Causes undefined symbols to be treated as having the value @code{FALSE}
7554 in the context
7555 of a preprocessor test. In the absence of this option, an undefined symbol in
7556 a @code{#if} or @code{#elsif} test will be treated as an error.
7557
7558 @end table
7559
7560 @noindent
7561 Examples of valid lines in a preprocessor data file:
7562
7563 @smallexample
7564   "toto.adb"  "prep.def" -u
7565   --  preprocess "toto.adb", using definition file "prep.def",
7566   --  undefined symbol are False.
7567
7568   * -c -DVERSION=V101
7569   --  preprocess all other sources without a definition file;
7570   --  suppressed lined are commented; symbol VERSION has the value V101.
7571
7572   "titi.adb" "prep2.def" -s
7573   --  preprocess "titi.adb", using definition file "prep2.def";
7574   --  list all symbols with their values.
7575 @end smallexample
7576
7577 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7578 @cindex @option{-gnateD} (@command{gcc})
7579 Define or redefine a preprocessing symbol, associated with value. If no value
7580 is given on the command line, then the value of the symbol is @code{True}.
7581 A symbol is an identifier, following normal Ada (case-insensitive)
7582 rules for its syntax, and value is any sequence (including an empty sequence)
7583 of characters from the set (letters, digits, period, underline).
7584 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7585 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7586
7587 @noindent
7588 A symbol declared with this ^switch^switch^ on the command line replaces a
7589 symbol with the same name either in a definition file or specified with a
7590 ^switch^switch^ -D in the preprocessor data file.
7591
7592 @noindent
7593 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7594
7595 @item -gnateG
7596 When integrated preprocessing is performed and the preprocessor modifies
7597 the source text, write the result of this preprocessing into a file
7598 <source>^.prep^_prep^.
7599
7600 @end table
7601
7602 @node Code Generation Control
7603 @subsection Code Generation Control
7604
7605 @noindent
7606
7607 The GCC technology provides a wide range of target dependent
7608 @option{-m} switches for controlling
7609 details of code generation with respect to different versions of
7610 architectures. This includes variations in instruction sets (e.g.@:
7611 different members of the power pc family), and different requirements
7612 for optimal arrangement of instructions (e.g.@: different members of
7613 the x86 family). The list of available @option{-m} switches may be
7614 found in the GCC documentation.
7615
7616 Use of these @option{-m} switches may in some cases result in improved
7617 code performance.
7618
7619 The GNAT Pro technology is tested and qualified without any
7620 @option{-m} switches,
7621 so generally the most reliable approach is to avoid the use of these
7622 switches. However, we generally expect most of these switches to work
7623 successfully with GNAT Pro, and many customers have reported successful
7624 use of these options.
7625
7626 Our general advice is to avoid the use of @option{-m} switches unless
7627 special needs lead to requirements in this area. In particular,
7628 there is no point in using @option{-m} switches to improve performance
7629 unless you actually see a performance improvement.
7630
7631 @ifset vms
7632 @node Return Codes
7633 @subsection Return Codes
7634 @cindex Return Codes
7635 @cindex @option{/RETURN_CODES=VMS}
7636
7637 @noindent
7638 On VMS, GNAT compiled programs return POSIX-style codes by default,
7639 e.g.@: @option{/RETURN_CODES=POSIX}.
7640
7641 To enable VMS style return codes, use GNAT BIND and LINK with the option
7642 @option{/RETURN_CODES=VMS}. For example:
7643
7644 @smallexample
7645 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7646 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7647 @end smallexample
7648
7649 @noindent
7650 Programs built with /RETURN_CODES=VMS are suitable to be called in
7651 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7652 are suitable for spawning with appropriate GNAT RTL routines.
7653
7654 @end ifset
7655
7656 @node Search Paths and the Run-Time Library (RTL)
7657 @section Search Paths and the Run-Time Library (RTL)
7658
7659 @noindent
7660 With the GNAT source-based library system, the compiler must be able to
7661 find source files for units that are needed by the unit being compiled.
7662 Search paths are used to guide this process.
7663
7664 The compiler compiles one source file whose name must be given
7665 explicitly on the command line. In other words, no searching is done
7666 for this file. To find all other source files that are needed (the most
7667 common being the specs of units), the compiler examines the following
7668 directories, in the following order:
7669
7670 @enumerate
7671 @item
7672 The directory containing the source file of the main unit being compiled
7673 (the file name on the command line).
7674
7675 @item
7676 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7677 @command{gcc} command line, in the order given.
7678
7679 @item
7680 @findex ADA_PRJ_INCLUDE_FILE
7681 Each of the directories listed in the text file whose name is given
7682 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7683
7684 @noindent
7685 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7686 driver when project files are used. It should not normally be set
7687 by other means.
7688
7689 @item
7690 @findex ADA_INCLUDE_PATH
7691 Each of the directories listed in the value of the
7692 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7693 @ifclear vms
7694 Construct this value
7695 exactly as the @env{PATH} environment variable: a list of directory
7696 names separated by colons (semicolons when working with the NT version).
7697 @end ifclear
7698 @ifset vms
7699 Normally, define this value as a logical name containing a comma separated
7700 list of directory names.
7701
7702 This variable can also be defined by means of an environment string
7703 (an argument to the HP C exec* set of functions).
7704
7705 Logical Name:
7706 @smallexample
7707 DEFINE ANOTHER_PATH FOO:[BAG]
7708 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7709 @end smallexample
7710
7711 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7712 first, followed by the standard Ada
7713 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7714 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7715 (Text_IO, Sequential_IO, etc)
7716 instead of the standard Ada packages. Thus, in order to get the standard Ada
7717 packages by default, ADA_INCLUDE_PATH must be redefined.
7718 @end ifset
7719
7720 @item
7721 The content of the @file{ada_source_path} file which is part of the GNAT
7722 installation tree and is used to store standard libraries such as the
7723 GNAT Run Time Library (RTL) source files.
7724 @ifclear vms
7725 @ref{Installing a library}
7726 @end ifclear
7727 @end enumerate
7728
7729 @noindent
7730 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7731 inhibits the use of the directory
7732 containing the source file named in the command line. You can still
7733 have this directory on your search path, but in this case it must be
7734 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7735
7736 Specifying the switch @option{-nostdinc}
7737 inhibits the search of the default location for the GNAT Run Time
7738 Library (RTL) source files.
7739
7740 The compiler outputs its object files and ALI files in the current
7741 working directory.
7742 @ifclear vms
7743 Caution: The object file can be redirected with the @option{-o} switch;
7744 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7745 so the @file{ALI} file will not go to the right place. Therefore, you should
7746 avoid using the @option{-o} switch.
7747 @end ifclear
7748
7749 @findex System.IO
7750 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7751 children make up the GNAT RTL, together with the simple @code{System.IO}
7752 package used in the @code{"Hello World"} example. The sources for these units
7753 are needed by the compiler and are kept together in one directory. Not
7754 all of the bodies are needed, but all of the sources are kept together
7755 anyway. In a normal installation, you need not specify these directory
7756 names when compiling or binding. Either the environment variables or
7757 the built-in defaults cause these files to be found.
7758
7759 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7760 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7761 consisting of child units of @code{GNAT}. This is a collection of generally
7762 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7763 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7764
7765 Besides simplifying access to the RTL, a major use of search paths is
7766 in compiling sources from multiple directories. This can make
7767 development environments much more flexible.
7768
7769 @node Order of Compilation Issues
7770 @section Order of Compilation Issues
7771
7772 @noindent
7773 If, in our earlier example, there was a spec for the @code{hello}
7774 procedure, it would be contained in the file @file{hello.ads}; yet this
7775 file would not have to be explicitly compiled. This is the result of the
7776 model we chose to implement library management. Some of the consequences
7777 of this model are as follows:
7778
7779 @itemize @bullet
7780 @item
7781 There is no point in compiling specs (except for package
7782 specs with no bodies) because these are compiled as needed by clients. If
7783 you attempt a useless compilation, you will receive an error message.
7784 It is also useless to compile subunits because they are compiled as needed
7785 by the parent.
7786
7787 @item
7788 There are no order of compilation requirements: performing a
7789 compilation never obsoletes anything. The only way you can obsolete
7790 something and require recompilations is to modify one of the
7791 source files on which it depends.
7792
7793 @item
7794 There is no library as such, apart from the ALI files
7795 (@pxref{The Ada Library Information Files}, for information on the format
7796 of these files). For now we find it convenient to create separate ALI files,
7797 but eventually the information therein may be incorporated into the object
7798 file directly.
7799
7800 @item
7801 When you compile a unit, the source files for the specs of all units
7802 that it @code{with}'s, all its subunits, and the bodies of any generics it
7803 instantiates must be available (reachable by the search-paths mechanism
7804 described above), or you will receive a fatal error message.
7805 @end itemize
7806
7807 @node Examples
7808 @section Examples
7809
7810 @noindent
7811 The following are some typical Ada compilation command line examples:
7812
7813 @table @code
7814 @item $ gcc -c xyz.adb
7815 Compile body in file @file{xyz.adb} with all default options.
7816
7817 @ifclear vms
7818 @item $ gcc -c -O2 -gnata xyz-def.adb
7819 @end ifclear
7820 @ifset vms
7821 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7822 @end ifset
7823
7824 Compile the child unit package in file @file{xyz-def.adb} with extensive
7825 optimizations, and pragma @code{Assert}/@code{Debug} statements
7826 enabled.
7827
7828 @item $ gcc -c -gnatc abc-def.adb
7829 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7830 mode.
7831 @end table
7832
7833 @node Binding Using gnatbind
7834 @chapter Binding Using @code{gnatbind}
7835 @findex gnatbind
7836
7837 @menu
7838 * Running gnatbind::
7839 * Switches for gnatbind::
7840 * Command-Line Access::
7841 * Search Paths for gnatbind::
7842 * Examples of gnatbind Usage::
7843 @end menu
7844
7845 @noindent
7846 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7847 to bind compiled GNAT objects.
7848
7849 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7850 driver (see @ref{The GNAT Driver and Project Files}).
7851
7852 The @code{gnatbind} program performs four separate functions:
7853
7854 @enumerate
7855 @item
7856 Checks that a program is consistent, in accordance with the rules in
7857 Chapter 10 of the Ada Reference Manual. In particular, error
7858 messages are generated if a program uses inconsistent versions of a
7859 given unit.
7860
7861 @item
7862 Checks that an acceptable order of elaboration exists for the program
7863 and issues an error message if it cannot find an order of elaboration
7864 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7865
7866 @item
7867 Generates a main program incorporating the given elaboration order.
7868 This program is a small Ada package (body and spec) that
7869 must be subsequently compiled
7870 using the GNAT compiler. The necessary compilation step is usually
7871 performed automatically by @command{gnatlink}. The two most important
7872 functions of this program
7873 are to call the elaboration routines of units in an appropriate order
7874 and to call the main program.
7875
7876 @item
7877 Determines the set of object files required by the given main program.
7878 This information is output in the forms of comments in the generated program,
7879 to be read by the @command{gnatlink} utility used to link the Ada application.
7880 @end enumerate
7881
7882 @node Running gnatbind
7883 @section Running @code{gnatbind}
7884
7885 @noindent
7886 The form of the @code{gnatbind} command is
7887
7888 @smallexample
7889 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7890 @end smallexample
7891
7892 @noindent
7893 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7894 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7895 package in two files whose names are
7896 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7897 For example, if given the
7898 parameter @file{hello.ali}, for a main program contained in file
7899 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7900 and @file{b~hello.adb}.
7901
7902 When doing consistency checking, the binder takes into consideration
7903 any source files it can locate. For example, if the binder determines
7904 that the given main program requires the package @code{Pack}, whose
7905 @file{.ALI}
7906 file is @file{pack.ali} and whose corresponding source spec file is
7907 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7908 (using the same search path conventions as previously described for the
7909 @command{gcc} command). If it can locate this source file, it checks that
7910 the time stamps
7911 or source checksums of the source and its references to in @file{ALI} files
7912 match. In other words, any @file{ALI} files that mentions this spec must have
7913 resulted from compiling this version of the source file (or in the case
7914 where the source checksums match, a version close enough that the
7915 difference does not matter).
7916
7917 @cindex Source files, use by binder
7918 The effect of this consistency checking, which includes source files, is
7919 that the binder ensures that the program is consistent with the latest
7920 version of the source files that can be located at bind time. Editing a
7921 source file without compiling files that depend on the source file cause
7922 error messages to be generated by the binder.
7923
7924 For example, suppose you have a main program @file{hello.adb} and a
7925 package @code{P}, from file @file{p.ads} and you perform the following
7926 steps:
7927
7928 @enumerate
7929 @item
7930 Enter @code{gcc -c hello.adb} to compile the main program.
7931
7932 @item
7933 Enter @code{gcc -c p.ads} to compile package @code{P}.
7934
7935 @item
7936 Edit file @file{p.ads}.
7937
7938 @item
7939 Enter @code{gnatbind hello}.
7940 @end enumerate
7941
7942 @noindent
7943 At this point, the file @file{p.ali} contains an out-of-date time stamp
7944 because the file @file{p.ads} has been edited. The attempt at binding
7945 fails, and the binder generates the following error messages:
7946
7947 @smallexample
7948 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7949 error: "p.ads" has been modified and must be recompiled
7950 @end smallexample
7951
7952 @noindent
7953 Now both files must be recompiled as indicated, and then the bind can
7954 succeed, generating a main program. You need not normally be concerned
7955 with the contents of this file, but for reference purposes a sample
7956 binder output file is given in @ref{Example of Binder Output File}.
7957
7958 In most normal usage, the default mode of @command{gnatbind} which is to
7959 generate the main package in Ada, as described in the previous section.
7960 In particular, this means that any Ada programmer can read and understand
7961 the generated main program. It can also be debugged just like any other
7962 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7963 @command{gnatbind} and @command{gnatlink}.
7964
7965 However for some purposes it may be convenient to generate the main
7966 program in C rather than Ada. This may for example be helpful when you
7967 are generating a mixed language program with the main program in C. The
7968 GNAT compiler itself is an example.
7969 The use of the @option{^-C^/BIND_FILE=C^} switch
7970 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7971 be generated in C (and compiled using the gnu C compiler).
7972
7973 @node Switches for gnatbind
7974 @section Switches for @command{gnatbind}
7975
7976 @noindent
7977 The following switches are available with @code{gnatbind}; details will
7978 be presented in subsequent sections.
7979
7980 @menu
7981 * Consistency-Checking Modes::
7982 * Binder Error Message Control::
7983 * Elaboration Control::
7984 * Output Control::
7985 * Binding with Non-Ada Main Programs::
7986 * Binding Programs with No Main Subprogram::
7987 @end menu
7988
7989 @table @option
7990 @c !sort!
7991
7992 @item --version
7993 @cindex @option{--version} @command{gnatbind}
7994 Display Copyright and version, then exit disregarding all other options.
7995
7996 @item --help
7997 @cindex @option{--help} @command{gnatbind}
7998 If @option{--version} was not used, display usage, then exit disregarding
7999 all other options.
8000
8001 @item -a
8002 @cindex @option{-a} @command{gnatbind}
8003 Indicates that, if supported by the platform, the adainit procedure should
8004 be treated as an initialisation routine by the linker (a constructor). This
8005 is intended to be used by the Project Manager to automatically initialize
8006 shared Stand-Alone Libraries.
8007
8008 @item ^-aO^/OBJECT_SEARCH^
8009 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8010 Specify directory to be searched for ALI files.
8011
8012 @item ^-aI^/SOURCE_SEARCH^
8013 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8014 Specify directory to be searched for source file.
8015
8016 @item ^-A^/BIND_FILE=ADA^
8017 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
8018 Generate binder program in Ada (default)
8019
8020 @item ^-b^/REPORT_ERRORS=BRIEF^
8021 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8022 Generate brief messages to @file{stderr} even if verbose mode set.
8023
8024 @item ^-c^/NOOUTPUT^
8025 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8026 Check only, no generation of binder output file.
8027
8028 @item ^-C^/BIND_FILE=C^
8029 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
8030 Generate binder program in C
8031
8032 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8033 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8034 This switch can be used to change the default task stack size value
8035 to a specified size @var{nn}, which is expressed in bytes by default, or
8036 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8037 with @var{m}.
8038 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8039 in effect, to completing all task specs with
8040 @smallexample @c ada
8041    pragma Storage_Size (nn);
8042 @end smallexample
8043 When they do not already have such a pragma.
8044
8045 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8046 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8047 This switch can be used to change the default secondary stack size value
8048 to a specified size @var{nn}, which is expressed in bytes by default, or
8049 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8050 with @var{m}.
8051
8052 The secondary stack is used to deal with functions that return a variable
8053 sized result, for example a function returning an unconstrained
8054 String. There are two ways in which this secondary stack is allocated.
8055
8056 For most targets, the secondary stack is growing on demand and is allocated
8057 as a chain of blocks in the heap. The -D option is not very
8058 relevant. It only give some control over the size of the allocated
8059 blocks (whose size is the minimum of the default secondary stack size value,
8060 and the actual size needed for the current allocation request).
8061
8062 For certain targets, notably VxWorks 653,
8063 the secondary stack is allocated by carving off a fixed ratio chunk of the
8064 primary task stack. The -D option is used to define the
8065 size of the environment task's secondary stack.
8066
8067 @item ^-e^/ELABORATION_DEPENDENCIES^
8068 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8069 Output complete list of elaboration-order dependencies.
8070
8071 @item ^-E^/STORE_TRACEBACKS^
8072 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8073 Store tracebacks in exception occurrences when the target supports it.
8074 This is the default with the zero cost exception mechanism.
8075 @ignore
8076 @c The following may get moved to an appendix
8077 This option is currently supported on the following targets:
8078 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8079 @end ignore
8080 See also the packages @code{GNAT.Traceback} and
8081 @code{GNAT.Traceback.Symbolic} for more information.
8082 @ifclear vms
8083 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8084 @command{gcc} option.
8085 @end ifclear
8086
8087 @item ^-F^/FORCE_ELABS_FLAGS^
8088 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8089 Force the checks of elaboration flags. @command{gnatbind} does not normally
8090 generate checks of elaboration flags for the main executable, except when
8091 a Stand-Alone Library is used. However, there are cases when this cannot be
8092 detected by gnatbind. An example is importing an interface of a Stand-Alone
8093 Library through a pragma Import and only specifying through a linker switch
8094 this Stand-Alone Library. This switch is used to guarantee that elaboration
8095 flag checks are generated.
8096
8097 @item ^-h^/HELP^
8098 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8099 Output usage (help) information
8100
8101 @item ^-I^/SEARCH^
8102 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8103 Specify directory to be searched for source and ALI files.
8104
8105 @item ^-I-^/NOCURRENT_DIRECTORY^
8106 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8107 Do not look for sources in the current directory where @code{gnatbind} was
8108 invoked, and do not look for ALI files in the directory containing the
8109 ALI file named in the @code{gnatbind} command line.
8110
8111 @item ^-l^/ORDER_OF_ELABORATION^
8112 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8113 Output chosen elaboration order.
8114
8115 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8116 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8117 Bind the units for library building. In this case the adainit and
8118 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8119 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8120 ^@var{xxx}final^@var{XXX}FINAL^.
8121 Implies ^-n^/NOCOMPILE^.
8122 @ifclear vms
8123 (@xref{GNAT and Libraries}, for more details.)
8124 @end ifclear
8125 @ifset vms
8126 On OpenVMS, these init and final procedures are exported in uppercase
8127 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8128 the init procedure will be "TOTOINIT" and the exported name of the final
8129 procedure will be "TOTOFINAL".
8130 @end ifset
8131
8132 @item ^-Mxyz^/RENAME_MAIN=xyz^
8133 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8134 Rename generated main program from main to xyz. This option is
8135 supported on cross environments only.
8136
8137 @item ^-m^/ERROR_LIMIT=^@var{n}
8138 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8139 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8140 in the range 1..999999. The default value if no switch is
8141 given is 9999. If the number of warnings reaches this limit, then a
8142 message is output and further warnings are suppressed, the bind
8143 continues in this case. If the number of errors reaches this
8144 limit, then a message is output and the bind is abandoned.
8145 A value of zero means that no limit is enforced. The equal
8146 sign is optional.
8147
8148 @ifset unw
8149 Furthermore, under Windows, the sources pointed to by the libraries path
8150 set in the registry are not searched for.
8151 @end ifset
8152
8153 @item ^-n^/NOMAIN^
8154 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8155 No main program.
8156
8157 @item -nostdinc
8158 @cindex @option{-nostdinc} (@command{gnatbind})
8159 Do not look for sources in the system default directory.
8160
8161 @item -nostdlib
8162 @cindex @option{-nostdlib} (@command{gnatbind})
8163 Do not look for library files in the system default directory.
8164
8165 @item --RTS=@var{rts-path}
8166 @cindex @option{--RTS} (@code{gnatbind})
8167 Specifies the default location of the runtime library. Same meaning as the
8168 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8169
8170 @item ^-o ^/OUTPUT=^@var{file}
8171 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8172 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8173 Note that if this option is used, then linking must be done manually,
8174 gnatlink cannot be used.
8175
8176 @item ^-O^/OBJECT_LIST^
8177 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8178 Output object list.
8179
8180 @item ^-p^/PESSIMISTIC_ELABORATION^
8181 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8182 Pessimistic (worst-case) elaboration order
8183
8184 @item ^-R^-R^
8185 @cindex @option{^-R^-R^} (@command{gnatbind})
8186 Output closure source list.
8187
8188 @item ^-s^/READ_SOURCES=ALL^
8189 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8190 Require all source files to be present.
8191
8192 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8193 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8194 Specifies the value to be used when detecting uninitialized scalar
8195 objects with pragma Initialize_Scalars.
8196 The @var{xxx} ^string specified with the switch^option^ may be either
8197 @itemize @bullet
8198 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8199 @item ``@option{^lo^LOW^}'' for the lowest possible value
8200 @item ``@option{^hi^HIGH^}'' for the highest possible value
8201 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8202 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8203 @end itemize
8204
8205 In addition, you can specify @option{-Sev} to indicate that the value is
8206 to be set at run time. In this case, the program will look for an environment
8207 @cindex GNAT_INIT_SCALARS
8208 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8209 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8210 If no environment variable is found, or if it does not have a valid value,
8211 then the default is @option{in} (invalid values).
8212
8213 @ifclear vms
8214 @item -static
8215 @cindex @option{-static} (@code{gnatbind})
8216 Link against a static GNAT run time.
8217
8218 @item -shared
8219 @cindex @option{-shared} (@code{gnatbind})
8220 Link against a shared GNAT run time when available.
8221 @end ifclear
8222
8223 @item ^-t^/NOTIME_STAMP_CHECK^
8224 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8225 Tolerate time stamp and other consistency errors
8226
8227 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8228 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8229 Set the time slice value to @var{n} milliseconds. If the system supports
8230 the specification of a specific time slice value, then the indicated value
8231 is used. If the system does not support specific time slice values, but
8232 does support some general notion of round-robin scheduling, then any
8233 nonzero value will activate round-robin scheduling.
8234
8235 A value of zero is treated specially. It turns off time
8236 slicing, and in addition, indicates to the tasking run time that the
8237 semantics should match as closely as possible the Annex D
8238 requirements of the Ada RM, and in particular sets the default
8239 scheduling policy to @code{FIFO_Within_Priorities}.
8240
8241 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8242 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8243 Enable dynamic stack usage, with @var{n} results stored and displayed
8244 at program termination. A result is generated when a task
8245 terminates. Results that can't be stored are displayed on the fly, at
8246 task termination. This option is currently not supported on Itanium
8247 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8248
8249 @item ^-v^/REPORT_ERRORS=VERBOSE^
8250 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8251 Verbose mode. Write error messages, header, summary output to
8252 @file{stdout}.
8253
8254 @ifclear vms
8255 @item -w@var{x}
8256 @cindex @option{-w} (@code{gnatbind})
8257 Warning mode (@var{x}=s/e for suppress/treat as error)
8258 @end ifclear
8259
8260 @ifset vms
8261 @item /WARNINGS=NORMAL
8262 @cindex @option{/WARNINGS} (@code{gnatbind})
8263 Normal warnings mode. Warnings are issued but ignored
8264
8265 @item /WARNINGS=SUPPRESS
8266 @cindex @option{/WARNINGS} (@code{gnatbind})
8267 All warning messages are suppressed
8268
8269 @item /WARNINGS=ERROR
8270 @cindex @option{/WARNINGS} (@code{gnatbind})
8271 Warning messages are treated as fatal errors
8272 @end ifset
8273
8274 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8275 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8276 Override default wide character encoding for standard Text_IO files.
8277
8278 @item ^-x^/READ_SOURCES=NONE^
8279 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8280 Exclude source files (check object consistency only).
8281
8282 @ifset vms
8283 @item /READ_SOURCES=AVAILABLE
8284 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8285 Default mode, in which sources are checked for consistency only if
8286 they are available.
8287 @end ifset
8288
8289 @item ^-y^/ENABLE_LEAP_SECONDS^
8290 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8291 Enable leap seconds support in @code{Ada.Calendar} and its children.
8292
8293 @item ^-z^/ZERO_MAIN^
8294 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8295 No main subprogram.
8296 @end table
8297
8298 @ifclear vms
8299 @noindent
8300 You may obtain this listing of switches by running @code{gnatbind} with
8301 no arguments.
8302 @end ifclear
8303
8304 @node Consistency-Checking Modes
8305 @subsection Consistency-Checking Modes
8306
8307 @noindent
8308 As described earlier, by default @code{gnatbind} checks
8309 that object files are consistent with one another and are consistent
8310 with any source files it can locate. The following switches control binder
8311 access to sources.
8312
8313 @table @option
8314 @c !sort!
8315 @item ^-s^/READ_SOURCES=ALL^
8316 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8317 Require source files to be present. In this mode, the binder must be
8318 able to locate all source files that are referenced, in order to check
8319 their consistency. In normal mode, if a source file cannot be located it
8320 is simply ignored. If you specify this switch, a missing source
8321 file is an error.
8322
8323 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8324 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8325 Override default wide character encoding for standard Text_IO files.
8326 Normally the default wide character encoding method used for standard
8327 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8328 the main source input (see description of switch
8329 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8330 use of this switch for the binder (which has the same set of
8331 possible arguments) overrides this default as specified.
8332
8333 @item ^-x^/READ_SOURCES=NONE^
8334 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8335 Exclude source files. In this mode, the binder only checks that ALI
8336 files are consistent with one another. Source files are not accessed.
8337 The binder runs faster in this mode, and there is still a guarantee that
8338 the resulting program is self-consistent.
8339 If a source file has been edited since it was last compiled, and you
8340 specify this switch, the binder will not detect that the object
8341 file is out of date with respect to the source file. Note that this is the
8342 mode that is automatically used by @command{gnatmake} because in this
8343 case the checking against sources has already been performed by
8344 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8345
8346 @ifset vms
8347 @item /READ_SOURCES=AVAILABLE
8348 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8349 This is the default mode in which source files are checked if they are
8350 available, and ignored if they are not available.
8351 @end ifset
8352 @end table
8353
8354 @node Binder Error Message Control
8355 @subsection Binder Error Message Control
8356
8357 @noindent
8358 The following switches provide control over the generation of error
8359 messages from the binder:
8360
8361 @table @option
8362 @c !sort!
8363 @item ^-v^/REPORT_ERRORS=VERBOSE^
8364 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8365 Verbose mode. In the normal mode, brief error messages are generated to
8366 @file{stderr}. If this switch is present, a header is written
8367 to @file{stdout} and any error messages are directed to @file{stdout}.
8368 All that is written to @file{stderr} is a brief summary message.
8369
8370 @item ^-b^/REPORT_ERRORS=BRIEF^
8371 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8372 Generate brief error messages to @file{stderr} even if verbose mode is
8373 specified. This is relevant only when used with the
8374 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8375
8376 @ifclear vms
8377 @item -m@var{n}
8378 @cindex @option{-m} (@code{gnatbind})
8379 Limits the number of error messages to @var{n}, a decimal integer in the
8380 range 1-999. The binder terminates immediately if this limit is reached.
8381
8382 @item -M@var{xxx}
8383 @cindex @option{-M} (@code{gnatbind})
8384 Renames the generated main program from @code{main} to @code{xxx}.
8385 This is useful in the case of some cross-building environments, where
8386 the actual main program is separate from the one generated
8387 by @code{gnatbind}.
8388 @end ifclear
8389
8390 @item ^-ws^/WARNINGS=SUPPRESS^
8391 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8392 @cindex Warnings
8393 Suppress all warning messages.
8394
8395 @item ^-we^/WARNINGS=ERROR^
8396 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8397 Treat any warning messages as fatal errors.
8398
8399 @ifset vms
8400 @item /WARNINGS=NORMAL
8401 Standard mode with warnings generated, but warnings do not get treated
8402 as errors.
8403 @end ifset
8404
8405 @item ^-t^/NOTIME_STAMP_CHECK^
8406 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8407 @cindex Time stamp checks, in binder
8408 @cindex Binder consistency checks
8409 @cindex Consistency checks, in binder
8410 The binder performs a number of consistency checks including:
8411
8412 @itemize @bullet
8413 @item
8414 Check that time stamps of a given source unit are consistent
8415 @item
8416 Check that checksums of a given source unit are consistent
8417 @item
8418 Check that consistent versions of @code{GNAT} were used for compilation
8419 @item
8420 Check consistency of configuration pragmas as required
8421 @end itemize
8422
8423 @noindent
8424 Normally failure of such checks, in accordance with the consistency
8425 requirements of the Ada Reference Manual, causes error messages to be
8426 generated which abort the binder and prevent the output of a binder
8427 file and subsequent link to obtain an executable.
8428
8429 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8430 into warnings, so that
8431 binding and linking can continue to completion even in the presence of such
8432 errors. The result may be a failed link (due to missing symbols), or a
8433 non-functional executable which has undefined semantics.
8434 @emph{This means that
8435 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8436 with extreme care.}
8437 @end table
8438
8439 @node Elaboration Control
8440 @subsection Elaboration Control
8441
8442 @noindent
8443 The following switches provide additional control over the elaboration
8444 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8445
8446 @table @option
8447 @item ^-p^/PESSIMISTIC_ELABORATION^
8448 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8449 Normally the binder attempts to choose an elaboration order that is
8450 likely to minimize the likelihood of an elaboration order error resulting
8451 in raising a @code{Program_Error} exception. This switch reverses the
8452 action of the binder, and requests that it deliberately choose an order
8453 that is likely to maximize the likelihood of an elaboration error.
8454 This is useful in ensuring portability and avoiding dependence on
8455 accidental fortuitous elaboration ordering.
8456
8457 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8458 switch if dynamic
8459 elaboration checking is used (@option{-gnatE} switch used for compilation).
8460 This is because in the default static elaboration mode, all necessary
8461 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8462 These implicit pragmas are still respected by the binder in
8463 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8464 safe elaboration order is assured.
8465 @end table
8466
8467 @node Output Control
8468 @subsection Output Control
8469
8470 @noindent
8471 The following switches allow additional control over the output
8472 generated by the binder.
8473
8474 @table @option
8475 @c !sort!
8476
8477 @item ^-A^/BIND_FILE=ADA^
8478 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8479 Generate binder program in Ada (default). The binder program is named
8480 @file{b~@var{mainprog}.adb} by default. This can be changed with
8481 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8482
8483 @item ^-c^/NOOUTPUT^
8484 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8485 Check only. Do not generate the binder output file. In this mode the
8486 binder performs all error checks but does not generate an output file.
8487
8488 @item ^-C^/BIND_FILE=C^
8489 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8490 Generate binder program in C. The binder program is named
8491 @file{b_@var{mainprog}.c}.
8492 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8493 option.
8494
8495 @item ^-e^/ELABORATION_DEPENDENCIES^
8496 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8497 Output complete list of elaboration-order dependencies, showing the
8498 reason for each dependency. This output can be rather extensive but may
8499 be useful in diagnosing problems with elaboration order. The output is
8500 written to @file{stdout}.
8501
8502 @item ^-h^/HELP^
8503 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8504 Output usage information. The output is written to @file{stdout}.
8505
8506 @item ^-K^/LINKER_OPTION_LIST^
8507 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8508 Output linker options to @file{stdout}. Includes library search paths,
8509 contents of pragmas Ident and Linker_Options, and libraries added
8510 by @code{gnatbind}.
8511
8512 @item ^-l^/ORDER_OF_ELABORATION^
8513 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8514 Output chosen elaboration order. The output is written to @file{stdout}.
8515
8516 @item ^-O^/OBJECT_LIST^
8517 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8518 Output full names of all the object files that must be linked to provide
8519 the Ada component of the program. The output is written to @file{stdout}.
8520 This list includes the files explicitly supplied and referenced by the user
8521 as well as implicitly referenced run-time unit files. The latter are
8522 omitted if the corresponding units reside in shared libraries. The
8523 directory names for the run-time units depend on the system configuration.
8524
8525 @item ^-o ^/OUTPUT=^@var{file}
8526 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8527 Set name of output file to @var{file} instead of the normal
8528 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8529 binder generated body filename. In C mode you would normally give
8530 @var{file} an extension of @file{.c} because it will be a C source program.
8531 Note that if this option is used, then linking must be done manually.
8532 It is not possible to use gnatlink in this case, since it cannot locate
8533 the binder file.
8534
8535 @item ^-r^/RESTRICTION_LIST^
8536 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8537 Generate list of @code{pragma Restrictions} that could be applied to
8538 the current unit. This is useful for code audit purposes, and also may
8539 be used to improve code generation in some cases.
8540
8541 @end table
8542
8543 @node Binding with Non-Ada Main Programs
8544 @subsection Binding with Non-Ada Main Programs
8545
8546 @noindent
8547 In our description so far we have assumed that the main
8548 program is in Ada, and that the task of the binder is to generate a
8549 corresponding function @code{main} that invokes this Ada main
8550 program. GNAT also supports the building of executable programs where
8551 the main program is not in Ada, but some of the called routines are
8552 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8553 The following switch is used in this situation:
8554
8555 @table @option
8556 @item ^-n^/NOMAIN^
8557 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8558 No main program. The main program is not in Ada.
8559 @end table
8560
8561 @noindent
8562 In this case, most of the functions of the binder are still required,
8563 but instead of generating a main program, the binder generates a file
8564 containing the following callable routines:
8565
8566 @table @code
8567 @item adainit
8568 @findex adainit
8569 You must call this routine to initialize the Ada part of the program by
8570 calling the necessary elaboration routines. A call to @code{adainit} is
8571 required before the first call to an Ada subprogram.
8572
8573 Note that it is assumed that the basic execution environment must be setup
8574 to be appropriate for Ada execution at the point where the first Ada
8575 subprogram is called. In particular, if the Ada code will do any
8576 floating-point operations, then the FPU must be setup in an appropriate
8577 manner. For the case of the x86, for example, full precision mode is
8578 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8579 that the FPU is in the right state.
8580
8581 @item adafinal
8582 @findex adafinal
8583 You must call this routine to perform any library-level finalization
8584 required by the Ada subprograms. A call to @code{adafinal} is required
8585 after the last call to an Ada subprogram, and before the program
8586 terminates.
8587 @end table
8588
8589 @noindent
8590 If the @option{^-n^/NOMAIN^} switch
8591 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8592 @cindex Binder, multiple input files
8593 is given, more than one ALI file may appear on
8594 the command line for @code{gnatbind}. The normal @dfn{closure}
8595 calculation is performed for each of the specified units. Calculating
8596 the closure means finding out the set of units involved by tracing
8597 @code{with} references. The reason it is necessary to be able to
8598 specify more than one ALI file is that a given program may invoke two or
8599 more quite separate groups of Ada units.
8600
8601 The binder takes the name of its output file from the last specified ALI
8602 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8603 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8604 The output is an Ada unit in source form that can
8605 be compiled with GNAT unless the -C switch is used in which case the
8606 output is a C source file, which must be compiled using the C compiler.
8607 This compilation occurs automatically as part of the @command{gnatlink}
8608 processing.
8609
8610 Currently the GNAT run time requires a FPU using 80 bits mode
8611 precision. Under targets where this is not the default it is required to
8612 call GNAT.Float_Control.Reset before using floating point numbers (this
8613 include float computation, float input and output) in the Ada code. A
8614 side effect is that this could be the wrong mode for the foreign code
8615 where floating point computation could be broken after this call.
8616
8617 @node Binding Programs with No Main Subprogram
8618 @subsection Binding Programs with No Main Subprogram
8619
8620 @noindent
8621 It is possible to have an Ada program which does not have a main
8622 subprogram. This program will call the elaboration routines of all the
8623 packages, then the finalization routines.
8624
8625 The following switch is used to bind programs organized in this manner:
8626
8627 @table @option
8628 @item ^-z^/ZERO_MAIN^
8629 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8630 Normally the binder checks that the unit name given on the command line
8631 corresponds to a suitable main subprogram. When this switch is used,
8632 a list of ALI files can be given, and the execution of the program
8633 consists of elaboration of these units in an appropriate order. Note
8634 that the default wide character encoding method for standard Text_IO
8635 files is always set to Brackets if this switch is set (you can use
8636 the binder switch
8637 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8638 @end table
8639
8640 @node Command-Line Access
8641 @section Command-Line Access
8642
8643 @noindent
8644 The package @code{Ada.Command_Line} provides access to the command-line
8645 arguments and program name. In order for this interface to operate
8646 correctly, the two variables
8647
8648 @smallexample
8649 @group
8650 int gnat_argc;
8651 char **gnat_argv;
8652 @end group
8653 @end smallexample
8654
8655 @noindent
8656 @findex gnat_argv
8657 @findex gnat_argc
8658 are declared in one of the GNAT library routines. These variables must
8659 be set from the actual @code{argc} and @code{argv} values passed to the
8660 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8661 generates the C main program to automatically set these variables.
8662 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8663 set these variables. If they are not set, the procedures in
8664 @code{Ada.Command_Line} will not be available, and any attempt to use
8665 them will raise @code{Constraint_Error}. If command line access is
8666 required, your main program must set @code{gnat_argc} and
8667 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8668 it.
8669
8670 @node Search Paths for gnatbind
8671 @section Search Paths for @code{gnatbind}
8672
8673 @noindent
8674 The binder takes the name of an ALI file as its argument and needs to
8675 locate source files as well as other ALI files to verify object consistency.
8676
8677 For source files, it follows exactly the same search rules as @command{gcc}
8678 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8679 directories searched are:
8680
8681 @enumerate
8682 @item
8683 The directory containing the ALI file named in the command line, unless
8684 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8685
8686 @item
8687 All directories specified by @option{^-I^/SEARCH^}
8688 switches on the @code{gnatbind}
8689 command line, in the order given.
8690
8691 @item
8692 @findex ADA_PRJ_OBJECTS_FILE
8693 Each of the directories listed in the text file whose name is given
8694 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8695
8696 @noindent
8697 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8698 driver when project files are used. It should not normally be set
8699 by other means.
8700
8701 @item
8702 @findex ADA_OBJECTS_PATH
8703 Each of the directories listed in the value of the
8704 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8705 @ifset unw
8706 Construct this value
8707 exactly as the @env{PATH} environment variable: a list of directory
8708 names separated by colons (semicolons when working with the NT version
8709 of GNAT).
8710 @end ifset
8711 @ifset vms
8712 Normally, define this value as a logical name containing a comma separated
8713 list of directory names.
8714
8715 This variable can also be defined by means of an environment string
8716 (an argument to the HP C exec* set of functions).
8717
8718 Logical Name:
8719 @smallexample
8720 DEFINE ANOTHER_PATH FOO:[BAG]
8721 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8722 @end smallexample
8723
8724 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8725 first, followed by the standard Ada
8726 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8727 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8728 (Text_IO, Sequential_IO, etc)
8729 instead of the standard Ada packages. Thus, in order to get the standard Ada
8730 packages by default, ADA_OBJECTS_PATH must be redefined.
8731 @end ifset
8732
8733 @item
8734 The content of the @file{ada_object_path} file which is part of the GNAT
8735 installation tree and is used to store standard libraries such as the
8736 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8737 specified.
8738 @ifclear vms
8739 @ref{Installing a library}
8740 @end ifclear
8741 @end enumerate
8742
8743 @noindent
8744 In the binder the switch @option{^-I^/SEARCH^}
8745 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8746 is used to specify both source and
8747 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8748 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8749 instead if you want to specify
8750 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8751 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8752 if you want to specify library paths
8753 only. This means that for the binder
8754 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8755 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8756 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8757 The binder generates the bind file (a C language source file) in the
8758 current working directory.
8759
8760 @findex Ada
8761 @findex System
8762 @findex Interfaces
8763 @findex GNAT
8764 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8765 children make up the GNAT Run-Time Library, together with the package
8766 GNAT and its children, which contain a set of useful additional
8767 library functions provided by GNAT. The sources for these units are
8768 needed by the compiler and are kept together in one directory. The ALI
8769 files and object files generated by compiling the RTL are needed by the
8770 binder and the linker and are kept together in one directory, typically
8771 different from the directory containing the sources. In a normal
8772 installation, you need not specify these directory names when compiling
8773 or binding. Either the environment variables or the built-in defaults
8774 cause these files to be found.
8775
8776 Besides simplifying access to the RTL, a major use of search paths is
8777 in compiling sources from multiple directories. This can make
8778 development environments much more flexible.
8779
8780 @node Examples of gnatbind Usage
8781 @section Examples of @code{gnatbind} Usage
8782
8783 @noindent
8784 This section contains a number of examples of using the GNAT binding
8785 utility @code{gnatbind}.
8786
8787 @table @code
8788 @item gnatbind hello
8789 The main program @code{Hello} (source program in @file{hello.adb}) is
8790 bound using the standard switch settings. The generated main program is
8791 @file{b~hello.adb}. This is the normal, default use of the binder.
8792
8793 @ifclear vms
8794 @item gnatbind hello -o mainprog.adb
8795 @end ifclear
8796 @ifset vms
8797 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8798 @end ifset
8799 The main program @code{Hello} (source program in @file{hello.adb}) is
8800 bound using the standard switch settings. The generated main program is
8801 @file{mainprog.adb} with the associated spec in
8802 @file{mainprog.ads}. Note that you must specify the body here not the
8803 spec, in the case where the output is in Ada. Note that if this option
8804 is used, then linking must be done manually, since gnatlink will not
8805 be able to find the generated file.
8806
8807 @ifclear vms
8808 @item gnatbind main -C -o mainprog.c -x
8809 @end ifclear
8810 @ifset vms
8811 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8812 @end ifset
8813 The main program @code{Main} (source program in
8814 @file{main.adb}) is bound, excluding source files from the
8815 consistency checking, generating
8816 the file @file{mainprog.c}.
8817
8818 @ifclear vms
8819 @item gnatbind -x main_program -C -o mainprog.c
8820 This command is exactly the same as the previous example. Switches may
8821 appear anywhere in the command line, and single letter switches may be
8822 combined into a single switch.
8823 @end ifclear
8824
8825 @ifclear vms
8826 @item gnatbind -n math dbase -C -o ada-control.c
8827 @end ifclear
8828 @ifset vms
8829 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8830 @end ifset
8831 The main program is in a language other than Ada, but calls to
8832 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8833 to @code{gnatbind} generates the file @file{ada-control.c} containing
8834 the @code{adainit} and @code{adafinal} routines to be called before and
8835 after accessing the Ada units.
8836 @end table
8837
8838 @c ------------------------------------
8839 @node Linking Using gnatlink
8840 @chapter Linking Using @command{gnatlink}
8841 @c ------------------------------------
8842 @findex gnatlink
8843
8844 @noindent
8845 This chapter discusses @command{gnatlink}, a tool that links
8846 an Ada program and builds an executable file. This utility
8847 invokes the system linker ^(via the @command{gcc} command)^^
8848 with a correct list of object files and library references.
8849 @command{gnatlink} automatically determines the list of files and
8850 references for the Ada part of a program. It uses the binder file
8851 generated by the @command{gnatbind} to determine this list.
8852
8853 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8854 driver (see @ref{The GNAT Driver and Project Files}).
8855
8856 @menu
8857 * Running gnatlink::
8858 * Switches for gnatlink::
8859 @end menu
8860
8861 @node Running gnatlink
8862 @section Running @command{gnatlink}
8863
8864 @noindent
8865 The form of the @command{gnatlink} command is
8866
8867 @smallexample
8868 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8869            @ovar{non-Ada objects} @ovar{linker options}
8870 @end smallexample
8871
8872 @noindent
8873 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8874 non-Ada objects
8875 or linker options) may be in any order, provided that no non-Ada object may
8876 be mistaken for a main @file{ALI} file.
8877 Any file name @file{F} without the @file{.ali}
8878 extension will be taken as the main @file{ALI} file if a file exists
8879 whose name is the concatenation of @file{F} and @file{.ali}.
8880
8881 @noindent
8882 @file{@var{mainprog}.ali} references the ALI file of the main program.
8883 The @file{.ali} extension of this file can be omitted. From this
8884 reference, @command{gnatlink} locates the corresponding binder file
8885 @file{b~@var{mainprog}.adb} and, using the information in this file along
8886 with the list of non-Ada objects and linker options, constructs a
8887 linker command file to create the executable.
8888
8889 The arguments other than the @command{gnatlink} switches and the main
8890 @file{ALI} file are passed to the linker uninterpreted.
8891 They typically include the names of
8892 object files for units written in other languages than Ada and any library
8893 references required to resolve references in any of these foreign language
8894 units, or in @code{Import} pragmas in any Ada units.
8895
8896 @var{linker options} is an optional list of linker specific
8897 switches.
8898 The default linker called by gnatlink is @command{gcc} which in
8899 turn calls the appropriate system linker.
8900 Standard options for the linker such as @option{-lmy_lib} or
8901 @option{-Ldir} can be added as is.
8902 For options that are not recognized by
8903 @command{gcc} as linker options, use the @command{gcc} switches
8904 @option{-Xlinker} or @option{-Wl,}.
8905 Refer to the GCC documentation for
8906 details. Here is an example showing how to generate a linker map:
8907
8908 @smallexample
8909 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8910 @end smallexample
8911
8912 Using @var{linker options} it is possible to set the program stack and
8913 heap size.
8914 @ifset unw
8915 See @ref{Setting Stack Size from gnatlink} and
8916 @ref{Setting Heap Size from gnatlink}.
8917 @end ifset
8918
8919 @command{gnatlink} determines the list of objects required by the Ada
8920 program and prepends them to the list of objects passed to the linker.
8921 @command{gnatlink} also gathers any arguments set by the use of
8922 @code{pragma Linker_Options} and adds them to the list of arguments
8923 presented to the linker.
8924
8925 @ifset vms
8926 @command{gnatlink} accepts the following types of extra files on the command
8927 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8928 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8929 handled according to their extension.
8930 @end ifset
8931
8932 @node Switches for gnatlink
8933 @section Switches for @command{gnatlink}
8934
8935 @noindent
8936 The following switches are available with the @command{gnatlink} utility:
8937
8938 @table @option
8939 @c !sort!
8940
8941 @item --version
8942 @cindex @option{--version} @command{gnatlink}
8943 Display Copyright and version, then exit disregarding all other options.
8944
8945 @item --help
8946 @cindex @option{--help} @command{gnatlink}
8947 If @option{--version} was not used, display usage, then exit disregarding
8948 all other options.
8949
8950 @item ^-A^/BIND_FILE=ADA^
8951 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8952 The binder has generated code in Ada. This is the default.
8953
8954 @item ^-C^/BIND_FILE=C^
8955 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8956 If instead of generating a file in Ada, the binder has generated one in
8957 C, then the linker needs to know about it. Use this switch to signal
8958 to @command{gnatlink} that the binder has generated C code rather than
8959 Ada code.
8960
8961 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8962 @cindex Command line length
8963 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8964 On some targets, the command line length is limited, and @command{gnatlink}
8965 will generate a separate file for the linker if the list of object files
8966 is too long.
8967 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8968 to be generated even if
8969 the limit is not exceeded. This is useful in some cases to deal with
8970 special situations where the command line length is exceeded.
8971
8972 @item ^-g^/DEBUG^
8973 @cindex Debugging information, including
8974 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8975 The option to include debugging information causes the Ada bind file (in
8976 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8977 @option{^-g^/DEBUG^}.
8978 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8979 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8980 Without @option{^-g^/DEBUG^}, the binder removes these files by
8981 default. The same procedure apply if a C bind file was generated using
8982 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8983 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8984
8985 @item ^-n^/NOCOMPILE^
8986 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8987 Do not compile the file generated by the binder. This may be used when
8988 a link is rerun with different options, but there is no need to recompile
8989 the binder file.
8990
8991 @item ^-v^/VERBOSE^
8992 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8993 Causes additional information to be output, including a full list of the
8994 included object files. This switch option is most useful when you want
8995 to see what set of object files are being used in the link step.
8996
8997 @item ^-v -v^/VERBOSE/VERBOSE^
8998 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8999 Very verbose mode. Requests that the compiler operate in verbose mode when
9000 it compiles the binder file, and that the system linker run in verbose mode.
9001
9002 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9003 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9004 @var{exec-name} specifies an alternate name for the generated
9005 executable program. If this switch is omitted, the executable has the same
9006 name as the main unit. For example, @code{gnatlink try.ali} creates
9007 an executable called @file{^try^TRY.EXE^}.
9008
9009 @ifclear vms
9010 @item -b @var{target}
9011 @cindex @option{-b} (@command{gnatlink})
9012 Compile your program to run on @var{target}, which is the name of a
9013 system configuration. You must have a GNAT cross-compiler built if
9014 @var{target} is not the same as your host system.
9015
9016 @item -B@var{dir}
9017 @cindex @option{-B} (@command{gnatlink})
9018 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9019 from @var{dir} instead of the default location. Only use this switch
9020 when multiple versions of the GNAT compiler are available.
9021 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9022 for further details. You would normally use the @option{-b} or
9023 @option{-V} switch instead.
9024
9025 @item --GCC=@var{compiler_name}
9026 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9027 Program used for compiling the binder file. The default is
9028 @command{gcc}. You need to use quotes around @var{compiler_name} if
9029 @code{compiler_name} contains spaces or other separator characters.
9030 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9031 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9032 inserted after your command name. Thus in the above example the compiler
9033 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9034 A limitation of this syntax is that the name and path name of the executable
9035 itself must not include any embedded spaces. If the compiler executable is
9036 different from the default one (gcc or <prefix>-gcc), then the back-end
9037 switches in the ALI file are not used to compile the binder generated source.
9038 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9039 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9040 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9041 is taken into account. However, all the additional switches are also taken
9042 into account. Thus,
9043 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9044 @option{--GCC="bar -x -y -z -t"}.
9045
9046 @item --LINK=@var{name}
9047 @cindex @option{--LINK=} (@command{gnatlink})
9048 @var{name} is the name of the linker to be invoked. This is especially
9049 useful in mixed language programs since languages such as C++ require
9050 their own linker to be used. When this switch is omitted, the default
9051 name for the linker is @command{gcc}. When this switch is used, the
9052 specified linker is called instead of @command{gcc} with exactly the same
9053 parameters that would have been passed to @command{gcc} so if the desired
9054 linker requires different parameters it is necessary to use a wrapper
9055 script that massages the parameters before invoking the real linker. It
9056 may be useful to control the exact invocation by using the verbose
9057 switch.
9058
9059 @end ifclear
9060
9061 @ifset vms
9062 @item /DEBUG=TRACEBACK
9063 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9064 This qualifier causes sufficient information to be included in the
9065 executable file to allow a traceback, but does not include the full
9066 symbol information needed by the debugger.
9067
9068 @item /IDENTIFICATION="<string>"
9069 @code{"<string>"} specifies the string to be stored in the image file
9070 identification field in the image header.
9071 It overrides any pragma @code{Ident} specified string.
9072
9073 @item /NOINHIBIT-EXEC
9074 Generate the executable file even if there are linker warnings.
9075
9076 @item /NOSTART_FILES
9077 Don't link in the object file containing the ``main'' transfer address.
9078 Used when linking with a foreign language main program compiled with an
9079 HP compiler.
9080
9081 @item /STATIC
9082 Prefer linking with object libraries over sharable images, even without
9083 /DEBUG.
9084 @end ifset
9085
9086 @end table
9087
9088 @node The GNAT Make Program gnatmake
9089 @chapter The GNAT Make Program @command{gnatmake}
9090 @findex gnatmake
9091
9092 @menu
9093 * Running gnatmake::
9094 * Switches for gnatmake::
9095 * Mode Switches for gnatmake::
9096 * Notes on the Command Line::
9097 * How gnatmake Works::
9098 * Examples of gnatmake Usage::
9099 @end menu
9100 @noindent
9101 A typical development cycle when working on an Ada program consists of
9102 the following steps:
9103
9104 @enumerate
9105 @item
9106 Edit some sources to fix bugs.
9107
9108 @item
9109 Add enhancements.
9110
9111 @item
9112 Compile all sources affected.
9113
9114 @item
9115 Rebind and relink.
9116
9117 @item
9118 Test.
9119 @end enumerate
9120
9121 @noindent
9122 The third step can be tricky, because not only do the modified files
9123 @cindex Dependency rules
9124 have to be compiled, but any files depending on these files must also be
9125 recompiled. The dependency rules in Ada can be quite complex, especially
9126 in the presence of overloading, @code{use} clauses, generics and inlined
9127 subprograms.
9128
9129 @command{gnatmake} automatically takes care of the third and fourth steps
9130 of this process. It determines which sources need to be compiled,
9131 compiles them, and binds and links the resulting object files.
9132
9133 Unlike some other Ada make programs, the dependencies are always
9134 accurately recomputed from the new sources. The source based approach of
9135 the GNAT compilation model makes this possible. This means that if
9136 changes to the source program cause corresponding changes in
9137 dependencies, they will always be tracked exactly correctly by
9138 @command{gnatmake}.
9139
9140 @node Running gnatmake
9141 @section Running @command{gnatmake}
9142
9143 @noindent
9144 The usual form of the @command{gnatmake} command is
9145
9146 @smallexample
9147 $ gnatmake @ovar{switches} @var{file_name}
9148       @ovar{file_names} @ovar{mode_switches}
9149 @end smallexample
9150
9151 @noindent
9152 The only required argument is one @var{file_name}, which specifies
9153 a compilation unit that is a main program. Several @var{file_names} can be
9154 specified: this will result in several executables being built.
9155 If @code{switches} are present, they can be placed before the first
9156 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9157 If @var{mode_switches} are present, they must always be placed after
9158 the last @var{file_name} and all @code{switches}.
9159
9160 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9161 extension may be omitted from the @var{file_name} arguments. However, if
9162 you are using non-standard extensions, then it is required that the
9163 extension be given. A relative or absolute directory path can be
9164 specified in a @var{file_name}, in which case, the input source file will
9165 be searched for in the specified directory only. Otherwise, the input
9166 source file will first be searched in the directory where
9167 @command{gnatmake} was invoked and if it is not found, it will be search on
9168 the source path of the compiler as described in
9169 @ref{Search Paths and the Run-Time Library (RTL)}.
9170
9171 All @command{gnatmake} output (except when you specify
9172 @option{^-M^/DEPENDENCIES_LIST^}) is to
9173 @file{stderr}. The output produced by the
9174 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9175 @file{stdout}.
9176
9177 @node Switches for gnatmake
9178 @section Switches for @command{gnatmake}
9179
9180 @noindent
9181 You may specify any of the following switches to @command{gnatmake}:
9182
9183 @table @option
9184 @c !sort!
9185
9186 @item --version
9187 @cindex @option{--version} @command{gnatmake}
9188 Display Copyright and version, then exit disregarding all other options.
9189
9190 @item --help
9191 @cindex @option{--help} @command{gnatmake}
9192 If @option{--version} was not used, display usage, then exit disregarding
9193 all other options.
9194
9195 @ifclear vms
9196 @item --GCC=@var{compiler_name}
9197 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9198 Program used for compiling. The default is `@command{gcc}'. You need to use
9199 quotes around @var{compiler_name} if @code{compiler_name} contains
9200 spaces or other separator characters. As an example @option{--GCC="foo -x
9201 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9202 compiler. A limitation of this syntax is that the name and path name of
9203 the executable itself must not include any embedded spaces. Note that
9204 switch @option{-c} is always inserted after your command name. Thus in the
9205 above example the compiler command that will be used by @command{gnatmake}
9206 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9207 used, only the last @var{compiler_name} is taken into account. However,
9208 all the additional switches are also taken into account. Thus,
9209 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9210 @option{--GCC="bar -x -y -z -t"}.
9211
9212 @item --GNATBIND=@var{binder_name}
9213 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9214 Program used for binding. The default is `@code{gnatbind}'. You need to
9215 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9216 or other separator characters. As an example @option{--GNATBIND="bar -x
9217 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9218 binder. Binder switches that are normally appended by @command{gnatmake}
9219 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9220 A limitation of this syntax is that the name and path name of the executable
9221 itself must not include any embedded spaces.
9222
9223 @item --GNATLINK=@var{linker_name}
9224 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9225 Program used for linking. The default is `@command{gnatlink}'. You need to
9226 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9227 or other separator characters. As an example @option{--GNATLINK="lan -x
9228 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9229 linker. Linker switches that are normally appended by @command{gnatmake} to
9230 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9231 A limitation of this syntax is that the name and path name of the executable
9232 itself must not include any embedded spaces.
9233
9234 @end ifclear
9235
9236 @item ^-a^/ALL_FILES^
9237 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9238 Consider all files in the make process, even the GNAT internal system
9239 files (for example, the predefined Ada library files), as well as any
9240 locked files. Locked files are files whose ALI file is write-protected.
9241 By default,
9242 @command{gnatmake} does not check these files,
9243 because the assumption is that the GNAT internal files are properly up
9244 to date, and also that any write protected ALI files have been properly
9245 installed. Note that if there is an installation problem, such that one
9246 of these files is not up to date, it will be properly caught by the
9247 binder.
9248 You may have to specify this switch if you are working on GNAT
9249 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9250 in conjunction with @option{^-f^/FORCE_COMPILE^}
9251 if you need to recompile an entire application,
9252 including run-time files, using special configuration pragmas,
9253 such as a @code{Normalize_Scalars} pragma.
9254
9255 By default
9256 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9257 internal files with
9258 @ifclear vms
9259 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9260 @end ifclear
9261 @ifset vms
9262 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9263 @end ifset
9264
9265 @item ^-b^/ACTIONS=BIND^
9266 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9267 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9268 compilation and binding, but no link.
9269 Can be combined with @option{^-l^/ACTIONS=LINK^}
9270 to do binding and linking. When not combined with
9271 @option{^-c^/ACTIONS=COMPILE^}
9272 all the units in the closure of the main program must have been previously
9273 compiled and must be up to date. The root unit specified by @var{file_name}
9274 may be given without extension, with the source extension or, if no GNAT
9275 Project File is specified, with the ALI file extension.
9276
9277 @item ^-c^/ACTIONS=COMPILE^
9278 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9279 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9280 is also specified. Do not perform linking, except if both
9281 @option{^-b^/ACTIONS=BIND^} and
9282 @option{^-l^/ACTIONS=LINK^} are also specified.
9283 If the root unit specified by @var{file_name} is not a main unit, this is the
9284 default. Otherwise @command{gnatmake} will attempt binding and linking
9285 unless all objects are up to date and the executable is more recent than
9286 the objects.
9287
9288 @item ^-C^/MAPPING^
9289 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9290 Use a temporary mapping file. A mapping file is a way to communicate
9291 to the compiler two mappings: from unit names to file names (without
9292 any directory information) and from file names to path names (with
9293 full directory information). A mapping file can make the compiler's
9294 file searches faster, especially if there are many source directories,
9295 or the sources are read over a slow network connection. If
9296 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9297 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9298 is initially populated based on the project file. If
9299 @option{^-C^/MAPPING^} is used without
9300 @option{^-P^/PROJECT_FILE^},
9301 the mapping file is initially empty. Each invocation of the compiler
9302 will add any newly accessed sources to the mapping file.
9303
9304 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9305 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9306 Use a specific mapping file. The file, specified as a path name (absolute or
9307 relative) by this switch, should already exist, otherwise the switch is
9308 ineffective. The specified mapping file will be communicated to the compiler.
9309 This switch is not compatible with a project file
9310 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9311 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9312
9313 @item ^-d^/DISPLAY_PROGRESS^
9314 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9315 Display progress for each source, up to date or not, as a single line
9316
9317 @smallexample
9318 completed x out of y (zz%)
9319 @end smallexample
9320
9321 If the file needs to be compiled this is displayed after the invocation of
9322 the compiler. These lines are displayed even in quiet output mode.
9323
9324 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9325 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9326 Put all object files and ALI file in directory @var{dir}.
9327 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9328 and ALI files go in the current working directory.
9329
9330 This switch cannot be used when using a project file.
9331
9332 @ifclear vms
9333 @item -eL
9334 @cindex @option{-eL} (@command{gnatmake})
9335 @cindex symbolic links
9336 Follow all symbolic links when processing project files.
9337 This should be used if your project uses symbolic links for files or
9338 directories, but is not needed in other cases.
9339
9340 @cindex naming scheme
9341 This also assumes that no directory matches the naming scheme for files (for
9342 instance that you do not have a directory called "sources.ads" when using the
9343 default GNAT naming scheme).
9344
9345 When you do not have to use this switch (ie by default), gnatmake is able to
9346 save a lot of system calls (several per source file and object file), which
9347 can result in a significant speed up to load and manipulate a project file,
9348 especially when using source files from a remote system.
9349
9350 @end ifclear
9351
9352 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9353 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9354 Output the commands for the compiler, the binder and the linker
9355 on ^standard output^SYS$OUTPUT^,
9356 instead of ^standard error^SYS$ERROR^.
9357
9358 @item ^-f^/FORCE_COMPILE^
9359 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9360 Force recompilations. Recompile all sources, even though some object
9361 files may be up to date, but don't recompile predefined or GNAT internal
9362 files or locked files (files with a write-protected ALI file),
9363 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9364
9365 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9366 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9367 When using project files, if some errors or warnings are detected during
9368 parsing and verbose mode is not in effect (no use of switch
9369 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9370 file, rather than its simple file name.
9371
9372 @item ^-g^/DEBUG^
9373 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9374 Enable debugging. This switch is simply passed to the compiler and to the
9375 linker.
9376
9377 @item ^-i^/IN_PLACE^
9378 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9379 In normal mode, @command{gnatmake} compiles all object files and ALI files
9380 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9381 then instead object files and ALI files that already exist are overwritten
9382 in place. This means that once a large project is organized into separate
9383 directories in the desired manner, then @command{gnatmake} will automatically
9384 maintain and update this organization. If no ALI files are found on the
9385 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9386 the new object and ALI files are created in the
9387 directory containing the source being compiled. If another organization
9388 is desired, where objects and sources are kept in different directories,
9389 a useful technique is to create dummy ALI files in the desired directories.
9390 When detecting such a dummy file, @command{gnatmake} will be forced to
9391 recompile the corresponding source file, and it will be put the resulting
9392 object and ALI files in the directory where it found the dummy file.
9393
9394 @item ^-j^/PROCESSES=^@var{n}
9395 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9396 @cindex Parallel make
9397 Use @var{n} processes to carry out the (re)compilations. On a
9398 multiprocessor machine compilations will occur in parallel. In the
9399 event of compilation errors, messages from various compilations might
9400 get interspersed (but @command{gnatmake} will give you the full ordered
9401 list of failing compiles at the end). If this is problematic, rerun
9402 the make process with n set to 1 to get a clean list of messages.
9403
9404 @item ^-k^/CONTINUE_ON_ERROR^
9405 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9406 Keep going. Continue as much as possible after a compilation error. To
9407 ease the programmer's task in case of compilation errors, the list of
9408 sources for which the compile fails is given when @command{gnatmake}
9409 terminates.
9410
9411 If @command{gnatmake} is invoked with several @file{file_names} and with this
9412 switch, if there are compilation errors when building an executable,
9413 @command{gnatmake} will not attempt to build the following executables.
9414
9415 @item ^-l^/ACTIONS=LINK^
9416 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9417 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9418 and linking. Linking will not be performed if combined with
9419 @option{^-c^/ACTIONS=COMPILE^}
9420 but not with @option{^-b^/ACTIONS=BIND^}.
9421 When not combined with @option{^-b^/ACTIONS=BIND^}
9422 all the units in the closure of the main program must have been previously
9423 compiled and must be up to date, and the main program needs to have been bound.
9424 The root unit specified by @var{file_name}
9425 may be given without extension, with the source extension or, if no GNAT
9426 Project File is specified, with the ALI file extension.
9427
9428 @item ^-m^/MINIMAL_RECOMPILATION^
9429 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9430 Specify that the minimum necessary amount of recompilations
9431 be performed. In this mode @command{gnatmake} ignores time
9432 stamp differences when the only
9433 modifications to a source file consist in adding/removing comments,
9434 empty lines, spaces or tabs. This means that if you have changed the
9435 comments in a source file or have simply reformatted it, using this
9436 switch will tell @command{gnatmake} not to recompile files that depend on it
9437 (provided other sources on which these files depend have undergone no
9438 semantic modifications). Note that the debugging information may be
9439 out of date with respect to the sources if the @option{-m} switch causes
9440 a compilation to be switched, so the use of this switch represents a
9441 trade-off between compilation time and accurate debugging information.
9442
9443 @item ^-M^/DEPENDENCIES_LIST^
9444 @cindex Dependencies, producing list
9445 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9446 Check if all objects are up to date. If they are, output the object
9447 dependences to @file{stdout} in a form that can be directly exploited in
9448 a @file{Makefile}. By default, each source file is prefixed with its
9449 (relative or absolute) directory name. This name is whatever you
9450 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9451 and @option{^-I^/SEARCH^} switches. If you use
9452 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9453 @option{^-q^/QUIET^}
9454 (see below), only the source file names,
9455 without relative paths, are output. If you just specify the
9456 @option{^-M^/DEPENDENCIES_LIST^}
9457 switch, dependencies of the GNAT internal system files are omitted. This
9458 is typically what you want. If you also specify
9459 the @option{^-a^/ALL_FILES^} switch,
9460 dependencies of the GNAT internal files are also listed. Note that
9461 dependencies of the objects in external Ada libraries (see switch
9462 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9463 are never reported.
9464
9465 @item ^-n^/DO_OBJECT_CHECK^
9466 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9467 Don't compile, bind, or link. Checks if all objects are up to date.
9468 If they are not, the full name of the first file that needs to be
9469 recompiled is printed.
9470 Repeated use of this option, followed by compiling the indicated source
9471 file, will eventually result in recompiling all required units.
9472
9473 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9474 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9475 Output executable name. The name of the final executable program will be
9476 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9477 name for the executable will be the name of the input file in appropriate form
9478 for an executable file on the host system.
9479
9480 This switch cannot be used when invoking @command{gnatmake} with several
9481 @file{file_names}.
9482
9483 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9484 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9485 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9486 automatically missing object directories, library directories and exec
9487 directories.
9488
9489 @item ^-P^/PROJECT_FILE=^@var{project}
9490 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9491 Use project file @var{project}. Only one such switch can be used.
9492 @xref{gnatmake and Project Files}.
9493
9494 @item ^-q^/QUIET^
9495 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9496 Quiet. When this flag is not set, the commands carried out by
9497 @command{gnatmake} are displayed.
9498
9499 @item ^-s^/SWITCH_CHECK/^
9500 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9501 Recompile if compiler switches have changed since last compilation.
9502 All compiler switches but -I and -o are taken into account in the
9503 following way:
9504 orders between different ``first letter'' switches are ignored, but
9505 orders between same switches are taken into account. For example,
9506 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9507 is equivalent to @option{-O -g}.
9508
9509 This switch is recommended when Integrated Preprocessing is used.
9510
9511 @item ^-u^/UNIQUE^
9512 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9513 Unique. Recompile at most the main files. It implies -c. Combined with
9514 -f, it is equivalent to calling the compiler directly. Note that using
9515 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9516 (@pxref{Project Files and Main Subprograms}).
9517
9518 @item ^-U^/ALL_PROJECTS^
9519 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9520 When used without a project file or with one or several mains on the command
9521 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9522 on the command line, all sources of all project files are checked and compiled
9523 if not up to date, and libraries are rebuilt, if necessary.
9524
9525 @item ^-v^/REASONS^
9526 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9527 Verbose. Display the reason for all recompilations @command{gnatmake}
9528 decides are necessary, with the highest verbosity level.
9529
9530 @item ^-vl^/LOW_VERBOSITY^
9531 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9532 Verbosity level Low. Display fewer lines than in verbosity Medium.
9533
9534 @item ^-vm^/MEDIUM_VERBOSITY^
9535 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9536 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9537
9538 @item ^-vh^/HIGH_VERBOSITY^
9539 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9540 Verbosity level High. Equivalent to ^-v^/REASONS^.
9541
9542 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9543 Indicate the verbosity of the parsing of GNAT project files.
9544 @xref{Switches Related to Project Files}.
9545
9546 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9547 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9548 Indicate that sources that are not part of any Project File may be compiled.
9549 Normally, when using Project Files, only sources that are part of a Project
9550 File may be compile. When this switch is used, a source outside of all Project
9551 Files may be compiled. The ALI file and the object file will be put in the
9552 object directory of the main Project. The compilation switches used will only
9553 be those specified on the command line. Even when
9554 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9555 command line need to be sources of a project file.
9556
9557 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9558 Indicate that external variable @var{name} has the value @var{value}.
9559 The Project Manager will use this value for occurrences of
9560 @code{external(name)} when parsing the project file.
9561 @xref{Switches Related to Project Files}.
9562
9563 @item ^-z^/NOMAIN^
9564 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9565 No main subprogram. Bind and link the program even if the unit name
9566 given on the command line is a package name. The resulting executable
9567 will execute the elaboration routines of the package and its closure,
9568 then the finalization routines.
9569
9570 @end table
9571
9572 @table @asis
9573 @item @command{gcc} @asis{switches}
9574 @ifclear vms
9575 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9576 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9577 @end ifclear
9578 @ifset vms
9579 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9580 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9581 automatically treated as a compiler switch, and passed on to all
9582 compilations that are carried out.
9583 @end ifset
9584 @end table
9585
9586 @noindent
9587 Source and library search path switches:
9588
9589 @table @option
9590 @c !sort!
9591 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9592 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9593 When looking for source files also look in directory @var{dir}.
9594 The order in which source files search is undertaken is
9595 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9596
9597 @item ^-aL^/SKIP_MISSING=^@var{dir}
9598 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9599 Consider @var{dir} as being an externally provided Ada library.
9600 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9601 files have been located in directory @var{dir}. This allows you to have
9602 missing bodies for the units in @var{dir} and to ignore out of date bodies
9603 for the same units. You still need to specify
9604 the location of the specs for these units by using the switches
9605 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9606 or @option{^-I^/SEARCH=^@var{dir}}.
9607 Note: this switch is provided for compatibility with previous versions
9608 of @command{gnatmake}. The easier method of causing standard libraries
9609 to be excluded from consideration is to write-protect the corresponding
9610 ALI files.
9611
9612 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9613 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9614 When searching for library and object files, look in directory
9615 @var{dir}. The order in which library files are searched is described in
9616 @ref{Search Paths for gnatbind}.
9617
9618 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9619 @cindex Search paths, for @command{gnatmake}
9620 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9621 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9622 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9623
9624 @item ^-I^/SEARCH=^@var{dir}
9625 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9626 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9627 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9628
9629 @item ^-I-^/NOCURRENT_DIRECTORY^
9630 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9631 @cindex Source files, suppressing search
9632 Do not look for source files in the directory containing the source
9633 file named in the command line.
9634 Do not look for ALI or object files in the directory
9635 where @command{gnatmake} was invoked.
9636
9637 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9638 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9639 @cindex Linker libraries
9640 Add directory @var{dir} to the list of directories in which the linker
9641 will search for libraries. This is equivalent to
9642 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9643 @ifclear vms
9644 Furthermore, under Windows, the sources pointed to by the libraries path
9645 set in the registry are not searched for.
9646 @end ifclear
9647
9648 @item -nostdinc
9649 @cindex @option{-nostdinc} (@command{gnatmake})
9650 Do not look for source files in the system default directory.
9651
9652 @item -nostdlib
9653 @cindex @option{-nostdlib} (@command{gnatmake})
9654 Do not look for library files in the system default directory.
9655
9656 @item --RTS=@var{rts-path}
9657 @cindex @option{--RTS} (@command{gnatmake})
9658 Specifies the default location of the runtime library. GNAT looks for the
9659 runtime
9660 in the following directories, and stops as soon as a valid runtime is found
9661 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9662 @file{ada_object_path} present):
9663
9664 @itemize @bullet
9665 @item <current directory>/$rts_path
9666
9667 @item <default-search-dir>/$rts_path
9668
9669 @item <default-search-dir>/rts-$rts_path
9670 @end itemize
9671
9672 @noindent
9673 The selected path is handled like a normal RTS path.
9674
9675 @end table
9676
9677 @node Mode Switches for gnatmake
9678 @section Mode Switches for @command{gnatmake}
9679
9680 @noindent
9681 The mode switches (referred to as @code{mode_switches}) allow the
9682 inclusion of switches that are to be passed to the compiler itself, the
9683 binder or the linker. The effect of a mode switch is to cause all
9684 subsequent switches up to the end of the switch list, or up to the next
9685 mode switch, to be interpreted as switches to be passed on to the
9686 designated component of GNAT.
9687
9688 @table @option
9689 @c !sort!
9690 @item -cargs @var{switches}
9691 @cindex @option{-cargs} (@command{gnatmake})
9692 Compiler switches. Here @var{switches} is a list of switches
9693 that are valid switches for @command{gcc}. They will be passed on to
9694 all compile steps performed by @command{gnatmake}.
9695
9696 @item -bargs @var{switches}
9697 @cindex @option{-bargs} (@command{gnatmake})
9698 Binder switches. Here @var{switches} is a list of switches
9699 that are valid switches for @code{gnatbind}. They will be passed on to
9700 all bind steps performed by @command{gnatmake}.
9701
9702 @item -largs @var{switches}
9703 @cindex @option{-largs} (@command{gnatmake})
9704 Linker switches. Here @var{switches} is a list of switches
9705 that are valid switches for @command{gnatlink}. They will be passed on to
9706 all link steps performed by @command{gnatmake}.
9707
9708 @item -margs @var{switches}
9709 @cindex @option{-margs} (@command{gnatmake})
9710 Make switches. The switches are directly interpreted by @command{gnatmake},
9711 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9712 or @option{-largs}.
9713 @end table
9714
9715 @node Notes on the Command Line
9716 @section Notes on the Command Line
9717
9718 @noindent
9719 This section contains some additional useful notes on the operation
9720 of the @command{gnatmake} command.
9721
9722 @itemize @bullet
9723 @item
9724 @cindex Recompilation, by @command{gnatmake}
9725 If @command{gnatmake} finds no ALI files, it recompiles the main program
9726 and all other units required by the main program.
9727 This means that @command{gnatmake}
9728 can be used for the initial compile, as well as during subsequent steps of
9729 the development cycle.
9730
9731 @item
9732 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9733 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9734 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9735 warning.
9736
9737 @item
9738 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9739 is used to specify both source and
9740 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9741 instead if you just want to specify
9742 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9743 if you want to specify library paths
9744 only.
9745
9746 @item
9747 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9748 This may conveniently be used to exclude standard libraries from
9749 consideration and in particular it means that the use of the
9750 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9751 unless @option{^-a^/ALL_FILES^} is also specified.
9752
9753 @item
9754 @command{gnatmake} has been designed to make the use of Ada libraries
9755 particularly convenient. Assume you have an Ada library organized
9756 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9757 of your Ada compilation units,
9758 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9759 specs of these units, but no bodies. Then to compile a unit
9760 stored in @code{main.adb}, which uses this Ada library you would just type
9761
9762 @smallexample
9763 @ifclear vms
9764 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9765 @end ifclear
9766 @ifset vms
9767 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9768            /SKIP_MISSING=@i{[OBJ_DIR]} main
9769 @end ifset
9770 @end smallexample
9771
9772 @item
9773 Using @command{gnatmake} along with the
9774 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9775 switch provides a mechanism for avoiding unnecessary recompilations. Using
9776 this switch,
9777 you can update the comments/format of your
9778 source files without having to recompile everything. Note, however, that
9779 adding or deleting lines in a source files may render its debugging
9780 info obsolete. If the file in question is a spec, the impact is rather
9781 limited, as that debugging info will only be useful during the
9782 elaboration phase of your program. For bodies the impact can be more
9783 significant. In all events, your debugger will warn you if a source file
9784 is more recent than the corresponding object, and alert you to the fact
9785 that the debugging information may be out of date.
9786 @end itemize
9787
9788 @node How gnatmake Works
9789 @section How @command{gnatmake} Works
9790
9791 @noindent
9792 Generally @command{gnatmake} automatically performs all necessary
9793 recompilations and you don't need to worry about how it works. However,
9794 it may be useful to have some basic understanding of the @command{gnatmake}
9795 approach and in particular to understand how it uses the results of
9796 previous compilations without incorrectly depending on them.
9797
9798 First a definition: an object file is considered @dfn{up to date} if the
9799 corresponding ALI file exists and if all the source files listed in the
9800 dependency section of this ALI file have time stamps matching those in
9801 the ALI file. This means that neither the source file itself nor any
9802 files that it depends on have been modified, and hence there is no need
9803 to recompile this file.
9804
9805 @command{gnatmake} works by first checking if the specified main unit is up
9806 to date. If so, no compilations are required for the main unit. If not,
9807 @command{gnatmake} compiles the main program to build a new ALI file that
9808 reflects the latest sources. Then the ALI file of the main unit is
9809 examined to find all the source files on which the main program depends,
9810 and @command{gnatmake} recursively applies the above procedure on all these
9811 files.
9812
9813 This process ensures that @command{gnatmake} only trusts the dependencies
9814 in an existing ALI file if they are known to be correct. Otherwise it
9815 always recompiles to determine a new, guaranteed accurate set of
9816 dependencies. As a result the program is compiled ``upside down'' from what may
9817 be more familiar as the required order of compilation in some other Ada
9818 systems. In particular, clients are compiled before the units on which
9819 they depend. The ability of GNAT to compile in any order is critical in
9820 allowing an order of compilation to be chosen that guarantees that
9821 @command{gnatmake} will recompute a correct set of new dependencies if
9822 necessary.
9823
9824 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9825 imported by several of the executables, it will be recompiled at most once.
9826
9827 Note: when using non-standard naming conventions
9828 (@pxref{Using Other File Names}), changing through a configuration pragmas
9829 file the version of a source and invoking @command{gnatmake} to recompile may
9830 have no effect, if the previous version of the source is still accessible
9831 by @command{gnatmake}. It may be necessary to use the switch
9832 ^-f^/FORCE_COMPILE^.
9833
9834 @node Examples of gnatmake Usage
9835 @section Examples of @command{gnatmake} Usage
9836
9837 @table @code
9838 @item gnatmake hello.adb
9839 Compile all files necessary to bind and link the main program
9840 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9841 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9842
9843 @item gnatmake main1 main2 main3
9844 Compile all files necessary to bind and link the main programs
9845 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9846 (containing unit @code{Main2}) and @file{main3.adb}
9847 (containing unit @code{Main3}) and bind and link the resulting object files
9848 to generate three executable files @file{^main1^MAIN1.EXE^},
9849 @file{^main2^MAIN2.EXE^}
9850 and @file{^main3^MAIN3.EXE^}.
9851
9852 @ifclear vms
9853 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9854 @end ifclear
9855
9856 @ifset vms
9857 @item gnatmake Main_Unit /QUIET
9858 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9859 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9860 @end ifset
9861 Compile all files necessary to bind and link the main program unit
9862 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9863 be done with optimization level 2 and the order of elaboration will be
9864 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9865 displaying commands it is executing.
9866 @end table
9867
9868 @c *************************
9869 @node Improving Performance
9870 @chapter Improving Performance
9871 @cindex Improving performance
9872
9873 @noindent
9874 This chapter presents several topics related to program performance.
9875 It first describes some of the tradeoffs that need to be considered
9876 and some of the techniques for making your program run faster.
9877 It then documents the @command{gnatelim} tool and unused subprogram/data
9878 elimination feature, which can reduce the size of program executables.
9879
9880 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9881 driver (see @ref{The GNAT Driver and Project Files}).
9882
9883 @ifnottex
9884 @menu
9885 * Performance Considerations::
9886 * Text_IO Suggestions::
9887 * Reducing Size of Ada Executables with gnatelim::
9888 * Reducing Size of Executables with unused subprogram/data elimination::
9889 @end menu
9890 @end ifnottex
9891
9892 @c *****************************
9893 @node Performance Considerations
9894 @section Performance Considerations
9895
9896 @noindent
9897 The GNAT system provides a number of options that allow a trade-off
9898 between
9899
9900 @itemize @bullet
9901 @item
9902 performance of the generated code
9903
9904 @item
9905 speed of compilation
9906
9907 @item
9908 minimization of dependences and recompilation
9909
9910 @item
9911 the degree of run-time checking.
9912 @end itemize
9913
9914 @noindent
9915 The defaults (if no options are selected) aim at improving the speed
9916 of compilation and minimizing dependences, at the expense of performance
9917 of the generated code:
9918
9919 @itemize @bullet
9920 @item
9921 no optimization
9922
9923 @item
9924 no inlining of subprogram calls
9925
9926 @item
9927 all run-time checks enabled except overflow and elaboration checks
9928 @end itemize
9929
9930 @noindent
9931 These options are suitable for most program development purposes. This
9932 chapter describes how you can modify these choices, and also provides
9933 some guidelines on debugging optimized code.
9934
9935 @menu
9936 * Controlling Run-Time Checks::
9937 * Use of Restrictions::
9938 * Optimization Levels::
9939 * Debugging Optimized Code::
9940 * Inlining of Subprograms::
9941 * Other Optimization Switches::
9942 * Optimization and Strict Aliasing::
9943
9944 @ifset vms
9945 * Coverage Analysis::
9946 @end ifset
9947 @end menu
9948
9949 @node Controlling Run-Time Checks
9950 @subsection Controlling Run-Time Checks
9951
9952 @noindent
9953 By default, GNAT generates all run-time checks, except integer overflow
9954 checks, stack overflow checks, and checks for access before elaboration on
9955 subprogram calls. The latter are not required in default mode, because all
9956 necessary checking is done at compile time.
9957 @cindex @option{-gnatp} (@command{gcc})
9958 @cindex @option{-gnato} (@command{gcc})
9959 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9960 be modified. @xref{Run-Time Checks}.
9961
9962 Our experience is that the default is suitable for most development
9963 purposes.
9964
9965 We treat integer overflow specially because these
9966 are quite expensive and in our experience are not as important as other
9967 run-time checks in the development process. Note that division by zero
9968 is not considered an overflow check, and divide by zero checks are
9969 generated where required by default.
9970
9971 Elaboration checks are off by default, and also not needed by default, since
9972 GNAT uses a static elaboration analysis approach that avoids the need for
9973 run-time checking. This manual contains a full chapter discussing the issue
9974 of elaboration checks, and if the default is not satisfactory for your use,
9975 you should read this chapter.
9976
9977 For validity checks, the minimal checks required by the Ada Reference
9978 Manual (for case statements and assignments to array elements) are on
9979 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9980 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9981 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9982 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9983 are also suppressed entirely if @option{-gnatp} is used.
9984
9985 @cindex Overflow checks
9986 @cindex Checks, overflow
9987 @findex Suppress
9988 @findex Unsuppress
9989 @cindex pragma Suppress
9990 @cindex pragma Unsuppress
9991 Note that the setting of the switches controls the default setting of
9992 the checks. They may be modified using either @code{pragma Suppress} (to
9993 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9994 checks) in the program source.
9995
9996 @node Use of Restrictions
9997 @subsection Use of Restrictions
9998
9999 @noindent
10000 The use of pragma Restrictions allows you to control which features are
10001 permitted in your program. Apart from the obvious point that if you avoid
10002 relatively expensive features like finalization (enforceable by the use
10003 of pragma Restrictions (No_Finalization), the use of this pragma does not
10004 affect the generated code in most cases.
10005
10006 One notable exception to this rule is that the possibility of task abort
10007 results in some distributed overhead, particularly if finalization or
10008 exception handlers are used. The reason is that certain sections of code
10009 have to be marked as non-abortable.
10010
10011 If you use neither the @code{abort} statement, nor asynchronous transfer
10012 of control (@code{select @dots{} then abort}), then this distributed overhead
10013 is removed, which may have a general positive effect in improving
10014 overall performance.  Especially code involving frequent use of tasking
10015 constructs and controlled types will show much improved performance.
10016 The relevant restrictions pragmas are
10017
10018 @smallexample @c ada
10019    pragma Restrictions (No_Abort_Statements);
10020    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10021 @end smallexample
10022
10023 @noindent
10024 It is recommended that these restriction pragmas be used if possible. Note
10025 that this also means that you can write code without worrying about the
10026 possibility of an immediate abort at any point.
10027
10028 @node Optimization Levels
10029 @subsection Optimization Levels
10030 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10031
10032 @noindent
10033 Without any optimization ^option,^qualifier,^
10034 the compiler's goal is to reduce the cost of
10035 compilation and to make debugging produce the expected results.
10036 Statements are independent: if you stop the program with a breakpoint between
10037 statements, you can then assign a new value to any variable or change
10038 the program counter to any other statement in the subprogram and get exactly
10039 the results you would expect from the source code.
10040
10041 Turning on optimization makes the compiler attempt to improve the
10042 performance and/or code size at the expense of compilation time and
10043 possibly the ability to debug the program.
10044
10045 If you use multiple
10046 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10047 the last such option is the one that is effective.
10048
10049 @noindent
10050 The default is optimization off. This results in the fastest compile
10051 times, but GNAT makes absolutely no attempt to optimize, and the
10052 generated programs are considerably larger and slower than when
10053 optimization is enabled. You can use the
10054 @ifclear vms
10055 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10056 @option{-O2}, @option{-O3}, and @option{-Os})
10057 @end ifclear
10058 @ifset vms
10059 @code{OPTIMIZE} qualifier
10060 @end ifset
10061 to @command{gcc} to control the optimization level:
10062
10063 @table @option
10064 @item ^-O0^/OPTIMIZE=NONE^
10065 No optimization (the default);
10066 generates unoptimized code but has
10067 the fastest compilation time.
10068
10069 Note that many other compilers do fairly extensive optimization
10070 even if ``no optimization'' is specified. With gcc, it is
10071 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10072 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10073 really does mean no optimization at all. This difference between
10074 gcc and other compilers should be kept in mind when doing
10075 performance comparisons.
10076
10077 @item ^-O1^/OPTIMIZE=SOME^
10078 Moderate optimization;
10079 optimizes reasonably well but does not
10080 degrade compilation time significantly.
10081
10082 @item ^-O2^/OPTIMIZE=ALL^
10083 @ifset vms
10084 @itemx /OPTIMIZE=DEVELOPMENT
10085 @end ifset
10086 Full optimization;
10087 generates highly optimized code and has
10088 the slowest compilation time.
10089
10090 @item ^-O3^/OPTIMIZE=INLINING^
10091 Full optimization as in @option{-O2},
10092 and also attempts automatic inlining of small
10093 subprograms within a unit (@pxref{Inlining of Subprograms}).
10094
10095 @item ^-Os^/OPTIMIZE=SPACE^
10096 Optimize space usage of resulting program.
10097 @end table
10098
10099 @noindent
10100 Higher optimization levels perform more global transformations on the
10101 program and apply more expensive analysis algorithms in order to generate
10102 faster and more compact code. The price in compilation time, and the
10103 resulting improvement in execution time,
10104 both depend on the particular application and the hardware environment.
10105 You should experiment to find the best level for your application.
10106
10107 Since the precise set of optimizations done at each level will vary from
10108 release to release (and sometime from target to target), it is best to think
10109 of the optimization settings in general terms.
10110 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10111 the GNU Compiler Collection (GCC)}, for details about
10112 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10113 individually enable or disable specific optimizations.
10114
10115 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10116 been tested extensively at all optimization levels. There are some bugs
10117 which appear only with optimization turned on, but there have also been
10118 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10119 level of optimization does not improve the reliability of the code
10120 generator, which in practice is highly reliable at all optimization
10121 levels.
10122
10123 Note regarding the use of @option{-O3}: The use of this optimization level
10124 is generally discouraged with GNAT, since it often results in larger
10125 executables which run more slowly. See further discussion of this point
10126 in @ref{Inlining of Subprograms}.
10127
10128 @node Debugging Optimized Code
10129 @subsection Debugging Optimized Code
10130 @cindex Debugging optimized code
10131 @cindex Optimization and debugging
10132
10133 @noindent
10134 Although it is possible to do a reasonable amount of debugging at
10135 @ifclear vms
10136 nonzero optimization levels,
10137 the higher the level the more likely that
10138 @end ifclear
10139 @ifset vms
10140 @option{/OPTIMIZE} settings other than @code{NONE},
10141 such settings will make it more likely that
10142 @end ifset
10143 source-level constructs will have been eliminated by optimization.
10144 For example, if a loop is strength-reduced, the loop
10145 control variable may be completely eliminated and thus cannot be
10146 displayed in the debugger.
10147 This can only happen at @option{-O2} or @option{-O3}.
10148 Explicit temporary variables that you code might be eliminated at
10149 ^level^setting^ @option{-O1} or higher.
10150
10151 The use of the @option{^-g^/DEBUG^} switch,
10152 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10153 which is needed for source-level debugging,
10154 affects the size of the program executable on disk,
10155 and indeed the debugging information can be quite large.
10156 However, it has no effect on the generated code (and thus does not
10157 degrade performance)
10158
10159 Since the compiler generates debugging tables for a compilation unit before
10160 it performs optimizations, the optimizing transformations may invalidate some
10161 of the debugging data.  You therefore need to anticipate certain
10162 anomalous situations that may arise while debugging optimized code.
10163 These are the most common cases:
10164
10165 @enumerate
10166 @item
10167 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10168 commands show
10169 the PC bouncing back and forth in the code.  This may result from any of
10170 the following optimizations:
10171
10172 @itemize @bullet
10173 @item
10174 @i{Common subexpression elimination:} using a single instance of code for a
10175 quantity that the source computes several times.  As a result you
10176 may not be able to stop on what looks like a statement.
10177
10178 @item
10179 @i{Invariant code motion:} moving an expression that does not change within a
10180 loop, to the beginning of the loop.
10181
10182 @item
10183 @i{Instruction scheduling:} moving instructions so as to
10184 overlap loads and stores (typically) with other code, or in
10185 general to move computations of values closer to their uses. Often
10186 this causes you to pass an assignment statement without the assignment
10187 happening and then later bounce back to the statement when the
10188 value is actually needed.  Placing a breakpoint on a line of code
10189 and then stepping over it may, therefore, not always cause all the
10190 expected side-effects.
10191 @end itemize
10192
10193 @item
10194 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10195 two identical pieces of code are merged and the program counter suddenly
10196 jumps to a statement that is not supposed to be executed, simply because
10197 it (and the code following) translates to the same thing as the code
10198 that @emph{was} supposed to be executed.  This effect is typically seen in
10199 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10200 a @code{break} in a C @code{^switch^switch^} statement.
10201
10202 @item
10203 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10204 There are various reasons for this effect:
10205
10206 @itemize @bullet
10207 @item
10208 In a subprogram prologue, a parameter may not yet have been moved to its
10209 ``home''.
10210
10211 @item
10212 A variable may be dead, and its register re-used.  This is
10213 probably the most common cause.
10214
10215 @item
10216 As mentioned above, the assignment of a value to a variable may
10217 have been moved.
10218
10219 @item
10220 A variable may be eliminated entirely by value propagation or
10221 other means.  In this case, GCC may incorrectly generate debugging
10222 information for the variable
10223 @end itemize
10224
10225 @noindent
10226 In general, when an unexpected value appears for a local variable or parameter
10227 you should first ascertain if that value was actually computed by
10228 your program, as opposed to being incorrectly reported by the debugger.
10229 Record fields or
10230 array elements in an object designated by an access value
10231 are generally less of a problem, once you have ascertained that the access
10232 value is sensible.
10233 Typically, this means checking variables in the preceding code and in the
10234 calling subprogram to verify that the value observed is explainable from other
10235 values (one must apply the procedure recursively to those
10236 other values); or re-running the code and stopping a little earlier
10237 (perhaps before the call) and stepping to better see how the variable obtained
10238 the value in question; or continuing to step @emph{from} the point of the
10239 strange value to see if code motion had simply moved the variable's
10240 assignments later.
10241 @end enumerate
10242
10243 @noindent
10244 In light of such anomalies, a recommended technique is to use @option{-O0}
10245 early in the software development cycle, when extensive debugging capabilities
10246 are most needed, and then move to @option{-O1} and later @option{-O2} as
10247 the debugger becomes less critical.
10248 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10249 a release management issue.
10250 @ifclear vms
10251 Note that if you use @option{-g} you can then use the @command{strip} program
10252 on the resulting executable,
10253 which removes both debugging information and global symbols.
10254 @end ifclear
10255
10256 @node Inlining of Subprograms
10257 @subsection Inlining of Subprograms
10258
10259 @noindent
10260 A call to a subprogram in the current unit is inlined if all the
10261 following conditions are met:
10262
10263 @itemize @bullet
10264 @item
10265 The optimization level is at least @option{-O1}.
10266
10267 @item
10268 The called subprogram is suitable for inlining: It must be small enough
10269 and not contain something that @command{gcc} cannot support in inlined
10270 subprograms.
10271
10272 @item
10273 @cindex pragma Inline
10274 @findex Inline
10275 Either @code{pragma Inline} applies to the subprogram, or it is local
10276 to the unit and called once from within it, or it is small and automatic
10277 inlining (optimization level @option{-O3}) is specified.
10278 @end itemize
10279
10280 @noindent
10281 Calls to subprograms in @code{with}'ed units are normally not inlined.
10282 To achieve actual inlining (that is, replacement of the call by the code
10283 in the body of the subprogram), the following conditions must all be true.
10284
10285 @itemize @bullet
10286 @item
10287 The optimization level is at least @option{-O1}.
10288
10289 @item
10290 The called subprogram is suitable for inlining: It must be small enough
10291 and not contain something that @command{gcc} cannot support in inlined
10292 subprograms.
10293
10294 @item
10295 The call appears in a body (not in a package spec).
10296
10297 @item
10298 There is a @code{pragma Inline} for the subprogram.
10299
10300 @item
10301 @cindex @option{-gnatn} (@command{gcc})
10302 The @option{^-gnatn^/INLINE^} switch
10303 is used in the @command{gcc} command line
10304 @end itemize
10305
10306 Even if all these conditions are met, it may not be possible for
10307 the compiler to inline the call, due to the length of the body,
10308 or features in the body that make it impossible for the compiler
10309 to do the inlining.
10310
10311 Note that specifying the @option{-gnatn} switch causes additional
10312 compilation dependencies. Consider the following:
10313
10314 @smallexample @c ada
10315 @cartouche
10316 package R is
10317    procedure Q;
10318    pragma Inline (Q);
10319 end R;
10320 package body R is
10321    @dots{}
10322 end R;
10323
10324 with R;
10325 procedure Main is
10326 begin
10327    @dots{}
10328    R.Q;
10329 end Main;
10330 @end cartouche
10331 @end smallexample
10332
10333 @noindent
10334 With the default behavior (no @option{-gnatn} switch specified), the
10335 compilation of the @code{Main} procedure depends only on its own source,
10336 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10337 means that editing the body of @code{R} does not require recompiling
10338 @code{Main}.
10339
10340 On the other hand, the call @code{R.Q} is not inlined under these
10341 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10342 is compiled, the call will be inlined if the body of @code{Q} is small
10343 enough, but now @code{Main} depends on the body of @code{R} in
10344 @file{r.adb} as well as on the spec. This means that if this body is edited,
10345 the main program must be recompiled. Note that this extra dependency
10346 occurs whether or not the call is in fact inlined by @command{gcc}.
10347
10348 The use of front end inlining with @option{-gnatN} generates similar
10349 additional dependencies.
10350
10351 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10352 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10353 can be used to prevent
10354 all inlining. This switch overrides all other conditions and ensures
10355 that no inlining occurs. The extra dependences resulting from
10356 @option{-gnatn} will still be active, even if
10357 this switch is used to suppress the resulting inlining actions.
10358
10359 @cindex @option{-fno-inline-functions} (@command{gcc})
10360 Note: The @option{-fno-inline-functions} switch can be used to prevent
10361 automatic inlining of small subprograms if @option{-O3} is used.
10362
10363 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10364 Note: The @option{-fno-inline-functions-called-once} switch
10365 can be used to prevent inlining of subprograms local to the unit
10366 and called once from within it if @option{-O1} is used.
10367
10368 Note regarding the use of @option{-O3}: There is no difference in inlining
10369 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10370 pragma @code{Inline} assuming the use of @option{-gnatn}
10371 or @option{-gnatN} (the switches that activate inlining). If you have used
10372 pragma @code{Inline} in appropriate cases, then it is usually much better
10373 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10374 in this case only has the effect of inlining subprograms you did not
10375 think should be inlined. We often find that the use of @option{-O3} slows
10376 down code by performing excessive inlining, leading to increased instruction
10377 cache pressure from the increased code size. So the bottom line here is
10378 that you should not automatically assume that @option{-O3} is better than
10379 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10380 it actually improves performance.
10381
10382 @node Other Optimization Switches
10383 @subsection Other Optimization Switches
10384 @cindex Optimization Switches
10385
10386 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10387 @command{gcc} optimization switches are potentially usable. These switches
10388 have not been extensively tested with GNAT but can generally be expected
10389 to work. Examples of switches in this category are
10390 @option{-funroll-loops} and
10391 the various target-specific @option{-m} options (in particular, it has been
10392 observed that @option{-march=pentium4} can significantly improve performance
10393 on appropriate machines). For full details of these switches, see
10394 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10395 the GNU Compiler Collection (GCC)}.
10396
10397 @node Optimization and Strict Aliasing
10398 @subsection Optimization and Strict Aliasing
10399 @cindex Aliasing
10400 @cindex Strict Aliasing
10401 @cindex No_Strict_Aliasing
10402
10403 @noindent
10404 The strong typing capabilities of Ada allow an optimizer to generate
10405 efficient code in situations where other languages would be forced to
10406 make worst case assumptions preventing such optimizations. Consider
10407 the following example:
10408
10409 @smallexample @c ada
10410 @cartouche
10411 procedure R is
10412    type Int1 is new Integer;
10413    type Int2 is new Integer;
10414    type Int1A is access Int1;
10415    type Int2A is access Int2;
10416    Int1V : Int1A;
10417    Int2V : Int2A;
10418    @dots{}
10419
10420 begin
10421    @dots{}
10422    for J in Data'Range loop
10423       if Data (J) = Int1V.all then
10424          Int2V.all := Int2V.all + 1;
10425       end if;
10426    end loop;
10427    @dots{}
10428 end R;
10429 @end cartouche
10430 @end smallexample
10431
10432 @noindent
10433 In this example, since the variable @code{Int1V} can only access objects
10434 of type @code{Int1}, and @code{Int2V} can only access objects of type
10435 @code{Int2}, there is no possibility that the assignment to
10436 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10437 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10438 for all iterations of the loop and avoid the extra memory reference
10439 required to dereference it each time through the loop.
10440
10441 This kind of optimization, called strict aliasing analysis, is
10442 triggered by specifying an optimization level of @option{-O2} or
10443 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10444 when access values are involved.
10445
10446 However, although this optimization is always correct in terms of
10447 the formal semantics of the Ada Reference Manual, difficulties can
10448 arise if features like @code{Unchecked_Conversion} are used to break
10449 the typing system. Consider the following complete program example:
10450
10451 @smallexample @c ada
10452 @cartouche
10453 package p1 is
10454    type int1 is new integer;
10455    type int2 is new integer;
10456    type a1 is access int1;
10457    type a2 is access int2;
10458 end p1;
10459
10460 with p1; use p1;
10461 package p2 is
10462    function to_a2 (Input : a1) return a2;
10463 end p2;
10464
10465 with Unchecked_Conversion;
10466 package body p2 is
10467    function to_a2 (Input : a1) return a2 is
10468       function to_a2u is
10469         new Unchecked_Conversion (a1, a2);
10470    begin
10471       return to_a2u (Input);
10472    end to_a2;
10473 end p2;
10474
10475 with p2; use p2;
10476 with p1; use p1;
10477 with Text_IO; use Text_IO;
10478 procedure m is
10479    v1 : a1 := new int1;
10480    v2 : a2 := to_a2 (v1);
10481 begin
10482    v1.all := 1;
10483    v2.all := 0;
10484    put_line (int1'image (v1.all));
10485 end;
10486 @end cartouche
10487 @end smallexample
10488
10489 @noindent
10490 This program prints out 0 in @option{-O0} or @option{-O1}
10491 mode, but it prints out 1 in @option{-O2} mode. That's
10492 because in strict aliasing mode, the compiler can and
10493 does assume that the assignment to @code{v2.all} could not
10494 affect the value of @code{v1.all}, since different types
10495 are involved.
10496
10497 This behavior is not a case of non-conformance with the standard, since
10498 the Ada RM specifies that an unchecked conversion where the resulting
10499 bit pattern is not a correct value of the target type can result in an
10500 abnormal value and attempting to reference an abnormal value makes the
10501 execution of a program erroneous.  That's the case here since the result
10502 does not point to an object of type @code{int2}.  This means that the
10503 effect is entirely unpredictable.
10504
10505 However, although that explanation may satisfy a language
10506 lawyer, in practice an applications programmer expects an
10507 unchecked conversion involving pointers to create true
10508 aliases and the behavior of printing 1 seems plain wrong.
10509 In this case, the strict aliasing optimization is unwelcome.
10510
10511 Indeed the compiler recognizes this possibility, and the
10512 unchecked conversion generates a warning:
10513
10514 @smallexample
10515 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10516 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10517 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10518 @end smallexample
10519
10520 @noindent
10521 Unfortunately the problem is recognized when compiling the body of
10522 package @code{p2}, but the actual "bad" code is generated while
10523 compiling the body of @code{m} and this latter compilation does not see
10524 the suspicious @code{Unchecked_Conversion}.
10525
10526 As implied by the warning message, there are approaches you can use to
10527 avoid the unwanted strict aliasing optimization in a case like this.
10528
10529 One possibility is to simply avoid the use of @option{-O2}, but
10530 that is a bit drastic, since it throws away a number of useful
10531 optimizations that do not involve strict aliasing assumptions.
10532
10533 A less drastic approach is to compile the program using the
10534 option @option{-fno-strict-aliasing}. Actually it is only the
10535 unit containing the dereferencing of the suspicious pointer
10536 that needs to be compiled. So in this case, if we compile
10537 unit @code{m} with this switch, then we get the expected
10538 value of zero printed. Analyzing which units might need
10539 the switch can be painful, so a more reasonable approach
10540 is to compile the entire program with options @option{-O2}
10541 and @option{-fno-strict-aliasing}. If the performance is
10542 satisfactory with this combination of options, then the
10543 advantage is that the entire issue of possible "wrong"
10544 optimization due to strict aliasing is avoided.
10545
10546 To avoid the use of compiler switches, the configuration
10547 pragma @code{No_Strict_Aliasing} with no parameters may be
10548 used to specify that for all access types, the strict
10549 aliasing optimization should be suppressed.
10550
10551 However, these approaches are still overkill, in that they causes
10552 all manipulations of all access values to be deoptimized. A more
10553 refined approach is to concentrate attention on the specific
10554 access type identified as problematic.
10555
10556 First, if a careful analysis of uses of the pointer shows
10557 that there are no possible problematic references, then
10558 the warning can be suppressed by bracketing the
10559 instantiation of @code{Unchecked_Conversion} to turn
10560 the warning off:
10561
10562 @smallexample @c ada
10563    pragma Warnings (Off);
10564    function to_a2u is
10565      new Unchecked_Conversion (a1, a2);
10566    pragma Warnings (On);
10567 @end smallexample
10568
10569 @noindent
10570 Of course that approach is not appropriate for this particular
10571 example, since indeed there is a problematic reference. In this
10572 case we can take one of two other approaches.
10573
10574 The first possibility is to move the instantiation of unchecked
10575 conversion to the unit in which the type is declared. In
10576 this example, we would move the instantiation of
10577 @code{Unchecked_Conversion} from the body of package
10578 @code{p2} to the spec of package @code{p1}. Now the
10579 warning disappears. That's because any use of the
10580 access type knows there is a suspicious unchecked
10581 conversion, and the strict aliasing optimization
10582 is automatically suppressed for the type.
10583
10584 If it is not practical to move the unchecked conversion to the same unit
10585 in which the destination access type is declared (perhaps because the
10586 source type is not visible in that unit), you may use pragma
10587 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10588 same declarative sequence as the declaration of the access type:
10589
10590 @smallexample @c ada
10591    type a2 is access int2;
10592    pragma No_Strict_Aliasing (a2);
10593 @end smallexample
10594
10595 @noindent
10596 Here again, the compiler now knows that the strict aliasing optimization
10597 should be suppressed for any reference to type @code{a2} and the
10598 expected behavior is obtained.
10599
10600 Finally, note that although the compiler can generate warnings for
10601 simple cases of unchecked conversions, there are tricker and more
10602 indirect ways of creating type incorrect aliases which the compiler
10603 cannot detect. Examples are the use of address overlays and unchecked
10604 conversions involving composite types containing access types as
10605 components. In such cases, no warnings are generated, but there can
10606 still be aliasing problems. One safe coding practice is to forbid the
10607 use of address clauses for type overlaying, and to allow unchecked
10608 conversion only for primitive types. This is not really a significant
10609 restriction since any possible desired effect can be achieved by
10610 unchecked conversion of access values.
10611
10612 The aliasing analysis done in strict aliasing mode can certainly
10613 have significant benefits. We have seen cases of large scale
10614 application code where the time is increased by up to 5% by turning
10615 this optimization off. If you have code that includes significant
10616 usage of unchecked conversion, you might want to just stick with
10617 @option{-O1} and avoid the entire issue. If you get adequate
10618 performance at this level of optimization level, that's probably
10619 the safest approach. If tests show that you really need higher
10620 levels of optimization, then you can experiment with @option{-O2}
10621 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10622 has on size and speed of the code. If you really need to use
10623 @option{-O2} with strict aliasing in effect, then you should
10624 review any uses of unchecked conversion of access types,
10625 particularly if you are getting the warnings described above.
10626
10627 @ifset vms
10628 @node Coverage Analysis
10629 @subsection Coverage Analysis
10630
10631 @noindent
10632 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10633 the user to determine the distribution of execution time across a program,
10634 @pxref{Profiling} for details of usage.
10635 @end ifset
10636
10637
10638 @node Text_IO Suggestions
10639 @section @code{Text_IO} Suggestions
10640 @cindex @code{Text_IO} and performance
10641
10642 @noindent
10643 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10644 the requirement of maintaining page and line counts. If performance
10645 is critical, a recommendation is to use @code{Stream_IO} instead of
10646 @code{Text_IO} for volume output, since this package has less overhead.
10647
10648 If @code{Text_IO} must be used, note that by default output to the standard
10649 output and standard error files is unbuffered (this provides better
10650 behavior when output statements are used for debugging, or if the
10651 progress of a program is observed by tracking the output, e.g. by
10652 using the Unix @command{tail -f} command to watch redirected output.
10653
10654 If you are generating large volumes of output with @code{Text_IO} and
10655 performance is an important factor, use a designated file instead
10656 of the standard output file, or change the standard output file to
10657 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10658
10659
10660
10661 @node Reducing Size of Ada Executables with gnatelim
10662 @section Reducing Size of Ada Executables with @code{gnatelim}
10663 @findex gnatelim
10664
10665 @noindent
10666 This section describes @command{gnatelim}, a tool which detects unused
10667 subprograms and helps the compiler to create a smaller executable for your
10668 program.
10669
10670 @menu
10671 * About gnatelim::
10672 * Running gnatelim::
10673 * Correcting the List of Eliminate Pragmas::
10674 * Making Your Executables Smaller::
10675 * Summary of the gnatelim Usage Cycle::
10676 @end menu
10677
10678 @node About gnatelim
10679 @subsection About @code{gnatelim}
10680
10681 @noindent
10682 When a program shares a set of Ada
10683 packages with other programs, it may happen that this program uses
10684 only a fraction of the subprograms defined in these packages. The code
10685 created for these unused subprograms increases the size of the executable.
10686
10687 @code{gnatelim} tracks unused subprograms in an Ada program and
10688 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10689 subprograms that are declared but never called. By placing the list of
10690 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10691 recompiling your program, you may decrease the size of its executable,
10692 because the compiler will not generate the code for 'eliminated' subprograms.
10693 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10694 information about this pragma.
10695
10696 @code{gnatelim} needs as its input data the name of the main subprogram
10697 and a bind file for a main subprogram.
10698
10699 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10700 the main subprogram. @code{gnatelim} can work with both Ada and C
10701 bind files; when both are present, it uses the Ada bind file.
10702 The following commands will build the program and create the bind file:
10703
10704 @smallexample
10705 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10706 $ gnatbind main_prog
10707 @end smallexample
10708
10709 Note that @code{gnatelim} needs neither object nor ALI files.
10710
10711 @node Running gnatelim
10712 @subsection Running @code{gnatelim}
10713
10714 @noindent
10715 @code{gnatelim} has the following command-line interface:
10716
10717 @smallexample
10718 $ gnatelim @ovar{options} name
10719 @end smallexample
10720
10721 @noindent
10722 @code{name} should be a name of a source file that contains the main subprogram
10723 of a program (partition).
10724
10725 @code{gnatelim} has the following switches:
10726
10727 @table @option
10728 @c !sort!
10729 @item ^-q^/QUIET^
10730 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10731 Quiet mode: by default @code{gnatelim} outputs to the standard error
10732 stream the number of program units left to be processed. This option turns
10733 this trace off.
10734
10735 @item ^-v^/VERBOSE^
10736 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10737 Verbose mode: @code{gnatelim} version information is printed as Ada
10738 comments to the standard output stream. Also, in addition to the number of
10739 program units left @code{gnatelim} will output the name of the current unit
10740 being processed.
10741
10742 @item ^-a^/ALL^
10743 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10744 Also look for subprograms from the GNAT run time that can be eliminated. Note
10745 that when @file{gnat.adc} is produced using this switch, the entire program
10746 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10747
10748 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10749 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10750 When looking for source files also look in directory @var{dir}. Specifying
10751 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10752 sources in the current directory.
10753
10754 @item ^-b^/BIND_FILE=^@var{bind_file}
10755 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10756 Specifies @var{bind_file} as the bind file to process. If not set, the name
10757 of the bind file is computed from the full expanded Ada name
10758 of a main subprogram.
10759
10760 @item ^-C^/CONFIG_FILE=^@var{config_file}
10761 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10762 Specifies a file @var{config_file} that contains configuration pragmas. The
10763 file must be specified with full path.
10764
10765 @item ^--GCC^/COMPILER^=@var{compiler_name}
10766 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10767 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10768 available on the path.
10769
10770 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10771 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10772 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10773 available on the path.
10774 @end table
10775
10776 @noindent
10777 @code{gnatelim} sends its output to the standard output stream, and all the
10778 tracing and debug information is sent to the standard error stream.
10779 In order to produce a proper GNAT configuration file
10780 @file{gnat.adc}, redirection must be used:
10781
10782 @smallexample
10783 @ifset vms
10784 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10785 @end ifset
10786 @ifclear vms
10787 $ gnatelim main_prog.adb > gnat.adc
10788 @end ifclear
10789 @end smallexample
10790
10791 @ifclear vms
10792 @noindent
10793 or
10794
10795 @smallexample
10796 $ gnatelim main_prog.adb >> gnat.adc
10797 @end smallexample
10798
10799 @noindent
10800 in order to append the @code{gnatelim} output to the existing contents of
10801 @file{gnat.adc}.
10802 @end ifclear
10803
10804 @node Correcting the List of Eliminate Pragmas
10805 @subsection Correcting the List of Eliminate Pragmas
10806
10807 @noindent
10808 In some rare cases @code{gnatelim} may try to eliminate
10809 subprograms that are actually called in the program. In this case, the
10810 compiler will generate an error message of the form:
10811
10812 @smallexample
10813 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10814 @end smallexample
10815
10816 @noindent
10817 You will need to manually remove the wrong @code{Eliminate} pragmas from
10818 the @file{gnat.adc} file. You should recompile your program
10819 from scratch after that, because you need a consistent @file{gnat.adc} file
10820 during the entire compilation.
10821
10822 @node Making Your Executables Smaller
10823 @subsection Making Your Executables Smaller
10824
10825 @noindent
10826 In order to get a smaller executable for your program you now have to
10827 recompile the program completely with the new @file{gnat.adc} file
10828 created by @code{gnatelim} in your current directory:
10829
10830 @smallexample
10831 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10832 @end smallexample
10833
10834 @noindent
10835 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10836 recompile everything
10837 with the set of pragmas @code{Eliminate} that you have obtained with
10838 @command{gnatelim}).
10839
10840 Be aware that the set of @code{Eliminate} pragmas is specific to each
10841 program. It is not recommended to merge sets of @code{Eliminate}
10842 pragmas created for different programs in one @file{gnat.adc} file.
10843
10844 @node Summary of the gnatelim Usage Cycle
10845 @subsection Summary of the gnatelim Usage Cycle
10846
10847 @noindent
10848 Here is a quick summary of the steps to be taken in order to reduce
10849 the size of your executables with @code{gnatelim}. You may use
10850 other GNAT options to control the optimization level,
10851 to produce the debugging information, to set search path, etc.
10852
10853 @enumerate
10854 @item
10855 Produce a bind file
10856
10857 @smallexample
10858 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10859 $ gnatbind main_prog
10860 @end smallexample
10861
10862 @item
10863 Generate a list of @code{Eliminate} pragmas
10864 @smallexample
10865 @ifset vms
10866 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10867 @end ifset
10868 @ifclear vms
10869 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10870 @end ifclear
10871 @end smallexample
10872
10873 @item
10874 Recompile the application
10875
10876 @smallexample
10877 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10878 @end smallexample
10879
10880 @end enumerate
10881
10882 @node Reducing Size of Executables with unused subprogram/data elimination
10883 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10884 @findex unused subprogram/data elimination
10885
10886 @noindent
10887 This section describes how you can eliminate unused subprograms and data from
10888 your executable just by setting options at compilation time.
10889
10890 @menu
10891 * About unused subprogram/data elimination::
10892 * Compilation options::
10893 * Example of unused subprogram/data elimination::
10894 @end menu
10895
10896 @node About unused subprogram/data elimination
10897 @subsection About unused subprogram/data elimination
10898
10899 @noindent
10900 By default, an executable contains all code and data of its composing objects
10901 (directly linked or coming from statically linked libraries), even data or code
10902 never used by this executable.
10903
10904 This feature will allow you to eliminate such unused code from your
10905 executable, making it smaller (in disk and in memory).
10906
10907 This functionality is available on all Linux platforms except for the IA-64
10908 architecture and on all cross platforms using the ELF binary file format.
10909 In both cases GNU binutils version 2.16 or later are required to enable it.
10910
10911 @node Compilation options
10912 @subsection Compilation options
10913
10914 @noindent
10915 The operation of eliminating the unused code and data from the final executable
10916 is directly performed by the linker.
10917
10918 In order to do this, it has to work with objects compiled with the
10919 following options:
10920 @option{-ffunction-sections} @option{-fdata-sections}.
10921 @cindex @option{-ffunction-sections} (@command{gcc})
10922 @cindex @option{-fdata-sections} (@command{gcc})
10923 These options are usable with C and Ada files.
10924 They will place respectively each
10925 function or data in a separate section in the resulting object file.
10926
10927 Once the objects and static libraries are created with these options, the
10928 linker can perform the dead code elimination. You can do this by setting
10929 the @option{-Wl,--gc-sections} option to gcc command or in the
10930 @option{-largs} section of @command{gnatmake}. This will perform a
10931 garbage collection of code and data never referenced.
10932
10933 If the linker performs a partial link (@option{-r} ld linker option), then you
10934 will need to provide one or several entry point using the
10935 @option{-e} / @option{--entry} ld option.
10936
10937 Note that objects compiled without the @option{-ffunction-sections} and
10938 @option{-fdata-sections} options can still be linked with the executable.
10939 However, no dead code elimination will be performed on those objects (they will
10940 be linked as is).
10941
10942 The GNAT static library is now compiled with -ffunction-sections and
10943 -fdata-sections on some platforms. This allows you to eliminate the unused code
10944 and data of the GNAT library from your executable.
10945
10946 @node Example of unused subprogram/data elimination
10947 @subsection Example of unused subprogram/data elimination
10948
10949 @noindent
10950 Here is a simple example:
10951
10952 @smallexample @c ada
10953 with Aux;
10954
10955 procedure Test is
10956 begin
10957    Aux.Used (10);
10958 end Test;
10959
10960 package Aux is
10961    Used_Data   : Integer;
10962    Unused_Data : Integer;
10963
10964    procedure Used   (Data : Integer);
10965    procedure Unused (Data : Integer);
10966 end Aux;
10967
10968 package body Aux is
10969    procedure Used (Data : Integer) is
10970    begin
10971       Used_Data := Data;
10972    end Used;
10973
10974    procedure Unused (Data : Integer) is
10975    begin
10976       Unused_Data := Data;
10977    end Unused;
10978 end Aux;
10979 @end smallexample
10980
10981 @noindent
10982 @code{Unused} and @code{Unused_Data} are never referenced in this code
10983 excerpt, and hence they may be safely removed from the final executable.
10984
10985 @smallexample
10986 $ gnatmake test
10987
10988 $ nm test | grep used
10989 020015f0 T aux__unused
10990 02005d88 B aux__unused_data
10991 020015cc T aux__used
10992 02005d84 B aux__used_data
10993
10994 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10995      -largs -Wl,--gc-sections
10996
10997 $ nm test | grep used
10998 02005350 T aux__used
10999 0201ffe0 B aux__used_data
11000 @end smallexample
11001
11002 @noindent
11003 It can be observed that the procedure @code{Unused} and the object
11004 @code{Unused_Data} are removed by the linker when using the
11005 appropriate options.
11006
11007 @c ********************************
11008 @node Renaming Files Using gnatchop
11009 @chapter Renaming Files Using @code{gnatchop}
11010 @findex gnatchop
11011
11012 @noindent
11013 This chapter discusses how to handle files with multiple units by using
11014 the @code{gnatchop} utility. This utility is also useful in renaming
11015 files to meet the standard GNAT default file naming conventions.
11016
11017 @menu
11018 * Handling Files with Multiple Units::
11019 * Operating gnatchop in Compilation Mode::
11020 * Command Line for gnatchop::
11021 * Switches for gnatchop::
11022 * Examples of gnatchop Usage::
11023 @end menu
11024
11025 @node Handling Files with Multiple Units
11026 @section Handling Files with Multiple Units
11027
11028 @noindent
11029 The basic compilation model of GNAT requires that a file submitted to the
11030 compiler have only one unit and there be a strict correspondence
11031 between the file name and the unit name.
11032
11033 The @code{gnatchop} utility allows both of these rules to be relaxed,
11034 allowing GNAT to process files which contain multiple compilation units
11035 and files with arbitrary file names. @code{gnatchop}
11036 reads the specified file and generates one or more output files,
11037 containing one unit per file. The unit and the file name correspond,
11038 as required by GNAT.
11039
11040 If you want to permanently restructure a set of ``foreign'' files so that
11041 they match the GNAT rules, and do the remaining development using the
11042 GNAT structure, you can simply use @command{gnatchop} once, generate the
11043 new set of files and work with them from that point on.
11044
11045 Alternatively, if you want to keep your files in the ``foreign'' format,
11046 perhaps to maintain compatibility with some other Ada compilation
11047 system, you can set up a procedure where you use @command{gnatchop} each
11048 time you compile, regarding the source files that it writes as temporary
11049 files that you throw away.
11050
11051 Note that if your file containing multiple units starts with a byte order
11052 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11053 will each start with a copy of this BOM, meaning that they can be compiled
11054 automatically in UTF-8 mode without needing to specify an explicit encoding.
11055
11056 @node Operating gnatchop in Compilation Mode
11057 @section Operating gnatchop in Compilation Mode
11058
11059 @noindent
11060 The basic function of @code{gnatchop} is to take a file with multiple units
11061 and split it into separate files. The boundary between files is reasonably
11062 clear, except for the issue of comments and pragmas. In default mode, the
11063 rule is that any pragmas between units belong to the previous unit, except
11064 that configuration pragmas always belong to the following unit. Any comments
11065 belong to the following unit. These rules
11066 almost always result in the right choice of
11067 the split point without needing to mark it explicitly and most users will
11068 find this default to be what they want. In this default mode it is incorrect to
11069 submit a file containing only configuration pragmas, or one that ends in
11070 configuration pragmas, to @code{gnatchop}.
11071
11072 However, using a special option to activate ``compilation mode'',
11073 @code{gnatchop}
11074 can perform another function, which is to provide exactly the semantics
11075 required by the RM for handling of configuration pragmas in a compilation.
11076 In the absence of configuration pragmas (at the main file level), this
11077 option has no effect, but it causes such configuration pragmas to be handled
11078 in a quite different manner.
11079
11080 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11081 only configuration pragmas, then this file is appended to the
11082 @file{gnat.adc} file in the current directory. This behavior provides
11083 the required behavior described in the RM for the actions to be taken
11084 on submitting such a file to the compiler, namely that these pragmas
11085 should apply to all subsequent compilations in the same compilation
11086 environment. Using GNAT, the current directory, possibly containing a
11087 @file{gnat.adc} file is the representation
11088 of a compilation environment. For more information on the
11089 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11090
11091 Second, in compilation mode, if @code{gnatchop}
11092 is given a file that starts with
11093 configuration pragmas, and contains one or more units, then these
11094 configuration pragmas are prepended to each of the chopped files. This
11095 behavior provides the required behavior described in the RM for the
11096 actions to be taken on compiling such a file, namely that the pragmas
11097 apply to all units in the compilation, but not to subsequently compiled
11098 units.
11099
11100 Finally, if configuration pragmas appear between units, they are appended
11101 to the previous unit. This results in the previous unit being illegal,
11102 since the compiler does not accept configuration pragmas that follow
11103 a unit. This provides the required RM behavior that forbids configuration
11104 pragmas other than those preceding the first compilation unit of a
11105 compilation.
11106
11107 For most purposes, @code{gnatchop} will be used in default mode. The
11108 compilation mode described above is used only if you need exactly
11109 accurate behavior with respect to compilations, and you have files
11110 that contain multiple units and configuration pragmas. In this
11111 circumstance the use of @code{gnatchop} with the compilation mode
11112 switch provides the required behavior, and is for example the mode
11113 in which GNAT processes the ACVC tests.
11114
11115 @node Command Line for gnatchop
11116 @section Command Line for @code{gnatchop}
11117
11118 @noindent
11119 The @code{gnatchop} command has the form:
11120
11121 @smallexample
11122 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11123       @ovar{directory}
11124 @end smallexample
11125
11126 @noindent
11127 The only required argument is the file name of the file to be chopped.
11128 There are no restrictions on the form of this file name. The file itself
11129 contains one or more Ada units, in normal GNAT format, concatenated
11130 together. As shown, more than one file may be presented to be chopped.
11131
11132 When run in default mode, @code{gnatchop} generates one output file in
11133 the current directory for each unit in each of the files.
11134
11135 @var{directory}, if specified, gives the name of the directory to which
11136 the output files will be written. If it is not specified, all files are
11137 written to the current directory.
11138
11139 For example, given a
11140 file called @file{hellofiles} containing
11141
11142 @smallexample @c ada
11143 @group
11144 @cartouche
11145 procedure hello;
11146
11147 with Text_IO; use Text_IO;
11148 procedure hello is
11149 begin
11150    Put_Line ("Hello");
11151 end hello;
11152 @end cartouche
11153 @end group
11154 @end smallexample
11155
11156 @noindent
11157 the command
11158
11159 @smallexample
11160 $ gnatchop ^hellofiles^HELLOFILES.^
11161 @end smallexample
11162
11163 @noindent
11164 generates two files in the current directory, one called
11165 @file{hello.ads} containing the single line that is the procedure spec,
11166 and the other called @file{hello.adb} containing the remaining text. The
11167 original file is not affected. The generated files can be compiled in
11168 the normal manner.
11169
11170 @noindent
11171 When gnatchop is invoked on a file that is empty or that contains only empty
11172 lines and/or comments, gnatchop will not fail, but will not produce any
11173 new sources.
11174
11175 For example, given a
11176 file called @file{toto.txt} containing
11177
11178 @smallexample @c ada
11179 @group
11180 @cartouche
11181 --  Just a comment
11182 @end cartouche
11183 @end group
11184 @end smallexample
11185
11186 @noindent
11187 the command
11188
11189 @smallexample
11190 $ gnatchop ^toto.txt^TOT.TXT^
11191 @end smallexample
11192
11193 @noindent
11194 will not produce any new file and will result in the following warnings:
11195
11196 @smallexample
11197 toto.txt:1:01: warning: empty file, contains no compilation units
11198 no compilation units found
11199 no source files written
11200 @end smallexample
11201
11202 @node Switches for gnatchop
11203 @section Switches for @code{gnatchop}
11204
11205 @noindent
11206 @command{gnatchop} recognizes the following switches:
11207
11208 @table @option
11209 @c !sort!
11210
11211 @item --version
11212 @cindex @option{--version} @command{gnatchop}
11213 Display Copyright and version, then exit disregarding all other options.
11214
11215 @item --help
11216 @cindex @option{--help} @command{gnatchop}
11217 If @option{--version} was not used, display usage, then exit disregarding
11218 all other options.
11219
11220 @item ^-c^/COMPILATION^
11221 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11222 Causes @code{gnatchop} to operate in compilation mode, in which
11223 configuration pragmas are handled according to strict RM rules. See
11224 previous section for a full description of this mode.
11225
11226 @ifclear vms
11227 @item -gnat@var{xxx}
11228 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11229 used to parse the given file. Not all @var{xxx} options make sense,
11230 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11231 process a source file that uses Latin-2 coding for identifiers.
11232 @end ifclear
11233
11234 @item ^-h^/HELP^
11235 Causes @code{gnatchop} to generate a brief help summary to the standard
11236 output file showing usage information.
11237
11238 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11239 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11240 Limit generated file names to the specified number @code{mm}
11241 of characters.
11242 This is useful if the
11243 resulting set of files is required to be interoperable with systems
11244 which limit the length of file names.
11245 @ifset vms
11246 If no value is given, or
11247 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11248 a default of 39, suitable for OpenVMS Alpha
11249 Systems, is assumed
11250 @end ifset
11251 @ifclear vms
11252 No space is allowed between the @option{-k} and the numeric value. The numeric
11253 value may be omitted in which case a default of @option{-k8},
11254 suitable for use
11255 with DOS-like file systems, is used. If no @option{-k} switch
11256 is present then
11257 there is no limit on the length of file names.
11258 @end ifclear
11259
11260 @item ^-p^/PRESERVE^
11261 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11262 Causes the file ^modification^creation^ time stamp of the input file to be
11263 preserved and used for the time stamp of the output file(s). This may be
11264 useful for preserving coherency of time stamps in an environment where
11265 @code{gnatchop} is used as part of a standard build process.
11266
11267 @item ^-q^/QUIET^
11268 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11269 Causes output of informational messages indicating the set of generated
11270 files to be suppressed. Warnings and error messages are unaffected.
11271
11272 @item ^-r^/REFERENCE^
11273 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11274 @findex Source_Reference
11275 Generate @code{Source_Reference} pragmas. Use this switch if the output
11276 files are regarded as temporary and development is to be done in terms
11277 of the original unchopped file. This switch causes
11278 @code{Source_Reference} pragmas to be inserted into each of the
11279 generated files to refers back to the original file name and line number.
11280 The result is that all error messages refer back to the original
11281 unchopped file.
11282 In addition, the debugging information placed into the object file (when
11283 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11284 specified)
11285 also refers back to this original file so that tools like profilers and
11286 debuggers will give information in terms of the original unchopped file.
11287
11288 If the original file to be chopped itself contains
11289 a @code{Source_Reference}
11290 pragma referencing a third file, then gnatchop respects
11291 this pragma, and the generated @code{Source_Reference} pragmas
11292 in the chopped file refer to the original file, with appropriate
11293 line numbers. This is particularly useful when @code{gnatchop}
11294 is used in conjunction with @code{gnatprep} to compile files that
11295 contain preprocessing statements and multiple units.
11296
11297 @item ^-v^/VERBOSE^
11298 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11299 Causes @code{gnatchop} to operate in verbose mode. The version
11300 number and copyright notice are output, as well as exact copies of
11301 the gnat1 commands spawned to obtain the chop control information.
11302
11303 @item ^-w^/OVERWRITE^
11304 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11305 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11306 fatal error if there is already a file with the same name as a
11307 file it would otherwise output, in other words if the files to be
11308 chopped contain duplicated units. This switch bypasses this
11309 check, and causes all but the last instance of such duplicated
11310 units to be skipped.
11311
11312 @ifclear vms
11313 @item --GCC=@var{xxxx}
11314 @cindex @option{--GCC=} (@code{gnatchop})
11315 Specify the path of the GNAT parser to be used. When this switch is used,
11316 no attempt is made to add the prefix to the GNAT parser executable.
11317 @end ifclear
11318 @end table
11319
11320 @node Examples of gnatchop Usage
11321 @section Examples of @code{gnatchop} Usage
11322
11323 @table @code
11324 @ifset vms
11325 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11326 @end ifset
11327 @ifclear vms
11328 @item gnatchop -w hello_s.ada prerelease/files
11329 @end ifclear
11330
11331 Chops the source file @file{hello_s.ada}. The output files will be
11332 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11333 overwriting any
11334 files with matching names in that directory (no files in the current
11335 directory are modified).
11336
11337 @item gnatchop ^archive^ARCHIVE.^
11338 Chops the source file @file{^archive^ARCHIVE.^}
11339 into the current directory. One
11340 useful application of @code{gnatchop} is in sending sets of sources
11341 around, for example in email messages. The required sources are simply
11342 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11343 command), and then
11344 @command{gnatchop} is used at the other end to reconstitute the original
11345 file names.
11346
11347 @item gnatchop file1 file2 file3 direc
11348 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11349 the resulting files in the directory @file{direc}. Note that if any units
11350 occur more than once anywhere within this set of files, an error message
11351 is generated, and no files are written. To override this check, use the
11352 @option{^-w^/OVERWRITE^} switch,
11353 in which case the last occurrence in the last file will
11354 be the one that is output, and earlier duplicate occurrences for a given
11355 unit will be skipped.
11356 @end table
11357
11358 @node Configuration Pragmas
11359 @chapter Configuration Pragmas
11360 @cindex Configuration pragmas
11361 @cindex Pragmas, configuration
11362
11363 @noindent
11364 Configuration pragmas include those pragmas described as
11365 such in the Ada Reference Manual, as well as
11366 implementation-dependent pragmas that are configuration pragmas.
11367 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11368 for details on these additional GNAT-specific configuration pragmas.
11369 Most notably, the pragma @code{Source_File_Name}, which allows
11370 specifying non-default names for source files, is a configuration
11371 pragma. The following is a complete list of configuration pragmas
11372 recognized by GNAT:
11373
11374 @smallexample
11375    Ada_83
11376    Ada_95
11377    Ada_05
11378    Ada_2005
11379    Assertion_Policy
11380    Assume_No_Invalid_Values
11381    C_Pass_By_Copy
11382    Check_Name
11383    Check_Policy
11384    Compile_Time_Error
11385    Compile_Time_Warning
11386    Compiler_Unit
11387    Component_Alignment
11388    Convention_Identifier
11389    Debug_Policy
11390    Detect_Blocking
11391    Discard_Names
11392    Elaboration_Checks
11393    Eliminate
11394    Extend_System
11395    Extensions_Allowed
11396    External_Name_Casing
11397    Fast_Math
11398    Favor_Top_Level
11399    Float_Representation
11400    Implicit_Packing
11401    Initialize_Scalars
11402    Interrupt_State
11403    License
11404    Locking_Policy
11405    Long_Float
11406    No_Run_Time
11407    No_Strict_Aliasing
11408    Normalize_Scalars
11409    Optimize_Alignment
11410    Persistent_BSS
11411    Polling
11412    Priority_Specific_Dispatching
11413    Profile
11414    Profile_Warnings
11415    Propagate_Exceptions
11416    Queuing_Policy
11417    Ravenscar
11418    Restricted_Run_Time
11419    Restrictions
11420    Restrictions_Warnings
11421    Reviewable
11422    Source_File_Name
11423    Source_File_Name_Project
11424    Style_Checks
11425    Suppress
11426    Suppress_Exception_Locations
11427    Task_Dispatching_Policy
11428    Universal_Data
11429    Unsuppress
11430    Use_VADS_Size
11431    Validity_Checks
11432    Warnings
11433    Wide_Character_Encoding
11434
11435 @end smallexample
11436
11437 @menu
11438 * Handling of Configuration Pragmas::
11439 * The Configuration Pragmas Files::
11440 @end menu
11441
11442 @node Handling of Configuration Pragmas
11443 @section Handling of Configuration Pragmas
11444
11445 Configuration pragmas may either appear at the start of a compilation
11446 unit, in which case they apply only to that unit, or they may apply to
11447 all compilations performed in a given compilation environment.
11448
11449 GNAT also provides the @code{gnatchop} utility to provide an automatic
11450 way to handle configuration pragmas following the semantics for
11451 compilations (that is, files with multiple units), described in the RM.
11452 See @ref{Operating gnatchop in Compilation Mode} for details.
11453 However, for most purposes, it will be more convenient to edit the
11454 @file{gnat.adc} file that contains configuration pragmas directly,
11455 as described in the following section.
11456
11457 @node The Configuration Pragmas Files
11458 @section The Configuration Pragmas Files
11459 @cindex @file{gnat.adc}
11460
11461 @noindent
11462 In GNAT a compilation environment is defined by the current
11463 directory at the time that a compile command is given. This current
11464 directory is searched for a file whose name is @file{gnat.adc}. If
11465 this file is present, it is expected to contain one or more
11466 configuration pragmas that will be applied to the current compilation.
11467 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11468 considered.
11469
11470 Configuration pragmas may be entered into the @file{gnat.adc} file
11471 either by running @code{gnatchop} on a source file that consists only of
11472 configuration pragmas, or more conveniently  by
11473 direct editing of the @file{gnat.adc} file, which is a standard format
11474 source file.
11475
11476 In addition to @file{gnat.adc}, additional files containing configuration
11477 pragmas may be applied to the current compilation using the switch
11478 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11479 contains only configuration pragmas. These configuration pragmas are
11480 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11481 is present and switch @option{-gnatA} is not used).
11482
11483 It is allowed to specify several switches @option{-gnatec}, all of which
11484 will be taken into account.
11485
11486 If you are using project file, a separate mechanism is provided using
11487 project attributes, see @ref{Specifying Configuration Pragmas} for more
11488 details.
11489
11490 @ifset vms
11491 Of special interest to GNAT OpenVMS Alpha is the following
11492 configuration pragma:
11493
11494 @smallexample @c ada
11495 @cartouche
11496 pragma Extend_System (Aux_DEC);
11497 @end cartouche
11498 @end smallexample
11499
11500 @noindent
11501 In the presence of this pragma, GNAT adds to the definition of the
11502 predefined package SYSTEM all the additional types and subprograms that are
11503 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11504 @end ifset
11505
11506 @node Handling Arbitrary File Naming Conventions Using gnatname
11507 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11508 @cindex Arbitrary File Naming Conventions
11509
11510 @menu
11511 * Arbitrary File Naming Conventions::
11512 * Running gnatname::
11513 * Switches for gnatname::
11514 * Examples of gnatname Usage::
11515 @end menu
11516
11517 @node Arbitrary File Naming Conventions
11518 @section Arbitrary File Naming Conventions
11519
11520 @noindent
11521 The GNAT compiler must be able to know the source file name of a compilation
11522 unit.  When using the standard GNAT default file naming conventions
11523 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11524 does not need additional information.
11525
11526 @noindent
11527 When the source file names do not follow the standard GNAT default file naming
11528 conventions, the GNAT compiler must be given additional information through
11529 a configuration pragmas file (@pxref{Configuration Pragmas})
11530 or a project file.
11531 When the non-standard file naming conventions are well-defined,
11532 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11533 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11534 if the file naming conventions are irregular or arbitrary, a number
11535 of pragma @code{Source_File_Name} for individual compilation units
11536 must be defined.
11537 To help maintain the correspondence between compilation unit names and
11538 source file names within the compiler,
11539 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11540 set of files.
11541
11542 @node Running gnatname
11543 @section Running @code{gnatname}
11544
11545 @noindent
11546 The usual form of the @code{gnatname} command is
11547
11548 @smallexample
11549 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11550       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11551 @end smallexample
11552
11553 @noindent
11554 All of the arguments are optional. If invoked without any argument,
11555 @code{gnatname} will display its usage.
11556
11557 @noindent
11558 When used with at least one naming pattern, @code{gnatname} will attempt to
11559 find all the compilation units in files that follow at least one of the
11560 naming patterns. To find these compilation units,
11561 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11562 regular files.
11563
11564 @noindent
11565 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11566 Each Naming Pattern is enclosed between double quotes.
11567 A Naming Pattern is a regular expression similar to the wildcard patterns
11568 used in file names by the Unix shells or the DOS prompt.
11569
11570 @noindent
11571 @code{gnatname} may be called with several sections of directories/patterns.
11572 Sections are separated by switch @code{--and}. In each section, there must be
11573 at least one pattern. If no directory is specified in a section, the current
11574 directory (or the project directory is @code{-P} is used) is implied.
11575 The options other that the directory switches and the patterns apply globally
11576 even if they are in different sections.
11577
11578 @noindent
11579 Examples of Naming Patterns are
11580
11581 @smallexample
11582    "*.[12].ada"
11583    "*.ad[sb]*"
11584    "body_*"    "spec_*"
11585 @end smallexample
11586
11587 @noindent
11588 For a more complete description of the syntax of Naming Patterns,
11589 see the second kind of regular expressions described in @file{g-regexp.ads}
11590 (the ``Glob'' regular expressions).
11591
11592 @noindent
11593 When invoked with no switch @code{-P}, @code{gnatname} will create a
11594 configuration pragmas file @file{gnat.adc} in the current working directory,
11595 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11596 unit.
11597
11598 @node Switches for gnatname
11599 @section Switches for @code{gnatname}
11600
11601 @noindent
11602 Switches for @code{gnatname} must precede any specified Naming Pattern.
11603
11604 @noindent
11605 You may specify any of the following switches to @code{gnatname}:
11606
11607 @table @option
11608 @c !sort!
11609
11610 @item --version
11611 @cindex @option{--version} @command{gnatname}
11612 Display Copyright and version, then exit disregarding all other options.
11613
11614 @item --help
11615 @cindex @option{--help} @command{gnatname}
11616 If @option{--version} was not used, display usage, then exit disregarding
11617 all other options.
11618
11619 @item --and
11620 Start another section of directories/patterns.
11621
11622 @item ^-c^/CONFIG_FILE=^@file{file}
11623 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11624 Create a configuration pragmas file @file{file} (instead of the default
11625 @file{gnat.adc}).
11626 @ifclear vms
11627 There may be zero, one or more space between @option{-c} and
11628 @file{file}.
11629 @end ifclear
11630 @file{file} may include directory information. @file{file} must be
11631 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11632 When a switch @option{^-c^/CONFIG_FILE^} is
11633 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11634
11635 @item ^-d^/SOURCE_DIRS=^@file{dir}
11636 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11637 Look for source files in directory @file{dir}. There may be zero, one or more
11638 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11639 When a switch @option{^-d^/SOURCE_DIRS^}
11640 is specified, the current working directory will not be searched for source
11641 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11642 or @option{^-D^/DIR_FILES^} switch.
11643 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11644 If @file{dir} is a relative path, it is relative to the directory of
11645 the configuration pragmas file specified with switch
11646 @option{^-c^/CONFIG_FILE^},
11647 or to the directory of the project file specified with switch
11648 @option{^-P^/PROJECT_FILE^} or,
11649 if neither switch @option{^-c^/CONFIG_FILE^}
11650 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11651 current working directory. The directory
11652 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11653
11654 @item ^-D^/DIRS_FILE=^@file{file}
11655 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11656 Look for source files in all directories listed in text file @file{file}.
11657 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11658 and @file{file}.
11659 @file{file} must be an existing, readable text file.
11660 Each nonempty line in @file{file} must be a directory.
11661 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11662 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11663 @file{file}.
11664
11665 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11666 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11667 Foreign patterns. Using this switch, it is possible to add sources of languages
11668 other than Ada to the list of sources of a project file.
11669 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11670 For example,
11671 @smallexample
11672 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11673 @end smallexample
11674 @noindent
11675 will look for Ada units in all files with the @file{.ada} extension,
11676 and will add to the list of file for project @file{prj.gpr} the C files
11677 with extension @file{.^c^C^}.
11678
11679 @item ^-h^/HELP^
11680 @cindex @option{^-h^/HELP^} (@code{gnatname})
11681 Output usage (help) information. The output is written to @file{stdout}.
11682
11683 @item ^-P^/PROJECT_FILE=^@file{proj}
11684 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11685 Create or update project file @file{proj}. There may be zero, one or more space
11686 between @option{-P} and @file{proj}. @file{proj} may include directory
11687 information. @file{proj} must be writable.
11688 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11689 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11690 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11691
11692 @item ^-v^/VERBOSE^
11693 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11694 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11695 This includes name of the file written, the name of the directories to search
11696 and, for each file in those directories whose name matches at least one of
11697 the Naming Patterns, an indication of whether the file contains a unit,
11698 and if so the name of the unit.
11699
11700 @item ^-v -v^/VERBOSE /VERBOSE^
11701 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11702 Very Verbose mode. In addition to the output produced in verbose mode,
11703 for each file in the searched directories whose name matches none of
11704 the Naming Patterns, an indication is given that there is no match.
11705
11706 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11707 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11708 Excluded patterns. Using this switch, it is possible to exclude some files
11709 that would match the name patterns. For example,
11710 @smallexample
11711 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11712 @end smallexample
11713 @noindent
11714 will look for Ada units in all files with the @file{.ada} extension,
11715 except those whose names end with @file{_nt.ada}.
11716
11717 @end table
11718
11719 @node Examples of gnatname Usage
11720 @section Examples of @code{gnatname} Usage
11721
11722 @ifset vms
11723 @smallexample
11724 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11725 @end smallexample
11726 @end ifset
11727
11728 @ifclear vms
11729 @smallexample
11730 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11731 @end smallexample
11732 @end ifclear
11733
11734 @noindent
11735 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11736 and be writable. In addition, the directory
11737 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11738 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11739
11740 @ifclear vms
11741 Note the optional spaces after @option{-c} and @option{-d}.
11742 @end ifclear
11743
11744 @smallexample
11745 @ifclear vms
11746 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11747   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11748 @end ifclear
11749 @ifset vms
11750 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11751   /EXCLUDED_PATTERN=*_nt_body.ada
11752   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11753   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11754 @end ifset
11755 @end smallexample
11756
11757 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11758 even in conjunction with one or several switches
11759 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11760 are used in this example.
11761
11762 @c *****************************************
11763 @c * G N A T  P r o j e c t  M a n a g e r *
11764 @c *****************************************
11765 @node GNAT Project Manager
11766 @chapter GNAT Project Manager
11767
11768 @menu
11769 * Introduction::
11770 * Examples of Project Files::
11771 * Project File Syntax::
11772 * Objects and Sources in Project Files::
11773 * Importing Projects::
11774 * Project Extension::
11775 * Project Hierarchy Extension::
11776 * External References in Project Files::
11777 * Packages in Project Files::
11778 * Variables from Imported Projects::
11779 * Naming Schemes::
11780 * Library Projects::
11781 * Stand-alone Library Projects::
11782 * Switches Related to Project Files::
11783 * Tools Supporting Project Files::
11784 * An Extended Example::
11785 * Project File Complete Syntax::
11786 @end menu
11787
11788 @c ****************
11789 @c * Introduction *
11790 @c ****************
11791
11792 @node Introduction
11793 @section Introduction
11794
11795 @noindent
11796 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11797 you to manage complex builds involving a number of source files, directories,
11798 and compilation options for different system configurations. In particular,
11799 project files allow you to specify:
11800 @itemize @bullet
11801 @item
11802 The directory or set of directories containing the source files, and/or the
11803 names of the specific source files themselves
11804 @item
11805 The directory in which the compiler's output
11806 (@file{ALI} files, object files, tree files) is to be placed
11807 @item
11808 The directory in which the executable programs is to be placed
11809 @item
11810 ^Switch^Switch^ settings for any of the project-enabled tools
11811 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11812 @code{gnatfind}); you can apply these settings either globally or to individual
11813 compilation units.
11814 @item
11815 The source files containing the main subprogram(s) to be built
11816 @item
11817 The source programming language(s) (currently Ada and/or C)
11818 @item
11819 Source file naming conventions; you can specify these either globally or for
11820 individual compilation units
11821 @end itemize
11822
11823 @menu
11824 * Project Files::
11825 @end menu
11826
11827 @node Project Files
11828 @subsection Project Files
11829
11830 @noindent
11831 Project files are written in a syntax close to that of Ada, using  familiar
11832 notions such as packages, context clauses, declarations, default values,
11833 assignments, and inheritance. Finally, project files can be built
11834 hierarchically from other project files, simplifying complex system
11835 integration and project reuse.
11836
11837 A @dfn{project} is a specific set of values for various compilation properties.
11838 The settings for a given project are described by means of
11839 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11840 Property values in project files are either strings or lists of strings.
11841 Properties that are not explicitly set receive default values.  A project
11842 file may interrogate the values of @dfn{external variables} (user-defined
11843 command-line switches or environment variables), and it may specify property
11844 settings conditionally, based on the value of such variables.
11845
11846 In simple cases, a project's source files depend only on other source files
11847 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11848 used in
11849 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11850 the Project Manager also allows more sophisticated arrangements,
11851 where the source files in one project depend on source files in other
11852 projects:
11853 @itemize @bullet
11854 @item
11855 One project can @emph{import} other projects containing needed source files.
11856 @item
11857 You can organize GNAT projects in a hierarchy: a @emph{child} project
11858 can extend a @emph{parent} project, inheriting the parent's source files and
11859 optionally overriding any of them with alternative versions
11860 @end itemize
11861
11862 @noindent
11863 More generally, the Project Manager lets you structure large development
11864 efforts into hierarchical subsystems, where build decisions are delegated
11865 to the subsystem level, and thus different compilation environments
11866 (^switch^switch^ settings) used for different subsystems.
11867
11868 The Project Manager is invoked through the
11869 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11870 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11871 @ifclear vms
11872 There may be zero, one or more spaces between @option{-P} and
11873 @option{@emph{projectfile}}.
11874 @end ifclear
11875 If you want to define (on the command line) an external variable that is
11876 queried by the project file, you must use the
11877 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11878 The Project Manager parses and interprets the project file, and drives the
11879 invoked tool based on the project settings.
11880
11881 The Project Manager supports a wide range of development strategies,
11882 for systems of all sizes.  Here are some typical practices that are
11883 easily handled:
11884 @itemize @bullet
11885 @item
11886 Using a common set of source files, but generating object files in different
11887 directories via different ^switch^switch^ settings
11888 @item
11889 Using a mostly-shared set of source files, but with different versions of
11890 some unit or units
11891 @end itemize
11892
11893 @noindent
11894 The destination of an executable can be controlled inside a project file
11895 using the @option{^-o^-o^}
11896 ^switch^switch^.
11897 In the absence of such a ^switch^switch^ either inside
11898 the project file or on the command line, any executable files generated by
11899 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11900 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11901 in the object directory of the project.
11902
11903 You can use project files to achieve some of the effects of a source
11904 versioning system (for example, defining separate projects for
11905 the different sets of sources that comprise different releases) but the
11906 Project Manager is independent of any source configuration management tools
11907 that might be used by the developers.
11908
11909 The next section introduces the main features of GNAT's project facility
11910 through a sequence of examples; subsequent sections will present the syntax
11911 and semantics in more detail. A more formal description of the project
11912 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11913 Reference Manual}.
11914
11915 @c *****************************
11916 @c * Examples of Project Files *
11917 @c *****************************
11918
11919 @node Examples of Project Files
11920 @section Examples of Project Files
11921 @noindent
11922 This section illustrates some of the typical uses of project files and
11923 explains their basic structure and behavior.
11924
11925 @menu
11926 * Common Sources with Different ^Switches^Switches^ and Directories::
11927 * Using External Variables::
11928 * Importing Other Projects::
11929 * Extending a Project::
11930 @end menu
11931
11932 @node Common Sources with Different ^Switches^Switches^ and Directories
11933 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11934
11935 @menu
11936 * Source Files::
11937 * Specifying the Object Directory::
11938 * Specifying the Exec Directory::
11939 * Project File Packages::
11940 * Specifying ^Switch^Switch^ Settings::
11941 * Main Subprograms::
11942 * Executable File Names::
11943 * Source File Naming Conventions::
11944 * Source Language(s)::
11945 @end menu
11946
11947 @noindent
11948 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11949 @file{proc.adb} are in the @file{/common} directory.  The file
11950 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11951 package @code{Pack}.  We want to compile these source files under two sets
11952 of ^switches^switches^:
11953 @itemize @bullet
11954 @item
11955 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11956 and the @option{^-gnata^-gnata^},
11957 @option{^-gnato^-gnato^},
11958 and @option{^-gnatE^-gnatE^} switches to the
11959 compiler; the compiler's output is to appear in @file{/common/debug}
11960 @item
11961 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11962 to the compiler; the compiler's output is to appear in @file{/common/release}
11963 @end itemize
11964
11965 @noindent
11966 The GNAT project files shown below, respectively @file{debug.gpr} and
11967 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11968
11969 Schematically:
11970 @smallexample
11971 @group
11972 ^/common^[COMMON]^
11973   debug.gpr
11974   release.gpr
11975   pack.ads
11976   pack.adb
11977   proc.adb
11978 @end group
11979 @group
11980 ^/common/debug^[COMMON.DEBUG]^
11981   proc.ali, proc.o
11982   pack.ali, pack.o
11983 @end group
11984 @group
11985 ^/common/release^[COMMON.RELEASE]^
11986   proc.ali, proc.o
11987   pack.ali, pack.o
11988 @end group
11989 @end smallexample
11990 Here are the corresponding project files:
11991
11992 @smallexample @c projectfile
11993 @group
11994 project Debug is
11995   for Object_Dir use "debug";
11996   for Main use ("proc");
11997
11998   package Builder is
11999     for ^Default_Switches^Default_Switches^ ("Ada")
12000         use ("^-g^-g^");
12001     for Executable ("proc.adb") use "proc1";
12002   end Builder;
12003 @end group
12004
12005 @group
12006   package Compiler is
12007     for ^Default_Switches^Default_Switches^ ("Ada")
12008        use ("-fstack-check",
12009             "^-gnata^-gnata^",
12010             "^-gnato^-gnato^",
12011             "^-gnatE^-gnatE^");
12012   end Compiler;
12013 end Debug;
12014 @end group
12015 @end smallexample
12016
12017 @smallexample @c projectfile
12018 @group
12019 project Release is
12020   for Object_Dir use "release";
12021   for Exec_Dir use ".";
12022   for Main use ("proc");
12023
12024   package Compiler is
12025     for ^Default_Switches^Default_Switches^ ("Ada")
12026         use ("^-O2^-O2^");
12027   end Compiler;
12028 end Release;
12029 @end group
12030 @end smallexample
12031
12032 @noindent
12033 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
12034 insensitive), and analogously the project defined by @file{release.gpr} is
12035 @code{"Release"}.  For consistency the file should have the same name as the
12036 project, and the project file's extension should be @code{"gpr"}. These
12037 conventions are not required, but a warning is issued if they are not followed.
12038
12039 If the current directory is @file{^/temp^[TEMP]^}, then the command
12040 @smallexample
12041 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12042 @end smallexample
12043
12044 @noindent
12045 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12046 as well as the @code{^proc1^PROC1.EXE^} executable,
12047 using the ^switch^switch^ settings defined in the project file.
12048
12049 Likewise, the command
12050 @smallexample
12051 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12052 @end smallexample
12053
12054 @noindent
12055 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12056 and the @code{^proc^PROC.EXE^}
12057 executable in @file{^/common^[COMMON]^},
12058 using the ^switch^switch^ settings from the project file.
12059
12060 @node Source Files
12061 @unnumberedsubsubsec Source Files
12062
12063 @noindent
12064 If a project file does not explicitly specify a set of source directories or
12065 a set of source files, then by default the project's source files are the
12066 Ada source files in the project file directory.  Thus @file{pack.ads},
12067 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12068
12069 @node Specifying the Object Directory
12070 @unnumberedsubsubsec Specifying the Object Directory
12071
12072 @noindent
12073 Several project properties are modeled by Ada-style @emph{attributes};
12074 a property is defined by supplying the equivalent of an Ada attribute
12075 definition clause in the project file.
12076 A project's object directory is another such a property; the corresponding
12077 attribute is @code{Object_Dir}, and its value is also a string expression,
12078 specified either as absolute or relative. In the later case,
12079 it is relative to the project file directory. Thus the compiler's
12080 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12081 (for the @code{Debug} project)
12082 and to @file{^/common/release^[COMMON.RELEASE]^}
12083 (for the @code{Release} project).
12084 If @code{Object_Dir} is not specified, then the default is the project file
12085 directory itself.
12086
12087 @node Specifying the Exec Directory
12088 @unnumberedsubsubsec Specifying the Exec Directory
12089
12090 @noindent
12091 A project's exec directory is another property; the corresponding
12092 attribute is @code{Exec_Dir}, and its value is also a string expression,
12093 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12094 then the default is the object directory (which may also be the project file
12095 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12096 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12097 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12098 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12099
12100 @node Project File Packages
12101 @unnumberedsubsubsec Project File Packages
12102
12103 @noindent
12104 A GNAT tool that is integrated with the Project Manager is modeled by a
12105 corresponding package in the project file. In the example above,
12106 The @code{Debug} project defines the packages @code{Builder}
12107 (for @command{gnatmake}) and @code{Compiler};
12108 the @code{Release} project defines only the @code{Compiler} package.
12109
12110 The Ada-like package syntax is not to be taken literally.  Although packages in
12111 project files bear a surface resemblance to packages in Ada source code, the
12112 notation is simply a way to convey a grouping of properties for a named
12113 entity.  Indeed, the package names permitted in project files are restricted
12114 to a predefined set, corresponding to the project-aware tools, and the contents
12115 of packages are limited to a small set of constructs.
12116 The packages in the example above contain attribute definitions.
12117
12118 @node Specifying ^Switch^Switch^ Settings
12119 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12120
12121 @noindent
12122 ^Switch^Switch^ settings for a project-aware tool can be specified through
12123 attributes in the package that corresponds to the tool.
12124 The example above illustrates one of the relevant attributes,
12125 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12126 in both project files.
12127 Unlike simple attributes like @code{Source_Dirs},
12128 @code{^Default_Switches^Default_Switches^} is
12129 known as an @emph{associative array}.  When you define this attribute, you must
12130 supply an ``index'' (a literal string), and the effect of the attribute
12131 definition is to set the value of the array at the specified index.
12132 For the @code{^Default_Switches^Default_Switches^} attribute,
12133 the index is a programming language (in our case, Ada),
12134 and the value specified (after @code{use}) must be a list
12135 of string expressions.
12136
12137 The attributes permitted in project files are restricted to a predefined set.
12138 Some may appear at project level, others in packages.
12139 For any attribute that is an associative array, the index must always be a
12140 literal string, but the restrictions on this string (e.g., a file name or a
12141 language name) depend on the individual attribute.
12142 Also depending on the attribute, its specified value will need to be either a
12143 string or a string list.
12144
12145 In the @code{Debug} project, we set the switches for two tools,
12146 @command{gnatmake} and the compiler, and thus we include the two corresponding
12147 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12148 attribute with index @code{"Ada"}.
12149 Note that the package corresponding to
12150 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12151 similar, but only includes the @code{Compiler} package.
12152
12153 In project @code{Debug} above, the ^switches^switches^ starting with
12154 @option{-gnat} that are specified in package @code{Compiler}
12155 could have been placed in package @code{Builder}, since @command{gnatmake}
12156 transmits all such ^switches^switches^ to the compiler.
12157
12158 @node Main Subprograms
12159 @unnumberedsubsubsec Main Subprograms
12160
12161 @noindent
12162 One of the specifiable properties of a project is a list of files that contain
12163 main subprograms.  This property is captured in the @code{Main} attribute,
12164 whose value is a list of strings.  If a project defines the @code{Main}
12165 attribute, it is not necessary to identify the main subprogram(s) when
12166 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12167
12168 @node Executable File Names
12169 @unnumberedsubsubsec Executable File Names
12170
12171 @noindent
12172 By default, the executable file name corresponding to a main source is
12173 deduced from the main source file name. Through the attributes
12174 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12175 it is possible to change this default.
12176 In project @code{Debug} above, the executable file name
12177 for main source @file{^proc.adb^PROC.ADB^} is
12178 @file{^proc1^PROC1.EXE^}.
12179 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12180 of the executable files, when no attribute @code{Executable} applies:
12181 its value replace the platform-specific executable suffix.
12182 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12183 specify a non-default executable file name when several mains are built at once
12184 in a single @command{gnatmake} command.
12185
12186 @node Source File Naming Conventions
12187 @unnumberedsubsubsec Source File Naming Conventions
12188
12189 @noindent
12190 Since the project files above do not specify any source file naming
12191 conventions, the GNAT defaults are used.  The mechanism for defining source
12192 file naming conventions -- a package named @code{Naming} --
12193 is described below (@pxref{Naming Schemes}).
12194
12195 @node Source Language(s)
12196 @unnumberedsubsubsec Source Language(s)
12197
12198 @noindent
12199 Since the project files do not specify a @code{Languages} attribute, by
12200 default the GNAT tools assume that the language of the project file is Ada.
12201 More generally, a project can comprise source files
12202 in Ada, C, and/or other languages.
12203
12204 @node Using External Variables
12205 @subsection Using External Variables
12206
12207 @noindent
12208 Instead of supplying different project files for debug and release, we can
12209 define a single project file that queries an external variable (set either
12210 on the command line or via an ^environment variable^logical name^) in order to
12211 conditionally define the appropriate settings.  Again, assume that the
12212 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12213 located in directory @file{^/common^[COMMON]^}.  The following project file,
12214 @file{build.gpr}, queries the external variable named @code{STYLE} and
12215 defines an object directory and ^switch^switch^ settings based on whether
12216 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12217 the default is @code{"deb"}.
12218
12219 @smallexample @c projectfile
12220 @group
12221 project Build is
12222   for Main use ("proc");
12223
12224   type Style_Type is ("deb", "rel");
12225   Style : Style_Type := external ("STYLE", "deb");
12226
12227   case Style is
12228     when "deb" =>
12229       for Object_Dir use "debug";
12230
12231     when "rel" =>
12232       for Object_Dir use "release";
12233       for Exec_Dir use ".";
12234   end case;
12235 @end group
12236
12237 @group
12238   package Builder is
12239
12240     case Style is
12241       when "deb" =>
12242         for ^Default_Switches^Default_Switches^ ("Ada")
12243             use ("^-g^-g^");
12244         for Executable ("proc") use "proc1";
12245       when others =>
12246         null;
12247     end case;
12248
12249   end Builder;
12250 @end group
12251
12252 @group
12253   package Compiler is
12254
12255     case Style is
12256       when "deb" =>
12257         for ^Default_Switches^Default_Switches^ ("Ada")
12258             use ("^-gnata^-gnata^",
12259                  "^-gnato^-gnato^",
12260                  "^-gnatE^-gnatE^");
12261
12262       when "rel" =>
12263         for ^Default_Switches^Default_Switches^ ("Ada")
12264             use ("^-O2^-O2^");
12265     end case;
12266
12267   end Compiler;
12268
12269 end Build;
12270 @end group
12271 @end smallexample
12272
12273 @noindent
12274 @code{Style_Type} is an example of a @emph{string type}, which is the project
12275 file analog of an Ada enumeration type but whose components are string literals
12276 rather than identifiers.  @code{Style} is declared as a variable of this type.
12277
12278 The form @code{external("STYLE", "deb")} is known as an
12279 @emph{external reference}; its first argument is the name of an
12280 @emph{external variable}, and the second argument is a default value to be
12281 used if the external variable doesn't exist.  You can define an external
12282 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12283 or you can use ^an environment variable^a logical name^
12284 as an external variable.
12285
12286 Each @code{case} construct is expanded by the Project Manager based on the
12287 value of @code{Style}. Thus the command
12288 @ifclear vms
12289 @smallexample
12290 gnatmake -P/common/build.gpr -XSTYLE=deb
12291 @end smallexample
12292 @end ifclear
12293
12294 @ifset vms
12295 @smallexample
12296 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12297 @end smallexample
12298 @end ifset
12299
12300 @noindent
12301 is equivalent to the @command{gnatmake} invocation using the project file
12302 @file{debug.gpr} in the earlier example.  So is the command
12303 @smallexample
12304 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12305 @end smallexample
12306
12307 @noindent
12308 since @code{"deb"} is the default for @code{STYLE}.
12309
12310 Analogously,
12311
12312 @ifclear vms
12313 @smallexample
12314 gnatmake -P/common/build.gpr -XSTYLE=rel
12315 @end smallexample
12316 @end ifclear
12317
12318 @ifset vms
12319 @smallexample
12320 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12321 @end smallexample
12322 @end ifset
12323
12324 @noindent
12325 is equivalent to the @command{gnatmake} invocation using the project file
12326 @file{release.gpr} in the earlier example.
12327
12328 @node Importing Other Projects
12329 @subsection Importing Other Projects
12330 @cindex @code{ADA_PROJECT_PATH}
12331 @cindex @code{GPR_PROJECT_PATH}
12332
12333 @noindent
12334 A compilation unit in a source file in one project may depend on compilation
12335 units in source files in other projects.  To compile this unit under
12336 control of a project file, the
12337 dependent project must @emph{import} the projects containing the needed source
12338 files.
12339 This effect is obtained using syntax similar to an Ada @code{with} clause,
12340 but where @code{with}ed entities are strings that denote project files.
12341
12342 As an example, suppose that the two projects @code{GUI_Proj} and
12343 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12344 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12345 and @file{^/comm^[COMM]^}, respectively.
12346 Suppose that the source files for @code{GUI_Proj} are
12347 @file{gui.ads} and @file{gui.adb}, and that the source files for
12348 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12349 files is located in its respective project file directory.  Schematically:
12350
12351 @smallexample
12352 @group
12353 ^/gui^[GUI]^
12354   gui_proj.gpr
12355   gui.ads
12356   gui.adb
12357 @end group
12358
12359 @group
12360 ^/comm^[COMM]^
12361   comm_proj.gpr
12362   comm.ads
12363   comm.adb
12364 @end group
12365 @end smallexample
12366
12367 @noindent
12368 We want to develop an application in directory @file{^/app^[APP]^} that
12369 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12370 the corresponding project files (e.g.@: the ^switch^switch^ settings
12371 and object directory).
12372 Skeletal code for a main procedure might be something like the following:
12373
12374 @smallexample @c ada
12375 @group
12376 with GUI, Comm;
12377 procedure App_Main is
12378    @dots{}
12379 begin
12380    @dots{}
12381 end App_Main;
12382 @end group
12383 @end smallexample
12384
12385 @noindent
12386 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12387 effect:
12388
12389 @smallexample @c projectfile
12390 @group
12391 with "/gui/gui_proj", "/comm/comm_proj";
12392 project App_Proj is
12393    for Main use ("app_main");
12394 end App_Proj;
12395 @end group
12396 @end smallexample
12397
12398 @noindent
12399 Building an executable is achieved through the command:
12400 @smallexample
12401 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12402 @end smallexample
12403 @noindent
12404 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12405 in the directory where @file{app_proj.gpr} resides.
12406
12407 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12408 (as illustrated above) the @code{with} clause can omit the extension.
12409
12410 Our example specified an absolute path for each imported project file.
12411 Alternatively, the directory name of an imported object can be omitted
12412 if either
12413 @itemize @bullet
12414 @item
12415 The imported project file is in the same directory as the importing project
12416 file, or
12417 @item
12418 You have defined one or two ^environment variables^logical names^
12419 that includes the directory containing
12420 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12421 @code{ADA_PROJECT_PATH} is the same as
12422 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12423 directory names separated by colons (semicolons on Windows).
12424 @end itemize
12425
12426 @noindent
12427 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12428 to include @file{^/gui^[GUI]^} and
12429 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12430 as follows:
12431
12432 @smallexample @c projectfile
12433 @group
12434 with "gui_proj", "comm_proj";
12435 project App_Proj is
12436    for Main use ("app_main");
12437 end App_Proj;
12438 @end group
12439 @end smallexample
12440
12441 @noindent
12442 Importing other projects can create ambiguities.
12443 For example, the same unit might be present in different imported projects, or
12444 it might be present in both the importing project and in an imported project.
12445 Both of these conditions are errors.  Note that in the current version of
12446 the Project Manager, it is illegal to have an ambiguous unit even if the
12447 unit is never referenced by the importing project.  This restriction may be
12448 relaxed in a future release.
12449
12450 @node Extending a Project
12451 @subsection Extending a Project
12452
12453 @noindent
12454 In large software systems it is common to have multiple
12455 implementations of a common interface; in Ada terms, multiple versions of a
12456 package body for the same spec.  For example, one implementation
12457 might be safe for use in tasking programs, while another might only be used
12458 in sequential applications.  This can be modeled in GNAT using the concept
12459 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12460 another project (the ``parent'') then by default all source files of the
12461 parent project are inherited by the child, but the child project can
12462 override any of the parent's source files with new versions, and can also
12463 add new files.  This facility is the project analog of a type extension in
12464 Object-Oriented Programming.  Project hierarchies are permitted (a child
12465 project may be the parent of yet another project), and a project that
12466 inherits one project can also import other projects.
12467
12468 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12469 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12470 @file{pack.adb}, and @file{proc.adb}:
12471
12472 @smallexample
12473 @group
12474 ^/seq^[SEQ]^
12475   pack.ads
12476   pack.adb
12477   proc.adb
12478   seq_proj.gpr
12479 @end group
12480 @end smallexample
12481
12482 @noindent
12483 Note that the project file can simply be empty (that is, no attribute or
12484 package is defined):
12485
12486 @smallexample @c projectfile
12487 @group
12488 project Seq_Proj is
12489 end Seq_Proj;
12490 @end group
12491 @end smallexample
12492
12493 @noindent
12494 implying that its source files are all the Ada source files in the project
12495 directory.
12496
12497 Suppose we want to supply an alternate version of @file{pack.adb}, in
12498 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12499 @file{pack.ads} and @file{proc.adb}.  We can define a project
12500 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12501
12502 @smallexample
12503 @group
12504 ^/tasking^[TASKING]^
12505   pack.adb
12506   tasking_proj.gpr
12507 @end group
12508
12509 @group
12510 project Tasking_Proj extends "/seq/seq_proj" is
12511 end Tasking_Proj;
12512 @end group
12513 @end smallexample
12514
12515 @noindent
12516 The version of @file{pack.adb} used in a build depends on which project file
12517 is specified.
12518
12519 Note that we could have obtained the desired behavior using project import
12520 rather than project inheritance; a @code{base} project would contain the
12521 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12522 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12523 would import @code{base} and add a different version of @file{pack.adb}.  The
12524 choice depends on whether other sources in the original project need to be
12525 overridden.  If they do, then project extension is necessary, otherwise,
12526 importing is sufficient.
12527
12528 @noindent
12529 In a project file that extends another project file, it is possible to
12530 indicate that an inherited source is not part of the sources of the extending
12531 project. This is necessary sometimes when a package spec has been overloaded
12532 and no longer requires a body: in this case, it is necessary to indicate that
12533 the inherited body is not part of the sources of the project, otherwise there
12534 will be a compilation error when compiling the spec.
12535
12536 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12537 Its value is a string list: a list of file names. It is also possible to use
12538 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12539 the file name of a text file containing a list of file names, one per line.
12540
12541 @smallexample @c @projectfile
12542 project B extends "a" is
12543    for Source_Files use ("pkg.ads");
12544    --  New spec of Pkg does not need a completion
12545    for Excluded_Source_Files use ("pkg.adb");
12546 end B;
12547 @end smallexample
12548
12549 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12550 is still needed: if it is possible to build using @command{gnatmake} when such
12551 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12552 it is possible to remove the source completely from a system that includes
12553 project P.
12554
12555 @c ***********************
12556 @c * Project File Syntax *
12557 @c ***********************
12558
12559 @node Project File Syntax
12560 @section Project File Syntax
12561
12562 @menu
12563 * Basic Syntax::
12564 * Qualified Projects::
12565 * Packages::
12566 * Expressions::
12567 * String Types::
12568 * Variables::
12569 * Attributes::
12570 * Associative Array Attributes::
12571 * case Constructions::
12572 @end menu
12573
12574 @noindent
12575 This section describes the structure of project files.
12576
12577 A project may be an @emph{independent project}, entirely defined by a single
12578 project file. Any Ada source file in an independent project depends only
12579 on the predefined library and other Ada source files in the same project.
12580
12581 @noindent
12582 A project may also @dfn{depend on} other projects, in either or both of
12583 the following ways:
12584 @itemize @bullet
12585 @item It may import any number of projects
12586 @item It may extend at most one other project
12587 @end itemize
12588
12589 @noindent
12590 The dependence relation is a directed acyclic graph (the subgraph reflecting
12591 the ``extends'' relation is a tree).
12592
12593 A project's @dfn{immediate sources} are the source files directly defined by
12594 that project, either implicitly by residing in the project file's directory,
12595 or explicitly through any of the source-related attributes described below.
12596 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12597 of @var{proj} together with the immediate sources (unless overridden) of any
12598 project on which @var{proj} depends (either directly or indirectly).
12599
12600 @node Basic Syntax
12601 @subsection Basic Syntax
12602
12603 @noindent
12604 As seen in the earlier examples, project files have an Ada-like syntax.
12605 The minimal project file is:
12606 @smallexample @c projectfile
12607 @group
12608 project Empty is
12609
12610 end Empty;
12611 @end group
12612 @end smallexample
12613
12614 @noindent
12615 The identifier @code{Empty} is the name of the project.
12616 This project name must be present after the reserved
12617 word @code{end} at the end of the project file, followed by a semi-colon.
12618
12619 Any name in a project file, such as the project name or a variable name,
12620 has the same syntax as an Ada identifier.
12621
12622 The reserved words of project files are the Ada 95 reserved words plus
12623 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12624 reserved words currently used in project file syntax are:
12625
12626 @itemize @bullet
12627 @item
12628 @code{all}
12629 @item
12630 @code{at}
12631 @item
12632 @code{case}
12633 @item
12634 @code{end}
12635 @item
12636 @code{for}
12637 @item
12638 @code{is}
12639 @item
12640 @code{limited}
12641 @item
12642 @code{null}
12643 @item
12644 @code{others}
12645 @item
12646 @code{package}
12647 @item
12648 @code{renames}
12649 @item
12650 @code{type}
12651 @item
12652 @code{use}
12653 @item
12654 @code{when}
12655 @item
12656 @code{with}
12657 @end itemize
12658
12659 @noindent
12660 Comments in project files have the same syntax as in Ada, two consecutive
12661 hyphens through the end of the line.
12662
12663 @node Qualified Projects
12664 @subsection Qualified Projects
12665
12666 @noindent
12667 Before the reserved @code{project}, there may be one or two "qualifiers", that
12668 is identifiers or other reserved words, to qualify the project.
12669
12670 The current list of qualifiers is:
12671
12672 @itemize @bullet
12673 @item
12674 @code{abstract}: qualify a project with no sources. A qualified abstract
12675 project must either have no declaration of attributes @code{Source_Dirs},
12676 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12677 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12678 as empty. If it extends another project, the project it extends must also be a
12679 qualified abstract project.
12680
12681 @item
12682 @code{standard}: a standard project is a non library project with sources.
12683
12684 @item
12685 @code{aggregate}: for future extension
12686
12687 @item
12688 @code{aggregate library}: for future extension
12689
12690 @item
12691 @code{library}: a library project must declare both attributes
12692 @code{Library_Name} and @code{Library_Dir}.
12693
12694 @item
12695 @code{configuration}: a configuration project cannot be in a project tree.
12696 @end itemize
12697
12698 @node Packages
12699 @subsection Packages
12700
12701 @noindent
12702 A project file may contain @emph{packages}. The name of a package must be one
12703 of the identifiers from the following list. A package
12704 with a given name may only appear once in a project file. Package names are
12705 case insensitive. The following package names are legal:
12706
12707 @itemize @bullet
12708 @item
12709 @code{Naming}
12710 @item
12711 @code{Builder}
12712 @item
12713 @code{Compiler}
12714 @item
12715 @code{Binder}
12716 @item
12717 @code{Linker}
12718 @item
12719 @code{Finder}
12720 @item
12721 @code{Cross_Reference}
12722 @item
12723 @code{Check}
12724 @item
12725 @code{Eliminate}
12726 @item
12727 @code{Pretty_Printer}
12728 @item
12729 @code{Metrics}
12730 @item
12731 @code{gnatls}
12732 @item
12733 @code{gnatstub}
12734 @item
12735 @code{IDE}
12736 @item
12737 @code{Language_Processing}
12738 @end itemize
12739
12740 @noindent
12741 In its simplest form, a package may be empty:
12742
12743 @smallexample @c projectfile
12744 @group
12745 project Simple is
12746   package Builder is
12747   end Builder;
12748 end Simple;
12749 @end group
12750 @end smallexample
12751
12752 @noindent
12753 A package may contain @emph{attribute declarations},
12754 @emph{variable declarations} and @emph{case constructions}, as will be
12755 described below.
12756
12757 When there is ambiguity between a project name and a package name,
12758 the name always designates the project. To avoid possible confusion, it is
12759 always a good idea to avoid naming a project with one of the
12760 names allowed for packages or any name that starts with @code{gnat}.
12761
12762 @node Expressions
12763 @subsection Expressions
12764
12765 @noindent
12766 An @emph{expression} is either a @emph{string expression} or a
12767 @emph{string list expression}.
12768
12769 A @emph{string expression} is either a @emph{simple string expression} or a
12770 @emph{compound string expression}.
12771
12772 A @emph{simple string expression} is one of the following:
12773 @itemize @bullet
12774 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12775 @item A string-valued variable reference (@pxref{Variables})
12776 @item A string-valued attribute reference (@pxref{Attributes})
12777 @item An external reference (@pxref{External References in Project Files})
12778 @end itemize
12779
12780 @noindent
12781 A @emph{compound string expression} is a concatenation of string expressions,
12782 using the operator @code{"&"}
12783 @smallexample
12784        Path & "/" & File_Name & ".ads"
12785 @end smallexample
12786
12787 @noindent
12788 A @emph{string list expression} is either a
12789 @emph{simple string list expression} or a
12790 @emph{compound string list expression}.
12791
12792 A @emph{simple string list expression} is one of the following:
12793 @itemize @bullet
12794 @item A parenthesized list of zero or more string expressions,
12795 separated by commas
12796 @smallexample
12797    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12798    Empty_List := ();
12799 @end smallexample
12800 @item A string list-valued variable reference
12801 @item A string list-valued attribute reference
12802 @end itemize
12803
12804 @noindent
12805 A @emph{compound string list expression} is the concatenation (using
12806 @code{"&"}) of a simple string list expression and an expression.  Note that
12807 each term in a compound string list expression, except the first, may be
12808 either a string expression or a string list expression.
12809
12810 @smallexample @c projectfile
12811 @group
12812    File_Name_List := () & File_Name; --  One string in this list
12813    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12814    --  Two strings
12815    Big_List := File_Name_List & Extended_File_Name_List;
12816    --  Concatenation of two string lists: three strings
12817    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12818    --  Illegal: must start with a string list
12819 @end group
12820 @end smallexample
12821
12822 @node String Types
12823 @subsection String Types
12824
12825 @noindent
12826 A @emph{string type declaration} introduces a discrete set of string literals.
12827 If a string variable is declared to have this type, its value
12828 is restricted to the given set of literals.
12829
12830 Here is an example of a string type declaration:
12831
12832 @smallexample @c projectfile
12833    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12834 @end smallexample
12835
12836 @noindent
12837 Variables of a string type are called @emph{typed variables}; all other
12838 variables are called @emph{untyped variables}. Typed variables are
12839 particularly useful in @code{case} constructions, to support conditional
12840 attribute declarations.
12841 (@pxref{case Constructions}).
12842
12843 The string literals in the list are case sensitive and must all be different.
12844 They may include any graphic characters allowed in Ada, including spaces.
12845
12846 A string type may only be declared at the project level, not inside a package.
12847
12848 A string type may be referenced by its name if it has been declared in the same
12849 project file, or by an expanded name whose prefix is the name of the project
12850 in which it is declared.
12851
12852 @node Variables
12853 @subsection Variables
12854
12855 @noindent
12856 A variable may be declared at the project file level, or within a package.
12857 Here are some examples of variable declarations:
12858
12859 @smallexample @c projectfile
12860 @group
12861    This_OS : OS := external ("OS"); --  a typed variable declaration
12862    That_OS := "GNU/Linux";          --  an untyped variable declaration
12863 @end group
12864 @end smallexample
12865
12866 @noindent
12867 The syntax of a @emph{typed variable declaration} is identical to the Ada
12868 syntax for an object declaration. By contrast, the syntax of an untyped
12869 variable declaration is identical to an Ada assignment statement. In fact,
12870 variable declarations in project files have some of the characteristics of
12871 an assignment, in that successive declarations for the same variable are
12872 allowed. Untyped variable declarations do establish the expected kind of the
12873 variable (string or string list), and successive declarations for it must
12874 respect the initial kind.
12875
12876 @noindent
12877 A string variable declaration (typed or untyped) declares a variable
12878 whose value is a string. This variable may be used as a string expression.
12879 @smallexample @c projectfile
12880    File_Name       := "readme.txt";
12881    Saved_File_Name := File_Name & ".saved";
12882 @end smallexample
12883
12884 @noindent
12885 A string list variable declaration declares a variable whose value is a list
12886 of strings. The list may contain any number (zero or more) of strings.
12887
12888 @smallexample @c projectfile
12889    Empty_List := ();
12890    List_With_One_Element := ("^-gnaty^-gnaty^");
12891    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12892    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12893                  "pack2.ada", "util_.ada", "util.ada");
12894 @end smallexample
12895
12896 @noindent
12897 The same typed variable may not be declared more than once at project level,
12898 and it may not be declared more than once in any package; it is in effect
12899 a constant.
12900
12901 The same untyped variable may be declared several times. Declarations are
12902 elaborated in the order in which they appear, so  the new value replaces
12903 the old one, and any subsequent reference to the variable uses the new value.
12904 However, as noted above, if a variable has been declared as a string, all
12905 subsequent
12906 declarations must give it a string value. Similarly, if a variable has
12907 been declared as a string list, all subsequent declarations
12908 must give it a string list value.
12909
12910 A @emph{variable reference} may take several forms:
12911
12912 @itemize @bullet
12913 @item The simple variable name, for a variable in the current package (if any)
12914 or in the current project
12915 @item An expanded name, whose prefix is a context name.
12916 @end itemize
12917
12918 @noindent
12919 A @emph{context} may be one of the following:
12920
12921 @itemize @bullet
12922 @item The name of an existing package in the current project
12923 @item The name of an imported project of the current project
12924 @item The name of an ancestor project (i.e., a project extended by the current
12925 project, either directly or indirectly)
12926 @item An expanded name whose prefix is an imported/parent project name, and
12927 whose selector is a package name in that project.
12928 @end itemize
12929
12930 @noindent
12931 A variable reference may be used in an expression.
12932
12933 @node Attributes
12934 @subsection Attributes
12935
12936 @noindent
12937 A project (and its packages) may have @emph{attributes} that define
12938 the project's properties.  Some attributes have values that are strings;
12939 others have values that are string lists.
12940
12941 There are two categories of attributes: @emph{simple attributes}
12942 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12943
12944 Legal project attribute names, and attribute names for each legal package are
12945 listed below. Attributes names are case-insensitive.
12946
12947 The following attributes are defined on projects (all are simple attributes):
12948
12949 @multitable @columnfractions .4 .3
12950 @item @emph{Attribute Name}
12951 @tab @emph{Value}
12952 @item @code{Source_Files}
12953 @tab string list
12954 @item @code{Source_Dirs}
12955 @tab string list
12956 @item @code{Source_List_File}
12957 @tab string
12958 @item @code{Object_Dir}
12959 @tab string
12960 @item @code{Exec_Dir}
12961 @tab string
12962 @item @code{Excluded_Source_Dirs}
12963 @tab string list
12964 @item @code{Excluded_Source_Files}
12965 @tab string list
12966 @item @code{Excluded_Source_List_File}
12967 @tab string
12968 @item @code{Languages}
12969 @tab string list
12970 @item @code{Main}
12971 @tab string list
12972 @item @code{Library_Dir}
12973 @tab string
12974 @item @code{Library_Name}
12975 @tab string
12976 @item @code{Library_Kind}
12977 @tab string
12978 @item @code{Library_Version}
12979 @tab string
12980 @item @code{Library_Interface}
12981 @tab string
12982 @item @code{Library_Auto_Init}
12983 @tab string
12984 @item @code{Library_Options}
12985 @tab string list
12986 @item @code{Library_Src_Dir}
12987 @tab string
12988 @item @code{Library_ALI_Dir}
12989 @tab string
12990 @item @code{Library_GCC}
12991 @tab string
12992 @item @code{Library_Symbol_File}
12993 @tab string
12994 @item @code{Library_Symbol_Policy}
12995 @tab string
12996 @item @code{Library_Reference_Symbol_File}
12997 @tab string
12998 @item @code{Externally_Built}
12999 @tab string
13000 @end multitable
13001
13002 @noindent
13003 The following attributes are defined for package  @code{Naming}
13004 (@pxref{Naming Schemes}):
13005
13006 @multitable @columnfractions .4 .2 .2 .2
13007 @item Attribute Name @tab Category @tab Index @tab Value
13008 @item @code{Spec_Suffix}
13009 @tab associative array
13010 @tab language name
13011 @tab string
13012 @item @code{Body_Suffix}
13013 @tab associative array
13014 @tab language name
13015 @tab string
13016 @item @code{Separate_Suffix}
13017 @tab simple attribute
13018 @tab n/a
13019 @tab string
13020 @item @code{Casing}
13021 @tab simple attribute
13022 @tab n/a
13023 @tab string
13024 @item @code{Dot_Replacement}
13025 @tab simple attribute
13026 @tab n/a
13027 @tab string
13028 @item @code{Spec}
13029 @tab associative array
13030 @tab Ada unit name
13031 @tab string
13032 @item @code{Body}
13033 @tab associative array
13034 @tab Ada unit name
13035 @tab string
13036 @item @code{Specification_Exceptions}
13037 @tab associative array
13038 @tab language name
13039 @tab string list
13040 @item @code{Implementation_Exceptions}
13041 @tab associative array
13042 @tab language name
13043 @tab string list
13044 @end multitable
13045
13046 @noindent
13047 The following attributes are defined for packages @code{Builder},
13048 @code{Compiler}, @code{Binder},
13049 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13050 (@pxref{^Switches^Switches^ and Project Files}).
13051
13052 @multitable @columnfractions .4 .2 .2 .2
13053 @item Attribute Name @tab Category @tab Index @tab Value
13054 @item @code{^Default_Switches^Default_Switches^}
13055 @tab associative array
13056 @tab language name
13057 @tab string list
13058 @item @code{^Switches^Switches^}
13059 @tab associative array
13060 @tab file name
13061 @tab string list
13062 @end multitable
13063
13064 @noindent
13065 In addition, package @code{Compiler} has a single string attribute
13066 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13067 string attribute @code{Global_Configuration_Pragmas}.
13068
13069 @noindent
13070 Each simple attribute has a default value: the empty string (for string-valued
13071 attributes) and the empty list (for string list-valued attributes).
13072
13073 An attribute declaration defines a new value for an attribute.
13074
13075 Examples of simple attribute declarations:
13076
13077 @smallexample @c projectfile
13078    for Object_Dir use "objects";
13079    for Source_Dirs use ("units", "test/drivers");
13080 @end smallexample
13081
13082 @noindent
13083 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13084 attribute definition clause in Ada.
13085
13086 Attributes references may be appear in expressions.
13087 The general form for such a reference is @code{<entity>'<attribute>}:
13088 Associative array attributes are functions. Associative
13089 array attribute references must have an argument that is a string literal.
13090
13091 Examples are:
13092
13093 @smallexample @c projectfile
13094   project'Object_Dir
13095   Naming'Dot_Replacement
13096   Imported_Project'Source_Dirs
13097   Imported_Project.Naming'Casing
13098   Builder'^Default_Switches^Default_Switches^("Ada")
13099 @end smallexample
13100
13101 @noindent
13102 The prefix of an attribute may be:
13103 @itemize @bullet
13104 @item @code{project} for an attribute of the current project
13105 @item The name of an existing package of the current project
13106 @item The name of an imported project
13107 @item The name of a parent project that is extended by the current project
13108 @item An expanded name whose prefix is imported/parent project name,
13109 and whose selector is a package name
13110 @end itemize
13111
13112 @noindent
13113 Example:
13114 @smallexample @c projectfile
13115 @group
13116    project Prj is
13117      for Source_Dirs use project'Source_Dirs & "units";
13118      for Source_Dirs use project'Source_Dirs & "test/drivers"
13119    end Prj;
13120 @end group
13121 @end smallexample
13122
13123 @noindent
13124 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13125 has the default value: an empty string list. After this declaration,
13126 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13127 After the second attribute declaration @code{Source_Dirs} is a string list of
13128 two elements: @code{"units"} and @code{"test/drivers"}.
13129
13130 Note: this example is for illustration only. In practice,
13131 the project file would contain only one attribute declaration:
13132
13133 @smallexample @c projectfile
13134    for Source_Dirs use ("units", "test/drivers");
13135 @end smallexample
13136
13137 @node Associative Array Attributes
13138 @subsection Associative Array Attributes
13139
13140 @noindent
13141 Some attributes are defined as @emph{associative arrays}. An associative
13142 array may be regarded as a function that takes a string as a parameter
13143 and delivers a string or string list value as its result.
13144
13145 Here are some examples of single associative array attribute associations:
13146
13147 @smallexample @c projectfile
13148    for Body ("main") use "Main.ada";
13149    for ^Switches^Switches^ ("main.ada")
13150        use ("^-v^-v^",
13151             "^-gnatv^-gnatv^");
13152    for ^Switches^Switches^ ("main.ada")
13153             use Builder'^Switches^Switches^ ("main.ada")
13154               & "^-g^-g^";
13155 @end smallexample
13156
13157 @noindent
13158 Like untyped variables and simple attributes, associative array attributes
13159 may be declared several times. Each declaration supplies a new value for the
13160 attribute, and replaces the previous setting.
13161
13162 @noindent
13163 An associative array attribute may be declared as a full associative array
13164 declaration, with the value of the same attribute in an imported or extended
13165 project.
13166
13167 @smallexample @c projectfile
13168    package Builder is
13169       for Default_Switches use Default.Builder'Default_Switches;
13170    end Builder;
13171 @end smallexample
13172
13173 @noindent
13174 In this example, @code{Default} must be either a project imported by the
13175 current project, or the project that the current project extends. If the
13176 attribute is in a package (in this case, in package @code{Builder}), the same
13177 package needs to be specified.
13178
13179 @noindent
13180 A full associative array declaration replaces any other declaration for the
13181 attribute, including other full associative array declaration. Single
13182 associative array associations may be declare after a full associative
13183 declaration, modifying the value for a single association of the attribute.
13184
13185 @node case Constructions
13186 @subsection @code{case} Constructions
13187
13188 @noindent
13189 A @code{case} construction is used in a project file to effect conditional
13190 behavior.
13191 Here is a typical example:
13192
13193 @smallexample @c projectfile
13194 @group
13195 project MyProj is
13196    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13197
13198    OS : OS_Type := external ("OS", "GNU/Linux");
13199 @end group
13200
13201 @group
13202    package Compiler is
13203      case OS is
13204        when "GNU/Linux" | "Unix" =>
13205          for ^Default_Switches^Default_Switches^ ("Ada")
13206              use ("^-gnath^-gnath^");
13207        when "NT" =>
13208          for ^Default_Switches^Default_Switches^ ("Ada")
13209              use ("^-gnatP^-gnatP^");
13210        when others =>
13211      end case;
13212    end Compiler;
13213 end MyProj;
13214 @end group
13215 @end smallexample
13216
13217 @noindent
13218 The syntax of a @code{case} construction is based on the Ada case statement
13219 (although there is no @code{null} construction for empty alternatives).
13220
13221 The case expression must be a typed string variable.
13222 Each alternative comprises the reserved word @code{when}, either a list of
13223 literal strings separated by the @code{"|"} character or the reserved word
13224 @code{others},  and the @code{"=>"} token.
13225 Each literal string must belong to the string type that is the type of the
13226 case variable.
13227 An @code{others} alternative, if present, must occur last.
13228
13229 After each @code{=>}, there are zero or more constructions.  The only
13230 constructions allowed in a case construction are other case constructions,
13231 attribute declarations and variable declarations. String type declarations and
13232 package declarations are not allowed. Variable declarations are restricted to
13233 variables that have already been declared before the case construction.
13234
13235 The value of the case variable is often given by an external reference
13236 (@pxref{External References in Project Files}).
13237
13238 @c ****************************************
13239 @c * Objects and Sources in Project Files *
13240 @c ****************************************
13241
13242 @node Objects and Sources in Project Files
13243 @section Objects and Sources in Project Files
13244
13245 @menu
13246 * Object Directory::
13247 * Exec Directory::
13248 * Source Directories::
13249 * Source File Names::
13250 @end menu
13251
13252 @noindent
13253 Each project has exactly one object directory and one or more source
13254 directories. The source directories must contain at least one source file,
13255 unless  the project file explicitly specifies that no source files are present
13256 (@pxref{Source File Names}).
13257
13258 @node Object Directory
13259 @subsection Object Directory
13260
13261 @noindent
13262 The object directory for a project is the directory containing the compiler's
13263 output (such as @file{ALI} files and object files) for the project's immediate
13264 sources.
13265
13266 The object directory is given by the value of the attribute @code{Object_Dir}
13267 in the project file.
13268
13269 @smallexample @c projectfile
13270    for Object_Dir use "objects";
13271 @end smallexample
13272
13273 @noindent
13274 The attribute @code{Object_Dir} has a string value, the path name of the object
13275 directory. The path name may be absolute or relative to the directory of the
13276 project file. This directory must already exist, and be readable and writable.
13277
13278 By default, when the attribute @code{Object_Dir} is not given an explicit value
13279 or when its value is the empty string, the object directory is the same as the
13280 directory containing the project file.
13281
13282 @node Exec Directory
13283 @subsection Exec Directory
13284
13285 @noindent
13286 The exec directory for a project is the directory containing the executables
13287 for the project's main subprograms.
13288
13289 The exec directory is given by the value of the attribute @code{Exec_Dir}
13290 in the project file.
13291
13292 @smallexample @c projectfile
13293    for Exec_Dir use "executables";
13294 @end smallexample
13295
13296 @noindent
13297 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13298 directory. The path name may be absolute or relative to the directory of the
13299 project file. This directory must already exist, and be writable.
13300
13301 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13302 or when its value is the empty string, the exec directory is the same as the
13303 object directory of the project file.
13304
13305 @node Source Directories
13306 @subsection Source Directories
13307
13308 @noindent
13309 The source directories of a project are specified by the project file
13310 attribute @code{Source_Dirs}.
13311
13312 This attribute's value is a string list. If the attribute is not given an
13313 explicit value, then there is only one source directory, the one where the
13314 project file resides.
13315
13316 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13317 as in
13318
13319 @smallexample @c projectfile
13320     for Source_Dirs use ();
13321 @end smallexample
13322
13323 @noindent
13324 indicates that the project contains no source files.
13325
13326 Otherwise, each string in the string list designates one or more
13327 source directories.
13328
13329 @smallexample @c projectfile
13330    for Source_Dirs use ("sources", "test/drivers");
13331 @end smallexample
13332
13333 @noindent
13334 If a string in the list ends with @code{"/**"},  then the directory whose path
13335 name precedes the two asterisks, as well as all its subdirectories
13336 (recursively), are source directories.
13337
13338 @smallexample @c projectfile
13339    for Source_Dirs use ("/system/sources/**");
13340 @end smallexample
13341
13342 @noindent
13343 Here the directory @code{/system/sources} and all of its subdirectories
13344 (recursively) are source directories.
13345
13346 To specify that the source directories are the directory of the project file
13347 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13348 @smallexample @c projectfile
13349    for Source_Dirs use ("./**");
13350 @end smallexample
13351
13352 @noindent
13353 Each of the source directories must exist and be readable.
13354
13355 @node Source File Names
13356 @subsection Source File Names
13357
13358 @noindent
13359 In a project that contains source files, their names may be specified by the
13360 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13361 (a string). Source file names never include any directory information.
13362
13363 If the attribute @code{Source_Files} is given an explicit value, then each
13364 element of the list is a source file name.
13365
13366 @smallexample @c projectfile
13367    for Source_Files use ("main.adb");
13368    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13369 @end smallexample
13370
13371 @noindent
13372 If the attribute @code{Source_Files} is not given an explicit value,
13373 but the attribute @code{Source_List_File} is given a string value,
13374 then the source file names are contained in the text file whose path name
13375 (absolute or relative to the directory of the project file) is the
13376 value of the attribute @code{Source_List_File}.
13377
13378 Each line in the file that is not empty or is not a comment
13379 contains a source file name.
13380
13381 @smallexample @c projectfile
13382    for Source_List_File use "source_list.txt";
13383 @end smallexample
13384
13385 @noindent
13386 By default, if neither the attribute @code{Source_Files} nor the attribute
13387 @code{Source_List_File} is given an explicit value, then each file in the
13388 source directories that conforms to the project's naming scheme
13389 (@pxref{Naming Schemes}) is an immediate source of the project.
13390
13391 A warning is issued if both attributes @code{Source_Files} and
13392 @code{Source_List_File} are given explicit values. In this case, the attribute
13393 @code{Source_Files} prevails.
13394
13395 Each source file name must be the name of one existing source file
13396 in one of the source directories.
13397
13398 A @code{Source_Files} attribute whose value is an empty list
13399 indicates that there are no source files in the project.
13400
13401 If the order of the source directories is known statically, that is if
13402 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13403 be several files with the same source file name. In this case, only the file
13404 in the first directory is considered as an immediate source of the project
13405 file. If the order of the source directories is not known statically, it is
13406 an error to have several files with the same source file name.
13407
13408 Projects can be specified to have no Ada source
13409 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13410 list, or the @code{"Ada"} may be absent from @code{Languages}:
13411
13412 @smallexample @c projectfile
13413    for Source_Dirs use ();
13414    for Source_Files use ();
13415    for Languages use ("C", "C++");
13416 @end smallexample
13417
13418 @noindent
13419 Otherwise, a project must contain at least one immediate source.
13420
13421 Projects with no source files are useful as template packages
13422 (@pxref{Packages in Project Files}) for other projects; in particular to
13423 define a package @code{Naming} (@pxref{Naming Schemes}).
13424
13425 @c ****************************
13426 @c * Importing Projects *
13427 @c ****************************
13428
13429 @node  Importing Projects
13430 @section Importing Projects
13431 @cindex @code{ADA_PROJECT_PATH}
13432 @cindex @code{GPR_PROJECT_PATH}
13433
13434 @noindent
13435 An immediate source of a project P may depend on source files that
13436 are neither immediate sources of P nor in the predefined library.
13437 To get this effect, P must @emph{import} the projects that contain the needed
13438 source files.
13439
13440 @smallexample @c projectfile
13441 @group
13442   with "project1", "utilities.gpr";
13443   with "/namings/apex.gpr";
13444   project Main is
13445     @dots{}
13446 @end group
13447 @end smallexample
13448
13449 @noindent
13450 As can be seen in this example, the syntax for importing projects is similar
13451 to the syntax for importing compilation units in Ada. However, project files
13452 use literal strings instead of names, and the @code{with} clause identifies
13453 project files rather than packages.
13454
13455 Each literal string is the file name or path name (absolute or relative) of a
13456 project file. If a string corresponds to a file name, with no path or a
13457 relative path, then its location is determined by the @emph{project path}. The
13458 latter can be queried using @code{gnatls -v}. It contains:
13459
13460 @itemize @bullet
13461 @item
13462 In first position, the directory containing the current project file.
13463 @item
13464 In last position, the default project directory. This default project directory
13465 is part of the GNAT installation and is the standard place to install project
13466 files giving access to standard support libraries.
13467 @ifclear vms
13468 @ref{Installing a library}
13469 @end ifclear
13470
13471 @item
13472 In between, all the directories referenced in the
13473 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13474 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13475 @end itemize
13476
13477 @noindent
13478 If a relative pathname is used, as in
13479
13480 @smallexample @c projectfile
13481   with "tests/proj";
13482 @end smallexample
13483
13484 @noindent
13485 then the full path for the project is constructed by concatenating this
13486 relative path to those in the project path, in order, until a matching file is
13487 found. Any symbolic link will be fully resolved in the directory of the
13488 importing project file before the imported project file is examined.
13489
13490 If the @code{with}'ed project file name does not have an extension,
13491 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13492 then the file name as specified in the @code{with} clause (no extension) will
13493 be used. In the above example, if a file @code{project1.gpr} is found, then it
13494 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13495 then it will be used; if neither file exists, this is an error.
13496
13497 A warning is issued if the name of the project file does not match the
13498 name of the project; this check is case insensitive.
13499
13500 Any source file that is an immediate source of the imported project can be
13501 used by the immediate sources of the importing project, transitively. Thus
13502 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13503 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13504 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13505 because if and when @code{B} ceases to import @code{C}, some sources in
13506 @code{A} will no longer compile.
13507
13508 A side effect of this capability is that normally cyclic dependencies are not
13509 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13510 is not allowed to import @code{A}. However, there are cases when cyclic
13511 dependencies would be beneficial. For these cases, another form of import
13512 between projects exists, the @code{limited with}: a project @code{A} that
13513 imports a project @code{B} with a straight @code{with} may also be imported,
13514 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13515 to @code{A} include at least one @code{limited with}.
13516
13517 @smallexample @c 0projectfile
13518 with "../b/b.gpr";
13519 with "../c/c.gpr";
13520 project A is
13521 end A;
13522
13523 limited with "../a/a.gpr";
13524 project B is
13525 end B;
13526
13527 with "../d/d.gpr";
13528 project C is
13529 end C;
13530
13531 limited with "../a/a.gpr";
13532 project D is
13533 end D;
13534 @end smallexample
13535
13536 @noindent
13537 In the above legal example, there are two project cycles:
13538 @itemize @bullet
13539 @item A-> B-> A
13540 @item A -> C -> D -> A
13541 @end itemize
13542
13543 @noindent
13544 In each of these cycle there is one @code{limited with}: import of @code{A}
13545 from @code{B} and import of @code{A} from @code{D}.
13546
13547 The difference between straight @code{with} and @code{limited with} is that
13548 the name of a project imported with a @code{limited with} cannot be used in the
13549 project that imports it. In particular, its packages cannot be renamed and
13550 its variables cannot be referred to.
13551
13552 An exception to the above rules for @code{limited with} is that for the main
13553 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13554 @code{limited with} is equivalent to a straight @code{with}. For example,
13555 in the example above, projects @code{B} and @code{D} could not be main
13556 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13557 each have a @code{limited with} that is the only one in a cycle of importing
13558 projects.
13559
13560 @c *********************
13561 @c * Project Extension *
13562 @c *********************
13563
13564 @node Project Extension
13565 @section Project Extension
13566
13567 @noindent
13568 During development of a large system, it is sometimes necessary to use
13569 modified versions of some of the source files, without changing the original
13570 sources. This can be achieved through the @emph{project extension} facility.
13571
13572 @smallexample @c projectfile
13573    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13574 @end smallexample
13575
13576 @noindent
13577 A project extension declaration introduces an extending project
13578 (the @emph{child}) and a project being extended (the @emph{parent}).
13579
13580 By default, a child project inherits all the sources of its parent.
13581 However, inherited sources can be overridden: a unit in a parent is hidden
13582 by a unit of the same name in the child.
13583
13584 Inherited sources are considered to be sources (but not immediate sources)
13585 of the child project; see @ref{Project File Syntax}.
13586
13587 An inherited source file retains any switches specified in the parent project.
13588
13589 For example if the project @code{Utilities} contains the spec and the
13590 body of an Ada package @code{Util_IO}, then the project
13591 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13592 The original body of @code{Util_IO} will not be considered in program builds.
13593 However, the package spec will still be found in the project
13594 @code{Utilities}.
13595
13596 A child project can have only one parent, except when it is qualified as
13597 abstract. But it may import any number of other projects.
13598
13599 A project is not allowed to import directly or indirectly at the same time a
13600 child project and any of its ancestors.
13601
13602 @c *******************************
13603 @c * Project Hierarchy Extension *
13604 @c *******************************
13605
13606 @node Project Hierarchy Extension
13607 @section Project Hierarchy Extension
13608
13609 @noindent
13610 When extending a large system spanning multiple projects, it is often
13611 inconvenient to extend every project in the hierarchy that is impacted by a
13612 small change introduced. In such cases, it is possible to create a virtual
13613 extension of entire hierarchy using @code{extends all} relationship.
13614
13615 When the project is extended using @code{extends all} inheritance, all projects
13616 that are imported by it, both directly and indirectly, are considered virtually
13617 extended. That is, the Project Manager creates "virtual projects"
13618 that extend every project in the hierarchy; all these virtual projects have
13619 no sources of their own and have as object directory the object directory of
13620 the root of "extending all" project.
13621
13622 It is possible to explicitly extend one or more projects in the hierarchy
13623 in order to modify the sources. These extending projects must be imported by
13624 the "extending all" project, which will replace the corresponding virtual
13625 projects with the explicit ones.
13626
13627 When building such a project hierarchy extension, the Project Manager will
13628 ensure that both modified sources and sources in virtual extending projects
13629 that depend on them, are recompiled.
13630
13631 By means of example, consider the following hierarchy of projects.
13632
13633 @enumerate
13634 @item
13635 project A, containing package P1
13636 @item
13637 project B importing A and containing package P2 which depends on P1
13638 @item
13639 project C importing B and containing package P3 which depends on P2
13640 @end enumerate
13641
13642 @noindent
13643 We want to modify packages P1 and P3.
13644
13645 This project hierarchy will need to be extended as follows:
13646
13647 @enumerate
13648 @item
13649 Create project A1 that extends A, placing modified P1 there:
13650
13651 @smallexample @c 0projectfile
13652 project A1 extends "(@dots{})/A" is
13653 end A1;
13654 @end smallexample
13655
13656 @item
13657 Create project C1 that "extends all" C and imports A1, placing modified
13658 P3 there:
13659
13660 @smallexample @c 0projectfile
13661 with "(@dots{})/A1";
13662 project C1 extends all "(@dots{})/C" is
13663 end C1;
13664 @end smallexample
13665 @end enumerate
13666
13667 When you build project C1, your entire modified project space will be
13668 recompiled, including the virtual project B1 that has been impacted by the
13669 "extending all" inheritance of project C.
13670
13671 Note that if a Library Project in the hierarchy is virtually extended,
13672 the virtual project that extends the Library Project is not a Library Project.
13673
13674 @c ****************************************
13675 @c * External References in Project Files *
13676 @c ****************************************
13677
13678 @node  External References in Project Files
13679 @section External References in Project Files
13680
13681 @noindent
13682 A project file may contain references to external variables; such references
13683 are called @emph{external references}.
13684
13685 An external variable is either defined as part of the environment (an
13686 environment variable in Unix, for example) or else specified on the command
13687 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13688 If both, then the command line value is used.
13689
13690 The value of an external reference is obtained by means of the built-in
13691 function @code{external}, which returns a string value.
13692 This function has two forms:
13693 @itemize @bullet
13694 @item @code{external (external_variable_name)}
13695 @item @code{external (external_variable_name, default_value)}
13696 @end itemize
13697
13698 @noindent
13699 Each parameter must be a string literal.  For example:
13700
13701 @smallexample @c projectfile
13702    external ("USER")
13703    external ("OS", "GNU/Linux")
13704 @end smallexample
13705
13706 @noindent
13707 In the form with one parameter, the function returns the value of
13708 the external variable given as parameter. If this name is not present in the
13709 environment, the function returns an empty string.
13710
13711 In the form with two string parameters, the second argument is
13712 the value returned when the variable given as the first argument is not
13713 present in the environment. In the example above, if @code{"OS"} is not
13714 the name of ^an environment variable^a logical name^ and is not passed on
13715 the command line, then the returned value is @code{"GNU/Linux"}.
13716
13717 An external reference may be part of a string expression or of a string
13718 list expression, and can therefore appear in a variable declaration or
13719 an attribute declaration.
13720
13721 @smallexample @c projectfile
13722 @group
13723    type Mode_Type is ("Debug", "Release");
13724    Mode : Mode_Type := external ("MODE");
13725    case Mode is
13726      when "Debug" =>
13727         @dots{}
13728 @end group
13729 @end smallexample
13730
13731 @c *****************************
13732 @c * Packages in Project Files *
13733 @c *****************************
13734
13735 @node  Packages in Project Files
13736 @section Packages in Project Files
13737
13738 @noindent
13739 A @emph{package} defines the settings for project-aware tools within a
13740 project.
13741 For each such tool one can declare a package; the names for these
13742 packages are preset (@pxref{Packages}).
13743 A package may contain variable declarations, attribute declarations, and case
13744 constructions.
13745
13746 @smallexample @c projectfile
13747 @group
13748    project Proj is
13749       package Builder is  -- used by gnatmake
13750          for ^Default_Switches^Default_Switches^ ("Ada")
13751              use ("^-v^-v^",
13752                   "^-g^-g^");
13753       end Builder;
13754    end Proj;
13755 @end group
13756 @end smallexample
13757
13758 @noindent
13759 The syntax of package declarations mimics that of package in Ada.
13760
13761 Most of the packages have an attribute
13762 @code{^Default_Switches^Default_Switches^}.
13763 This attribute is an associative array, and its value is a string list.
13764 The index of the associative array is the name of a programming language (case
13765 insensitive). This attribute indicates the ^switch^switch^
13766 or ^switches^switches^ to be used
13767 with the corresponding tool.
13768
13769 Some packages also have another attribute, @code{^Switches^Switches^},
13770 an associative array whose value is a string list.
13771 The index is the name of a source file.
13772 This attribute indicates the ^switch^switch^
13773 or ^switches^switches^ to be used by the corresponding
13774 tool when dealing with this specific file.
13775
13776 Further information on these ^switch^switch^-related attributes is found in
13777 @ref{^Switches^Switches^ and Project Files}.
13778
13779 A package may be declared as a @emph{renaming} of another package; e.g., from
13780 the project file for an imported project.
13781
13782 @smallexample @c projectfile
13783 @group
13784   with "/global/apex.gpr";
13785   project Example is
13786     package Naming renames Apex.Naming;
13787     @dots{}
13788   end Example;
13789 @end group
13790 @end smallexample
13791
13792 @noindent
13793 Packages that are renamed in other project files often come from project files
13794 that have no sources: they are just used as templates. Any modification in the
13795 template will be reflected automatically in all the project files that rename
13796 a package from the template.
13797
13798 In addition to the tool-oriented packages, you can also declare a package
13799 named @code{Naming} to establish specialized source file naming conventions
13800 (@pxref{Naming Schemes}).
13801
13802 @c ************************************
13803 @c * Variables from Imported Projects *
13804 @c ************************************
13805
13806 @node Variables from Imported Projects
13807 @section Variables from Imported Projects
13808
13809 @noindent
13810 An attribute or variable defined in an imported or parent project can
13811 be used in expressions in the importing / extending project.
13812 Such an attribute or variable is denoted by an expanded name whose prefix
13813 is either the name of the project or the expanded name of a package within
13814 a project.
13815
13816 @smallexample @c projectfile
13817 @group
13818   with "imported";
13819   project Main extends "base" is
13820      Var1 := Imported.Var;
13821      Var2 := Base.Var & ".new";
13822 @end group
13823
13824 @group
13825      package Builder is
13826         for ^Default_Switches^Default_Switches^ ("Ada")
13827             use Imported.Builder'Ada_^Switches^Switches^ &
13828                 "^-gnatg^-gnatg^" &
13829                 "^-v^-v^";
13830      end Builder;
13831 @end group
13832
13833 @group
13834      package Compiler is
13835         for ^Default_Switches^Default_Switches^ ("Ada")
13836             use Base.Compiler'Ada_^Switches^Switches^;
13837      end Compiler;
13838   end Main;
13839 @end group
13840 @end smallexample
13841
13842 @noindent
13843 In this example:
13844
13845 @itemize @bullet
13846 @item
13847 The value of @code{Var1} is a copy of the variable @code{Var} defined
13848 in the project file @file{"imported.gpr"}
13849 @item
13850 the value of @code{Var2} is a copy of the value of variable @code{Var}
13851 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13852 @item
13853 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13854 @code{Builder} is a string list that includes in its value a copy of the value
13855 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13856 in project file @file{imported.gpr} plus two new elements:
13857 @option{"^-gnatg^-gnatg^"}
13858 and @option{"^-v^-v^"};
13859 @item
13860 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13861 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13862 defined in the @code{Compiler} package in project file @file{base.gpr},
13863 the project being extended.
13864 @end itemize
13865
13866 @c ******************
13867 @c * Naming Schemes *
13868 @c ******************
13869
13870 @node  Naming Schemes
13871 @section Naming Schemes
13872
13873 @noindent
13874 Sometimes an Ada software system is ported from a foreign compilation
13875 environment to GNAT, and the file names do not use the default GNAT
13876 conventions. Instead of changing all the file names (which for a variety
13877 of reasons might not be possible), you can define the relevant file
13878 naming scheme in the @code{Naming} package in your project file.
13879
13880 @noindent
13881 Note that the use of pragmas described in
13882 @ref{Alternative File Naming Schemes} by mean of a configuration
13883 pragmas file is not supported when using project files. You must use
13884 the features described in this paragraph. You can however use specify
13885 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13886
13887 @ifclear vms
13888 For example, the following
13889 package models the Apex file naming rules:
13890
13891 @smallexample @c projectfile
13892 @group
13893   package Naming is
13894     for Casing               use "lowercase";
13895     for Dot_Replacement      use ".";
13896     for Spec_Suffix ("Ada")  use ".1.ada";
13897     for Body_Suffix ("Ada")  use ".2.ada";
13898   end Naming;
13899 @end group
13900 @end smallexample
13901 @end ifclear
13902
13903 @ifset vms
13904 For example, the following package models the HP Ada file naming rules:
13905
13906 @smallexample @c projectfile
13907 @group
13908   package Naming is
13909     for Casing               use "lowercase";
13910     for Dot_Replacement      use "__";
13911     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13912     for Body_Suffix ("Ada")  use ".^ada^ada^";
13913   end Naming;
13914 @end group
13915 @end smallexample
13916
13917 @noindent
13918 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13919 names in lower case)
13920 @end ifset
13921
13922 @noindent
13923 You can define the following attributes in package @code{Naming}:
13924
13925 @table @code
13926
13927 @item @code{Casing}
13928 This must be a string with one of the three values @code{"lowercase"},
13929 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13930
13931 @noindent
13932 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13933
13934 @item @code{Dot_Replacement}
13935 This must be a string whose value satisfies the following conditions:
13936
13937 @itemize @bullet
13938 @item It must not be empty
13939 @item It cannot start or end with an alphanumeric character
13940 @item It cannot be a single underscore
13941 @item It cannot start with an underscore followed by an alphanumeric
13942 @item It cannot contain a dot @code{'.'} except if the entire string
13943 is @code{"."}
13944 @end itemize
13945
13946 @noindent
13947 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13948
13949 @item @code{Spec_Suffix}
13950 This is an associative array (indexed by the programming language name, case
13951 insensitive) whose value is a string that must satisfy the following
13952 conditions:
13953
13954 @itemize @bullet
13955 @item It must not be empty
13956 @item It must include at least one dot
13957 @end itemize
13958 @noindent
13959 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13960 @code{"^.ads^.ADS^"}.
13961
13962 @item @code{Body_Suffix}
13963 This is an associative array (indexed by the programming language name, case
13964 insensitive) whose value is a string that must satisfy the following
13965 conditions:
13966
13967 @itemize @bullet
13968 @item It must not be empty
13969 @item It must include at least one dot
13970 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13971 @end itemize
13972 @noindent
13973 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13974 same string, then a file name that ends with the longest of these two suffixes
13975 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13976 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13977
13978 If the suffix does not start with a '.', a file with a name exactly equal
13979 to the suffix will also be part of the project (for instance if you define
13980 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13981 of the project. This is not interesting in general when using projects to
13982 compile. However, it might become useful when a project is also used to
13983 find the list of source files in an editor, like the GNAT Programming System
13984 (GPS).
13985
13986 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13987 @code{"^.adb^.ADB^"}.
13988
13989 @item @code{Separate_Suffix}
13990 This must be a string whose value satisfies the same conditions as
13991 @code{Body_Suffix}. The same "longest suffix" rules apply.
13992
13993 @noindent
13994 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13995 value as @code{Body_Suffix ("Ada")}.
13996
13997 @item @code{Spec}
13998 @noindent
13999 You can use the associative array attribute @code{Spec}  to define
14000 the source file name for an individual Ada compilation unit's spec. The array
14001 index must be a string literal that identifies the Ada unit (case insensitive).
14002 The value of this attribute must be a string that identifies the file that
14003 contains this unit's spec (case sensitive or insensitive depending on the
14004 operating system).
14005
14006 @smallexample @c projectfile
14007    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
14008 @end smallexample
14009
14010 When the source file contains several units, you can indicate at what
14011 position the unit occurs in the file, with the following. The first unit
14012 in the file has index 1
14013
14014 @smallexample @c projectfile
14015   for Body ("top") use "foo.a" at 1;
14016   for Body ("foo") use "foo.a" at 2;
14017 @end smallexample
14018
14019 @item @code{Body}
14020
14021 You can use the associative array attribute @code{Body} to
14022 define the source file name for an individual Ada compilation unit's body
14023 (possibly a subunit).  The array index must be a string literal that identifies
14024 the Ada unit (case insensitive).  The value of this attribute must be a string
14025 that identifies the file that contains this unit's body or subunit (case
14026 sensitive or insensitive depending on the operating system).
14027
14028 @smallexample @c projectfile
14029    for Body ("MyPack.MyChild") use "mypack.mychild.body";
14030 @end smallexample
14031 @end table
14032
14033 @c ********************
14034 @c * Library Projects *
14035 @c ********************
14036
14037 @node Library Projects
14038 @section Library Projects
14039
14040 @noindent
14041 @emph{Library projects} are projects whose object code is placed in a library.
14042 (Note that this facility is not yet supported on all platforms).
14043
14044 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14045 single archive, which might either be a shared or a static library. This
14046 library can later on be linked with multiple executables, potentially
14047 reducing their sizes.
14048
14049 If your project file specifies languages other than Ada, but you are still
14050 using @code{gnatmake} to compile and link, the latter will not try to
14051 compile your sources other than Ada (you should use @code{gprbuild} if that
14052 is your intent). However, @code{gnatmake} will automatically link all object
14053 files found in the object directory, whether or not they were compiled from
14054 an Ada source file. This specific behavior only applies when multiple
14055 languages are specified.
14056
14057 To create a library project, you need to define in its project file
14058 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14059 Additionally, you may define other library-related attributes such as
14060 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14061 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14062
14063 The @code{Library_Name} attribute has a string value. There is no restriction
14064 on the name of a library. It is the responsibility of the developer to
14065 choose a name that will be accepted by the platform. It is recommended to
14066 choose names that could be Ada identifiers; such names are almost guaranteed
14067 to be acceptable on all platforms.
14068
14069 The @code{Library_Dir} attribute has a string value that designates the path
14070 (absolute or relative) of the directory where the library will reside.
14071 It must designate an existing directory, and this directory must be writable,
14072 different from the project's object directory and from any source directory
14073 in the project tree.
14074
14075 If both @code{Library_Name} and @code{Library_Dir} are specified and
14076 are legal, then the project file defines a library project.  The optional
14077 library-related attributes are checked only for such project files.
14078
14079 The @code{Library_Kind} attribute has a string value that must be one of the
14080 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14081 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14082 attribute is not specified, the library is a static library, that is
14083 an archive of object files that can be potentially linked into a
14084 static executable. Otherwise, the library may be dynamic or
14085 relocatable, that is a library that is loaded only at the start of execution.
14086
14087 If you need to build both a static and a dynamic library, you should use two
14088 different object directories, since in some cases some extra code needs to
14089 be generated for the latter. For such cases, it is recommended to either use
14090 two different project files, or a single one which uses external variables
14091 to indicate what kind of library should be build.
14092
14093 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14094 directory where the ALI files of the library will be copied. When it is
14095 not specified, the ALI files are copied to the directory specified in
14096 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14097 must be writable and different from the project's object directory and from
14098 any source directory in the project tree.
14099
14100 The @code{Library_Version} attribute has a string value whose interpretation
14101 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14102 used only for dynamic/relocatable libraries as the internal name of the
14103 library (the @code{"soname"}). If the library file name (built from the
14104 @code{Library_Name}) is different from the @code{Library_Version}, then the
14105 library file will be a symbolic link to the actual file whose name will be
14106 @code{Library_Version}.
14107
14108 Example (on Unix):
14109
14110 @smallexample @c projectfile
14111 @group
14112 project Plib is
14113
14114    Version := "1";
14115
14116    for Library_Dir use "lib_dir";
14117    for Library_Name use "dummy";
14118    for Library_Kind use "relocatable";
14119    for Library_Version use "libdummy.so." & Version;
14120
14121 end Plib;
14122 @end group
14123 @end smallexample
14124
14125 @noindent
14126 Directory @file{lib_dir} will contain the internal library file whose name
14127 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14128 @file{libdummy.so.1}.
14129
14130 When @command{gnatmake} detects that a project file
14131 is a library project file, it will check all immediate sources of the project
14132 and rebuild the library if any of the sources have been recompiled.
14133
14134 Standard project files can import library project files. In such cases,
14135 the libraries will only be rebuilt if some of its sources are recompiled
14136 because they are in the closure of some other source in an importing project.
14137 Sources of the library project files that are not in such a closure will
14138 not be checked, unless the full library is checked, because one of its sources
14139 needs to be recompiled.
14140
14141 For instance, assume the project file @code{A} imports the library project file
14142 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14143 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14144 @file{l2.ads}, @file{l2.adb}.
14145
14146 If @file{l1.adb} has been modified, then the library associated with @code{L}
14147 will be rebuilt when compiling all the immediate sources of @code{A} only
14148 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14149 @code{"with L1;"}.
14150
14151 To be sure that all the sources in the library associated with @code{L} are
14152 up to date, and that all the sources of project @code{A} are also up to date,
14153 the following two commands needs to be used:
14154
14155 @smallexample
14156 gnatmake -Pl.gpr
14157 gnatmake -Pa.gpr
14158 @end smallexample
14159
14160 When a library is built or rebuilt, an attempt is made first to delete all
14161 files in the library directory.
14162 All @file{ALI} files will also be copied from the object directory to the
14163 library directory. To build executables, @command{gnatmake} will use the
14164 library rather than the individual object files.
14165
14166 @ifclear vms
14167 It is also possible to create library project files for third-party libraries
14168 that are precompiled and cannot be compiled locally thanks to the
14169 @code{externally_built} attribute. (See @ref{Installing a library}).
14170 @end ifclear
14171
14172 @c *******************************
14173 @c * Stand-alone Library Projects *
14174 @c *******************************
14175
14176 @node Stand-alone Library Projects
14177 @section Stand-alone Library Projects
14178
14179 @noindent
14180 A Stand-alone Library is a library that contains the necessary code to
14181 elaborate the Ada units that are included in the library. A Stand-alone
14182 Library is suitable to be used in an executable when the main is not
14183 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14184 subprogram.
14185
14186 A Stand-alone Library Project is a Library Project where the library is
14187 a Stand-alone Library.
14188
14189 To be a Stand-alone Library Project, in addition to the two attributes
14190 that make a project a Library Project (@code{Library_Name} and
14191 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14192 @code{Library_Interface} must be defined.
14193
14194 @smallexample @c projectfile
14195 @group
14196    for Library_Dir use "lib_dir";
14197    for Library_Name use "dummy";
14198    for Library_Interface use ("int1", "int1.child");
14199 @end group
14200 @end smallexample
14201
14202 Attribute @code{Library_Interface} has a nonempty string list value,
14203 each string in the list designating a unit contained in an immediate source
14204 of the project file.
14205
14206 When a Stand-alone Library is built, first the binder is invoked to build
14207 a package whose name depends on the library name
14208 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14209 This binder-generated package includes initialization and
14210 finalization procedures whose
14211 names depend on the library name (dummyinit and dummyfinal in the example
14212 above). The object corresponding to this package is included in the library.
14213
14214 A dynamic or relocatable Stand-alone Library is automatically initialized
14215 if automatic initialization of Stand-alone Libraries is supported on the
14216 platform and if attribute @code{Library_Auto_Init} is not specified or
14217 is specified with the value "true". A static Stand-alone Library is never
14218 automatically initialized.
14219
14220 Single string attribute @code{Library_Auto_Init} may be specified with only
14221 two possible values: "false" or "true" (case-insensitive). Specifying
14222 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14223 initialization of dynamic or relocatable libraries.
14224
14225 When a non-automatically initialized Stand-alone Library is used
14226 in an executable, its initialization procedure must be called before
14227 any service of the library is used.
14228 When the main subprogram is in Ada, it may mean that the initialization
14229 procedure has to be called during elaboration of another package.
14230
14231 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14232 (those that are listed in attribute @code{Library_Interface}) are copied to
14233 the Library Directory. As a consequence, only the Interface Units may be
14234 imported from Ada units outside of the library. If other units are imported,
14235 the binding phase will fail.
14236
14237 When a Stand-Alone Library is bound, the switches that are specified in
14238 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14239 used in the call to @command{gnatbind}.
14240
14241 The string list attribute @code{Library_Options} may be used to specified
14242 additional switches to the call to @command{gcc} to link the library.
14243
14244 The attribute @code{Library_Src_Dir}, may be specified for a
14245 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14246 single string value. Its value must be the path (absolute or relative to the
14247 project directory) of an existing directory. This directory cannot be the
14248 object directory or one of the source directories, but it can be the same as
14249 the library directory. The sources of the Interface
14250 Units of the library, necessary to an Ada client of the library, will be
14251 copied to the designated directory, called Interface Copy directory.
14252 These sources includes the specs of the Interface Units, but they may also
14253 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14254 are used, or when there is a generic units in the spec. Before the sources
14255 are copied to the Interface Copy directory, an attempt is made to delete all
14256 files in the Interface Copy directory.
14257
14258 @c *************************************
14259 @c * Switches Related to Project Files *
14260 @c *************************************
14261 @node Switches Related to Project Files
14262 @section Switches Related to Project Files
14263
14264 @noindent
14265 The following switches are used by GNAT tools that support project files:
14266
14267 @table @option
14268
14269 @item ^-P^/PROJECT_FILE=^@var{project}
14270 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14271 Indicates the name of a project file. This project file will be parsed with
14272 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14273 if any, and using the external references indicated
14274 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14275 @ifclear vms
14276 There may zero, one or more spaces between @option{-P} and @var{project}.
14277 @end ifclear
14278
14279 @noindent
14280 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14281
14282 @noindent
14283 Since the Project Manager parses the project file only after all the switches
14284 on the command line are checked, the order of the switches
14285 @option{^-P^/PROJECT_FILE^},
14286 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14287 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14288
14289 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14290 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14291 Indicates that external variable @var{name} has the value @var{value}.
14292 The Project Manager will use this value for occurrences of
14293 @code{external(name)} when parsing the project file.
14294
14295 @ifclear vms
14296 @noindent
14297 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14298 put between quotes.
14299 @smallexample
14300   -XOS=NT
14301   -X"user=John Doe"
14302 @end smallexample
14303 @end ifclear
14304
14305 @noindent
14306 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14307 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14308 @var{name}, only the last one is used.
14309
14310 @noindent
14311 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14312 takes precedence over the value of the same name in the environment.
14313
14314 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14315 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14316 Indicates the verbosity of the parsing of GNAT project files.
14317
14318 @ifclear vms
14319 @option{-vP0} means Default;
14320 @option{-vP1} means Medium;
14321 @option{-vP2} means High.
14322 @end ifclear
14323
14324 @ifset vms
14325 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14326 HIGH.
14327 @end ifset
14328
14329 @noindent
14330 The default is ^Default^DEFAULT^: no output for syntactically correct
14331 project files.
14332 @noindent
14333 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14334 only the last one is used.
14335
14336 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14337 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14338 Add directory <dir> at the beginning of the project search path, in order,
14339 after the current working directory.
14340
14341 @ifclear vms
14342 @item -eL
14343 @cindex @option{-eL} (any project-aware tool)
14344 Follow all symbolic links when processing project files.
14345 @end ifclear
14346
14347 @item ^--subdirs^/SUBDIRS^=<subdir>
14348 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14349 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14350 directories (except the source directories) are the subdirectories <subdir>
14351 of the directories specified in the project files. This applies in particular
14352 to object directories, library directories and exec directories. If the
14353 subdirectories do not exist, they are created automatically.
14354
14355 @end table
14356
14357 @c **********************************
14358 @c * Tools Supporting Project Files *
14359 @c **********************************
14360
14361 @node  Tools Supporting Project Files
14362 @section Tools Supporting Project Files
14363
14364 @menu
14365 * gnatmake and Project Files::
14366 * The GNAT Driver and Project Files::
14367 @end menu
14368
14369 @node gnatmake and Project Files
14370 @subsection gnatmake and Project Files
14371
14372 @noindent
14373 This section covers several topics related to @command{gnatmake} and
14374 project files: defining ^switches^switches^ for @command{gnatmake}
14375 and for the tools that it invokes; specifying configuration pragmas;
14376 the use of the @code{Main} attribute; building and rebuilding library project
14377 files.
14378
14379 @menu
14380 * ^Switches^Switches^ and Project Files::
14381 * Specifying Configuration Pragmas::
14382 * Project Files and Main Subprograms::
14383 * Library Project Files::
14384 @end menu
14385
14386 @node ^Switches^Switches^ and Project Files
14387 @subsubsection ^Switches^Switches^ and Project Files
14388
14389 @ifset vms
14390 It is not currently possible to specify VMS style qualifiers in the project
14391 files; only Unix style ^switches^switches^ may be specified.
14392 @end ifset
14393
14394 @noindent
14395 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14396 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14397 attribute, a @code{^Switches^Switches^} attribute, or both;
14398 as their names imply, these ^switch^switch^-related
14399 attributes affect the ^switches^switches^ that are used for each of these GNAT
14400 components when
14401 @command{gnatmake} is invoked.  As will be explained below, these
14402 component-specific ^switches^switches^ precede
14403 the ^switches^switches^ provided on the @command{gnatmake} command line.
14404
14405 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14406 array indexed by language name (case insensitive) whose value is a string list.
14407 For example:
14408
14409 @smallexample @c projectfile
14410 @group
14411 package Compiler is
14412   for ^Default_Switches^Default_Switches^ ("Ada")
14413       use ("^-gnaty^-gnaty^",
14414            "^-v^-v^");
14415 end Compiler;
14416 @end group
14417 @end smallexample
14418
14419 @noindent
14420 The @code{^Switches^Switches^} attribute is also an associative array,
14421 indexed by a file name (which may or may not be case sensitive, depending
14422 on the operating system) whose value is a string list.  For example:
14423
14424 @smallexample @c projectfile
14425 @group
14426 package Builder is
14427    for ^Switches^Switches^ ("main1.adb")
14428        use ("^-O2^-O2^");
14429    for ^Switches^Switches^ ("main2.adb")
14430        use ("^-g^-g^");
14431 end Builder;
14432 @end group
14433 @end smallexample
14434
14435 @noindent
14436 For the @code{Builder} package, the file names must designate source files
14437 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14438 file names must designate @file{ALI} or source files for main subprograms.
14439 In each case just the file name without an explicit extension is acceptable.
14440
14441 For each tool used in a program build (@command{gnatmake}, the compiler, the
14442 binder, and the linker), the corresponding package @dfn{contributes} a set of
14443 ^switches^switches^ for each file on which the tool is invoked, based on the
14444 ^switch^switch^-related attributes defined in the package.
14445 In particular, the ^switches^switches^
14446 that each of these packages contributes for a given file @var{f} comprise:
14447
14448 @itemize @bullet
14449 @item
14450 the value of attribute @code{^Switches^Switches^ (@var{f})},
14451 if it is specified in the package for the given file,
14452 @item
14453 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14454 if it is specified in the package.
14455 @end itemize
14456
14457 @noindent
14458 If neither of these attributes is defined in the package, then the package does
14459 not contribute any ^switches^switches^ for the given file.
14460
14461 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14462 two sets, in the following order: those contributed for the file
14463 by the @code{Builder} package;
14464 and the switches passed on the command line.
14465
14466 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14467 the ^switches^switches^ passed to the tool comprise three sets,
14468 in the following order:
14469
14470 @enumerate
14471 @item
14472 the applicable ^switches^switches^ contributed for the file
14473 by the @code{Builder} package in the project file supplied on the command line;
14474
14475 @item
14476 those contributed for the file by the package (in the relevant project file --
14477 see below) corresponding to the tool; and
14478
14479 @item
14480 the applicable switches passed on the command line.
14481 @end enumerate
14482
14483 @noindent
14484 The term @emph{applicable ^switches^switches^} reflects the fact that
14485 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14486 tools, depending on the individual ^switch^switch^.
14487
14488 @command{gnatmake} may invoke the compiler on source files from different
14489 projects. The Project Manager will use the appropriate project file to
14490 determine the @code{Compiler} package for each source file being compiled.
14491 Likewise for the @code{Binder} and @code{Linker} packages.
14492
14493 As an example, consider the following package in a project file:
14494
14495 @smallexample @c projectfile
14496 @group
14497 project Proj1 is
14498    package Compiler is
14499       for ^Default_Switches^Default_Switches^ ("Ada")
14500           use ("^-g^-g^");
14501       for ^Switches^Switches^ ("a.adb")
14502           use ("^-O1^-O1^");
14503       for ^Switches^Switches^ ("b.adb")
14504           use ("^-O2^-O2^",
14505                "^-gnaty^-gnaty^");
14506    end Compiler;
14507 end Proj1;
14508 @end group
14509 @end smallexample
14510
14511 @noindent
14512 If @command{gnatmake} is invoked with this project file, and it needs to
14513 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14514 @file{a.adb} will be compiled with the ^switch^switch^
14515 @option{^-O1^-O1^},
14516 @file{b.adb} with ^switches^switches^
14517 @option{^-O2^-O2^}
14518 and @option{^-gnaty^-gnaty^},
14519 and @file{c.adb} with @option{^-g^-g^}.
14520
14521 The following example illustrates the ordering of the ^switches^switches^
14522 contributed by different packages:
14523
14524 @smallexample @c projectfile
14525 @group
14526 project Proj2 is
14527    package Builder is
14528       for ^Switches^Switches^ ("main.adb")
14529           use ("^-g^-g^",
14530                "^-O1^-)1^",
14531                "^-f^-f^");
14532    end Builder;
14533 @end group
14534
14535 @group
14536    package Compiler is
14537       for ^Switches^Switches^ ("main.adb")
14538           use ("^-O2^-O2^");
14539    end Compiler;
14540 end Proj2;
14541 @end group
14542 @end smallexample
14543
14544 @noindent
14545 If you issue the command:
14546
14547 @smallexample
14548     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14549 @end smallexample
14550
14551 @noindent
14552 then the compiler will be invoked on @file{main.adb} with the following
14553 sequence of ^switches^switches^
14554
14555 @smallexample
14556    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14557 @end smallexample
14558
14559 with the last @option{^-O^-O^}
14560 ^switch^switch^ having precedence over the earlier ones;
14561 several other ^switches^switches^
14562 (such as @option{^-c^-c^}) are added implicitly.
14563
14564 The ^switches^switches^
14565 @option{^-g^-g^}
14566 and @option{^-O1^-O1^} are contributed by package
14567 @code{Builder},  @option{^-O2^-O2^} is contributed
14568 by the package @code{Compiler}
14569 and @option{^-O0^-O0^} comes from the command line.
14570
14571 The @option{^-g^-g^}
14572 ^switch^switch^ will also be passed in the invocation of
14573 @command{Gnatlink.}
14574
14575 A final example illustrates switch contributions from packages in different
14576 project files:
14577
14578 @smallexample @c projectfile
14579 @group
14580 project Proj3 is
14581    for Source_Files use ("pack.ads", "pack.adb");
14582    package Compiler is
14583       for ^Default_Switches^Default_Switches^ ("Ada")
14584           use ("^-gnata^-gnata^");
14585    end Compiler;
14586 end Proj3;
14587 @end group
14588
14589 @group
14590 with "Proj3";
14591 project Proj4 is
14592    for Source_Files use ("foo_main.adb", "bar_main.adb");
14593    package Builder is
14594       for ^Switches^Switches^ ("foo_main.adb")
14595           use ("^-s^-s^",
14596                "^-g^-g^");
14597    end Builder;
14598 end Proj4;
14599 @end group
14600
14601 @group
14602 -- Ada source file:
14603 with Pack;
14604 procedure Foo_Main is
14605    @dots{}
14606 end Foo_Main;
14607 @end group
14608 @end smallexample
14609
14610 If the command is
14611 @smallexample
14612 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14613 @end smallexample
14614
14615 @noindent
14616 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14617 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14618 @option{^-gnato^-gnato^} (passed on the command line).
14619 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14620 are @option{^-g^-g^} from @code{Proj4.Builder},
14621 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14622 and @option{^-gnato^-gnato^} from the command line.
14623
14624 @noindent
14625 When using @command{gnatmake} with project files, some ^switches^switches^ or
14626 arguments may be expressed as relative paths. As the working directory where
14627 compilation occurs may change, these relative paths are converted to absolute
14628 paths. For the ^switches^switches^ found in a project file, the relative paths
14629 are relative to the project file directory, for the switches on the command
14630 line, they are relative to the directory where @command{gnatmake} is invoked.
14631 The ^switches^switches^ for which this occurs are:
14632 ^-I^-I^,
14633 ^-A^-A^,
14634 ^-L^-L^,
14635 ^-aO^-aO^,
14636 ^-aL^-aL^,
14637 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14638 ^switch^switch^
14639 ^-o^-o^, object files specified in package @code{Linker} or after
14640 -largs on the command line). The exception to this rule is the ^switch^switch^
14641 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14642
14643 @node Specifying Configuration Pragmas
14644 @subsubsection Specifying Configuration Pragmas
14645
14646 When using @command{gnatmake} with project files, if there exists a file
14647 @file{gnat.adc} that contains configuration pragmas, this file will be
14648 ignored.
14649
14650 Configuration pragmas can be defined by means of the following attributes in
14651 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14652 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14653
14654 Both these attributes are single string attributes. Their values is the path
14655 name of a file containing configuration pragmas. If a path name is relative,
14656 then it is relative to the project directory of the project file where the
14657 attribute is defined.
14658
14659 When compiling a source, the configuration pragmas used are, in order,
14660 those listed in the file designated by attribute
14661 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14662 project file, if it is specified, and those listed in the file designated by
14663 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14664 the project file of the source, if it exists.
14665
14666 @node Project Files and Main Subprograms
14667 @subsubsection Project Files and Main Subprograms
14668
14669 @noindent
14670 When using a project file, you can invoke @command{gnatmake}
14671 with one or several main subprograms, by specifying their source files on the
14672 command line.
14673
14674 @smallexample
14675     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14676 @end smallexample
14677
14678 @noindent
14679 Each of these needs to be a source file of the same project, except
14680 when the switch ^-u^/UNIQUE^ is used.
14681
14682 @noindent
14683 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14684 same project, one of the project in the tree rooted at the project specified
14685 on the command line. The package @code{Builder} of this common project, the
14686 "main project" is the one that is considered by @command{gnatmake}.
14687
14688 @noindent
14689 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14690 imported directly or indirectly by the project specified on the command line.
14691 Note that if such a source file is not part of the project specified on the
14692 command line, the ^switches^switches^ found in package @code{Builder} of the
14693 project specified on the command line, if any, that are transmitted
14694 to the compiler will still be used, not those found in the project file of
14695 the source file.
14696
14697 @noindent
14698 When using a project file, you can also invoke @command{gnatmake} without
14699 explicitly specifying any main, and the effect depends on whether you have
14700 defined the @code{Main} attribute.  This attribute has a string list value,
14701 where each element in the list is the name of a source file (the file
14702 extension is optional) that contains a unit that can be a main subprogram.
14703
14704 If the @code{Main} attribute is defined in a project file as a non-empty
14705 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14706 line, then invoking @command{gnatmake} with this project file but without any
14707 main on the command line is equivalent to invoking @command{gnatmake} with all
14708 the file names in the @code{Main} attribute on the command line.
14709
14710 Example:
14711 @smallexample @c projectfile
14712 @group
14713    project Prj is
14714       for Main use ("main1", "main2", "main3");
14715    end Prj;
14716 @end group
14717 @end smallexample
14718
14719 @noindent
14720 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14721 is equivalent to
14722 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14723
14724 When the project attribute @code{Main} is not specified, or is specified
14725 as an empty string list, or when the switch @option{-u} is used on the command
14726 line, then invoking @command{gnatmake} with no main on the command line will
14727 result in all immediate sources of the project file being checked, and
14728 potentially recompiled. Depending on the presence of the switch @option{-u},
14729 sources from other project files on which the immediate sources of the main
14730 project file depend are also checked and potentially recompiled. In other
14731 words, the @option{-u} switch is applied to all of the immediate sources of the
14732 main project file.
14733
14734 When no main is specified on the command line and attribute @code{Main} exists
14735 and includes several mains, or when several mains are specified on the
14736 command line, the default ^switches^switches^ in package @code{Builder} will
14737 be used for all mains, even if there are specific ^switches^switches^
14738 specified for one or several mains.
14739
14740 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14741 the specific ^switches^switches^ for each main, if they are specified.
14742
14743 @node Library Project Files
14744 @subsubsection Library Project Files
14745
14746 @noindent
14747 When @command{gnatmake} is invoked with a main project file that is a library
14748 project file, it is not allowed to specify one or more mains on the command
14749 line.
14750
14751 @noindent
14752 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14753 ^-l^/ACTION=LINK^ have special meanings.
14754
14755 @itemize @bullet
14756 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14757 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14758 library.
14759
14760 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14761 to @command{gnatmake} that the binder generated file should be compiled
14762 (in the case of a stand-alone library) and that the library should be built.
14763
14764 @end itemize
14765
14766 @node The GNAT Driver and Project Files
14767 @subsection The GNAT Driver and Project Files
14768
14769 @noindent
14770 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14771 can benefit from project files:
14772 @command{^gnatbind^gnatbind^},
14773 @command{^gnatcheck^gnatcheck^}),
14774 @command{^gnatclean^gnatclean^}),
14775 @command{^gnatelim^gnatelim^},
14776 @command{^gnatfind^gnatfind^},
14777 @command{^gnatlink^gnatlink^},
14778 @command{^gnatls^gnatls^},
14779 @command{^gnatmetric^gnatmetric^},
14780 @command{^gnatpp^gnatpp^},
14781 @command{^gnatstub^gnatstub^},
14782 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14783 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14784 They must be invoked through the @command{gnat} driver.
14785
14786 The @command{gnat} driver is a wrapper that accepts a number of commands and
14787 calls the corresponding tool. It was designed initially for VMS platforms (to
14788 convert VMS qualifiers to Unix-style switches), but it is now available on all
14789 GNAT platforms.
14790
14791 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14792 (case insensitive):
14793
14794 @itemize @bullet
14795 @item
14796 BIND to invoke @command{^gnatbind^gnatbind^}
14797 @item
14798 CHOP to invoke @command{^gnatchop^gnatchop^}
14799 @item
14800 CLEAN to invoke @command{^gnatclean^gnatclean^}
14801 @item
14802 COMP or COMPILE to invoke the compiler
14803 @item
14804 ELIM to invoke @command{^gnatelim^gnatelim^}
14805 @item
14806 FIND to invoke @command{^gnatfind^gnatfind^}
14807 @item
14808 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14809 @item
14810 LINK to invoke @command{^gnatlink^gnatlink^}
14811 @item
14812 LS or LIST to invoke @command{^gnatls^gnatls^}
14813 @item
14814 MAKE to invoke @command{^gnatmake^gnatmake^}
14815 @item
14816 NAME to invoke @command{^gnatname^gnatname^}
14817 @item
14818 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14819 @item
14820 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14821 @item
14822 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14823 @item
14824 STUB to invoke @command{^gnatstub^gnatstub^}
14825 @item
14826 XREF to invoke @command{^gnatxref^gnatxref^}
14827 @end itemize
14828
14829 @noindent
14830 (note that the compiler is invoked using the command
14831 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14832
14833 @noindent
14834 On non-VMS platforms, between @command{gnat} and the command, two
14835 special switches may be used:
14836
14837 @itemize @bullet
14838 @item
14839 @command{-v} to display the invocation of the tool.
14840 @item
14841 @command{-dn} to prevent the @command{gnat} driver from removing
14842 the temporary files it has created. These temporary files are
14843 configuration files and temporary file list files.
14844 @end itemize
14845
14846 @noindent
14847 The command may be followed by switches and arguments for the invoked
14848 tool.
14849
14850 @smallexample
14851   gnat bind -C main.ali
14852   gnat ls -a main
14853   gnat chop foo.txt
14854 @end smallexample
14855
14856 @noindent
14857 Switches may also be put in text files, one switch per line, and the text
14858 files may be specified with their path name preceded by '@@'.
14859
14860 @smallexample
14861    gnat bind @@args.txt main.ali
14862 @end smallexample
14863
14864 @noindent
14865 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14866 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14867 (@option{^-P^/PROJECT_FILE^},
14868 @option{^-X^/EXTERNAL_REFERENCE^} and
14869 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14870 the switches of the invoking tool.
14871
14872 @noindent
14873 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14874 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14875 the immediate sources of the specified project file.
14876
14877 @noindent
14878 When GNAT METRIC is used with a project file, but with no source
14879 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14880 with all the immediate sources of the specified project file and with
14881 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14882 of the project.
14883
14884 @noindent
14885 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14886 a project file, no source is specified on the command line and
14887 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14888 the underlying tool (^gnatpp^gnatpp^ or
14889 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14890 not only for the immediate sources of the main project.
14891 @ifclear vms
14892 (-U stands for Universal or Union of the project files of the project tree)
14893 @end ifclear
14894
14895 @noindent
14896 For each of the following commands, there is optionally a corresponding
14897 package in the main project.
14898
14899 @itemize @bullet
14900 @item
14901 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14902
14903 @item
14904 package @code{Check} for command CHECK (invoking
14905 @code{^gnatcheck^gnatcheck^})
14906
14907 @item
14908 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14909
14910 @item
14911 package @code{Cross_Reference} for command XREF (invoking
14912 @code{^gnatxref^gnatxref^})
14913
14914 @item
14915 package @code{Eliminate} for command ELIM (invoking
14916 @code{^gnatelim^gnatelim^})
14917
14918 @item
14919 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14920
14921 @item
14922 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14923
14924 @item
14925 package @code{Gnatstub} for command STUB
14926 (invoking @code{^gnatstub^gnatstub^})
14927
14928 @item
14929 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14930
14931 @item
14932 package @code{Check} for command CHECK
14933 (invoking @code{^gnatcheck^gnatcheck^})
14934
14935 @item
14936 package @code{Metrics} for command METRIC
14937 (invoking @code{^gnatmetric^gnatmetric^})
14938
14939 @item
14940 package @code{Pretty_Printer} for command PP or PRETTY
14941 (invoking @code{^gnatpp^gnatpp^})
14942
14943 @end itemize
14944
14945 @noindent
14946 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14947 a simple variable with a string list value. It contains ^switches^switches^
14948 for the invocation of @code{^gnatls^gnatls^}.
14949
14950 @smallexample @c projectfile
14951 @group
14952 project Proj1 is
14953    package gnatls is
14954       for ^Switches^Switches^
14955           use ("^-a^-a^",
14956                "^-v^-v^");
14957    end gnatls;
14958 end Proj1;
14959 @end group
14960 @end smallexample
14961
14962 @noindent
14963 All other packages have two attribute @code{^Switches^Switches^} and
14964 @code{^Default_Switches^Default_Switches^}.
14965
14966 @noindent
14967 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14968 source file name, that has a string list value: the ^switches^switches^ to be
14969 used when the tool corresponding to the package is invoked for the specific
14970 source file.
14971
14972 @noindent
14973 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14974 indexed by  the programming language that has a string list value.
14975 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14976 ^switches^switches^ for the invocation of the tool corresponding
14977 to the package, except if a specific @code{^Switches^Switches^} attribute
14978 is specified for the source file.
14979
14980 @smallexample @c projectfile
14981 @group
14982 project Proj is
14983
14984    for Source_Dirs use ("./**");
14985
14986    package gnatls is
14987       for ^Switches^Switches^ use
14988           ("^-a^-a^",
14989            "^-v^-v^");
14990    end gnatls;
14991 @end group
14992 @group
14993
14994    package Compiler is
14995       for ^Default_Switches^Default_Switches^ ("Ada")
14996           use ("^-gnatv^-gnatv^",
14997                "^-gnatwa^-gnatwa^");
14998    end Binder;
14999 @end group
15000 @group
15001
15002    package Binder is
15003       for ^Default_Switches^Default_Switches^ ("Ada")
15004           use ("^-C^-C^",
15005                "^-e^-e^");
15006    end Binder;
15007 @end group
15008 @group
15009
15010    package Linker is
15011       for ^Default_Switches^Default_Switches^ ("Ada")
15012           use ("^-C^-C^");
15013       for ^Switches^Switches^ ("main.adb")
15014           use ("^-C^-C^",
15015                "^-v^-v^",
15016                "^-v^-v^");
15017    end Linker;
15018 @end group
15019 @group
15020
15021    package Finder is
15022       for ^Default_Switches^Default_Switches^ ("Ada")
15023            use ("^-a^-a^",
15024                 "^-f^-f^");
15025    end Finder;
15026 @end group
15027 @group
15028
15029    package Cross_Reference is
15030       for ^Default_Switches^Default_Switches^ ("Ada")
15031           use ("^-a^-a^",
15032                "^-f^-f^",
15033                "^-d^-d^",
15034                "^-u^-u^");
15035    end Cross_Reference;
15036 end Proj;
15037 @end group
15038 @end smallexample
15039
15040 @noindent
15041 With the above project file, commands such as
15042
15043 @smallexample
15044    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15045    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15046    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15047    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15048    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15049 @end smallexample
15050
15051 @noindent
15052 will set up the environment properly and invoke the tool with the switches
15053 found in the package corresponding to the tool:
15054 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15055 except @code{^Switches^Switches^ ("main.adb")}
15056 for @code{^gnatlink^gnatlink^}.
15057 It is also possible to invoke some of the tools,
15058 @code{^gnatcheck^gnatcheck^}),
15059 @code{^gnatmetric^gnatmetric^}),
15060 and @code{^gnatpp^gnatpp^})
15061 on a set of project units thanks to the combination of the switches
15062 @option{-P}, @option{-U} and possibly the main unit when one is interested
15063 in its closure. For instance,
15064 @smallexample
15065 gnat metric -Pproj
15066 @end smallexample
15067 will compute the metrics for all the immediate units of project
15068 @code{proj}.
15069 @smallexample
15070 gnat metric -Pproj -U
15071 @end smallexample
15072 will compute the metrics for all the units of the closure of projects
15073 rooted at @code{proj}.
15074 @smallexample
15075 gnat metric -Pproj -U main_unit
15076 @end smallexample
15077 will compute the metrics for the closure of units rooted at
15078 @code{main_unit}. This last possibility relies implicitly
15079 on @command{gnatbind}'s option @option{-R}.
15080
15081 @c **********************
15082 @node An Extended Example
15083 @section An Extended Example
15084
15085 @noindent
15086 Suppose that we have two programs, @var{prog1} and @var{prog2},
15087 whose sources are in corresponding directories. We would like
15088 to build them with a single @command{gnatmake} command, and we want to place
15089 their object files into @file{build} subdirectories of the source directories.
15090 Furthermore, we want to have to have two separate subdirectories
15091 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15092 the object files compiled with different set of compilation flags.
15093
15094 In other words, we have the following structure:
15095
15096 @smallexample
15097 @group
15098    main
15099      |- prog1
15100      |    |- build
15101      |         | debug
15102      |         | release
15103      |- prog2
15104           |- build
15105                | debug
15106                | release
15107 @end group
15108 @end smallexample
15109
15110 @noindent
15111 Here are the project files that we must place in a directory @file{main}
15112 to maintain this structure:
15113
15114 @enumerate
15115
15116 @item We create a @code{Common} project with a package @code{Compiler} that
15117 specifies the compilation ^switches^switches^:
15118
15119 @smallexample
15120 File "common.gpr":
15121 @group
15122 @b{project} Common @b{is}
15123
15124    @b{for} Source_Dirs @b{use} (); -- No source files
15125 @end group
15126
15127 @group
15128    @b{type} Build_Type @b{is} ("release", "debug");
15129    Build : Build_Type := External ("BUILD", "debug");
15130 @end group
15131 @group
15132    @b{package} Compiler @b{is}
15133       @b{case} Build @b{is}
15134          @b{when} "release" =>
15135            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15136                    @b{use} ("^-O2^-O2^");
15137          @b{when} "debug"   =>
15138            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15139                    @b{use} ("^-g^-g^");
15140       @b{end case};
15141    @b{end} Compiler;
15142
15143 @b{end} Common;
15144 @end group
15145 @end smallexample
15146
15147 @item We create separate projects for the two programs:
15148
15149 @smallexample
15150 @group
15151 File "prog1.gpr":
15152
15153 @b{with} "common";
15154 @b{project} Prog1 @b{is}
15155
15156     @b{for} Source_Dirs @b{use} ("prog1");
15157     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15158
15159     @b{package} Compiler @b{renames} Common.Compiler;
15160
15161 @b{end} Prog1;
15162 @end group
15163 @end smallexample
15164
15165 @smallexample
15166 @group
15167 File "prog2.gpr":
15168
15169 @b{with} "common";
15170 @b{project} Prog2 @b{is}
15171
15172     @b{for} Source_Dirs @b{use} ("prog2");
15173     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15174
15175     @b{package} Compiler @b{renames} Common.Compiler;
15176
15177 @end group
15178 @b{end} Prog2;
15179 @end smallexample
15180
15181 @item We create a wrapping project @code{Main}:
15182
15183 @smallexample
15184 @group
15185 File "main.gpr":
15186
15187 @b{with} "common";
15188 @b{with} "prog1";
15189 @b{with} "prog2";
15190 @b{project} Main @b{is}
15191
15192    @b{package} Compiler @b{renames} Common.Compiler;
15193
15194 @b{end} Main;
15195 @end group
15196 @end smallexample
15197
15198 @item Finally we need to create a dummy procedure that @code{with}s (either
15199 explicitly or implicitly) all the sources of our two programs.
15200
15201 @end enumerate
15202
15203 @noindent
15204 Now we can build the programs using the command
15205
15206 @smallexample
15207    gnatmake ^-P^/PROJECT_FILE=^main dummy
15208 @end smallexample
15209
15210 @noindent
15211 for the Debug mode, or
15212
15213 @ifclear vms
15214 @smallexample
15215    gnatmake -Pmain -XBUILD=release
15216 @end smallexample
15217 @end ifclear
15218
15219 @ifset vms
15220 @smallexample
15221    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15222 @end smallexample
15223 @end ifset
15224
15225 @noindent
15226 for the Release mode.
15227
15228 @c ********************************
15229 @c * Project File Complete Syntax *
15230 @c ********************************
15231
15232 @node Project File Complete Syntax
15233 @section Project File Complete Syntax
15234
15235 @smallexample
15236 project ::=
15237   context_clause project_declaration
15238
15239 context_clause ::=
15240   @{with_clause@}
15241
15242 with_clause ::=
15243   @b{with} path_name @{ , path_name @} ;
15244
15245 path_name ::=
15246    string_literal
15247
15248 project_declaration ::=
15249   simple_project_declaration | project_extension
15250
15251 simple_project_declaration ::=
15252   @b{project} <project_>simple_name @b{is}
15253     @{declarative_item@}
15254   @b{end} <project_>simple_name;
15255
15256 project_extension ::=
15257   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15258     @{declarative_item@}
15259   @b{end} <project_>simple_name;
15260
15261 declarative_item ::=
15262   package_declaration |
15263   typed_string_declaration |
15264   other_declarative_item
15265
15266 package_declaration ::=
15267   package_spec | package_renaming
15268
15269 package_spec ::=
15270   @b{package} package_identifier @b{is}
15271     @{simple_declarative_item@}
15272   @b{end} package_identifier ;
15273
15274 package_identifier ::=
15275   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15276   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15277   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15278
15279 package_renaming ::==
15280   @b{package} package_identifier @b{renames}
15281        <project_>simple_name.package_identifier ;
15282
15283 typed_string_declaration ::=
15284   @b{type} <typed_string_>_simple_name @b{is}
15285    ( string_literal @{, string_literal@} );
15286
15287 other_declarative_item ::=
15288   attribute_declaration |
15289   typed_variable_declaration |
15290   variable_declaration |
15291   case_construction
15292
15293 attribute_declaration ::=
15294   full_associative_array_declaration |
15295   @b{for} attribute_designator @b{use} expression ;
15296
15297 full_associative_array_declaration ::=
15298   @b{for} <associative_array_attribute_>simple_name @b{use}
15299   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15300
15301 attribute_designator ::=
15302   <simple_attribute_>simple_name |
15303   <associative_array_attribute_>simple_name ( string_literal )
15304
15305 typed_variable_declaration ::=
15306   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15307
15308 variable_declaration ::=
15309   <variable_>simple_name := expression;
15310
15311 expression ::=
15312   term @{& term@}
15313
15314 term ::=
15315   literal_string |
15316   string_list |
15317   <variable_>name |
15318   external_value |
15319   attribute_reference
15320
15321 string_literal ::=
15322   (same as Ada)
15323
15324 string_list ::=
15325   ( <string_>expression @{ , <string_>expression @} )
15326
15327 external_value ::=
15328   @b{external} ( string_literal [, string_literal] )
15329
15330 attribute_reference ::=
15331   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15332
15333 attribute_prefix ::=
15334   @b{project} |
15335   <project_>simple_name | package_identifier |
15336   <project_>simple_name . package_identifier
15337
15338 case_construction ::=
15339   @b{case} <typed_variable_>name @b{is}
15340     @{case_item@}
15341   @b{end case} ;
15342
15343 case_item ::=
15344   @b{when} discrete_choice_list =>
15345       @{case_construction | attribute_declaration@}
15346
15347 discrete_choice_list ::=
15348   string_literal @{| string_literal@} |
15349   @b{others}
15350
15351 name ::=
15352   simple_name @{. simple_name@}
15353
15354 simple_name ::=
15355   identifier (same as Ada)
15356
15357 @end smallexample
15358
15359 @node The Cross-Referencing Tools gnatxref and gnatfind
15360 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15361 @findex gnatxref
15362 @findex gnatfind
15363
15364 @noindent
15365 The compiler generates cross-referencing information (unless
15366 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15367 This information indicates where in the source each entity is declared and
15368 referenced. Note that entities in package Standard are not included, but
15369 entities in all other predefined units are included in the output.
15370
15371 Before using any of these two tools, you need to compile successfully your
15372 application, so that GNAT gets a chance to generate the cross-referencing
15373 information.
15374
15375 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15376 information to provide the user with the capability to easily locate the
15377 declaration and references to an entity. These tools are quite similar,
15378 the difference being that @code{gnatfind} is intended for locating
15379 definitions and/or references to a specified entity or entities, whereas
15380 @code{gnatxref} is oriented to generating a full report of all
15381 cross-references.
15382
15383 To use these tools, you must not compile your application using the
15384 @option{-gnatx} switch on the @command{gnatmake} command line
15385 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15386 information will not be generated.
15387
15388 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15389 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15390
15391 @menu
15392 * Switches for gnatxref::
15393 * Switches for gnatfind::
15394 * Project Files for gnatxref and gnatfind::
15395 * Regular Expressions in gnatfind and gnatxref::
15396 * Examples of gnatxref Usage::
15397 * Examples of gnatfind Usage::
15398 @end menu
15399
15400 @node Switches for gnatxref
15401 @section @code{gnatxref} Switches
15402
15403 @noindent
15404 The command invocation for @code{gnatxref} is:
15405 @smallexample
15406 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15407 @end smallexample
15408
15409 @noindent
15410 where
15411
15412 @table @var
15413 @item sourcefile1
15414 @itemx sourcefile2
15415 identifies the source files for which a report is to be generated. The
15416 ``with''ed units will be processed too. You must provide at least one file.
15417
15418 These file names are considered to be regular expressions, so for instance
15419 specifying @file{source*.adb} is the same as giving every file in the current
15420 directory whose name starts with @file{source} and whose extension is
15421 @file{adb}.
15422
15423 You shouldn't specify any directory name, just base names. @command{gnatxref}
15424 and @command{gnatfind} will be able to locate these files by themselves using
15425 the source path. If you specify directories, no result is produced.
15426
15427 @end table
15428
15429 @noindent
15430 The switches can be:
15431 @table @option
15432 @c !sort!
15433 @item --version
15434 @cindex @option{--version} @command{gnatxref}
15435 Display Copyright and version, then exit disregarding all other options.
15436
15437 @item --help
15438 @cindex @option{--help} @command{gnatxref}
15439 If @option{--version} was not used, display usage, then exit disregarding
15440 all other options.
15441
15442 @item ^-a^/ALL_FILES^
15443 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15444 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15445 the read-only files found in the library search path. Otherwise, these files
15446 will be ignored. This option can be used to protect Gnat sources or your own
15447 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15448 much faster, and their output much smaller. Read-only here refers to access
15449 or permissions status in the file system for the current user.
15450
15451 @item -aIDIR
15452 @cindex @option{-aIDIR} (@command{gnatxref})
15453 When looking for source files also look in directory DIR. The order in which
15454 source file search is undertaken is the same as for @command{gnatmake}.
15455
15456 @item -aODIR
15457 @cindex @option{-aODIR} (@command{gnatxref})
15458 When searching for library and object files, look in directory
15459 DIR. The order in which library files are searched is the same as for
15460 @command{gnatmake}.
15461
15462 @item -nostdinc
15463 @cindex @option{-nostdinc} (@command{gnatxref})
15464 Do not look for sources in the system default directory.
15465
15466 @item -nostdlib
15467 @cindex @option{-nostdlib} (@command{gnatxref})
15468 Do not look for library files in the system default directory.
15469
15470 @item --RTS=@var{rts-path}
15471 @cindex @option{--RTS} (@command{gnatxref})
15472 Specifies the default location of the runtime library. Same meaning as the
15473 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15474
15475 @item ^-d^/DERIVED_TYPES^
15476 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15477 If this switch is set @code{gnatxref} will output the parent type
15478 reference for each matching derived types.
15479
15480 @item ^-f^/FULL_PATHNAME^
15481 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15482 If this switch is set, the output file names will be preceded by their
15483 directory (if the file was found in the search path). If this switch is
15484 not set, the directory will not be printed.
15485
15486 @item ^-g^/IGNORE_LOCALS^
15487 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15488 If this switch is set, information is output only for library-level
15489 entities, ignoring local entities. The use of this switch may accelerate
15490 @code{gnatfind} and @code{gnatxref}.
15491
15492 @item -IDIR
15493 @cindex @option{-IDIR} (@command{gnatxref})
15494 Equivalent to @samp{-aODIR -aIDIR}.
15495
15496 @item -pFILE
15497 @cindex @option{-pFILE} (@command{gnatxref})
15498 Specify a project file to use @xref{Project Files}.
15499 If you need to use the @file{.gpr}
15500 project files, you should use gnatxref through the GNAT driver
15501 (@command{gnat xref -Pproject}).
15502
15503 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15504 project file in the current directory.
15505
15506 If a project file is either specified or found by the tools, then the content
15507 of the source directory and object directory lines are added as if they
15508 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15509 and @samp{^-aO^OBJECT_SEARCH^}.
15510 @item ^-u^/UNUSED^
15511 Output only unused symbols. This may be really useful if you give your
15512 main compilation unit on the command line, as @code{gnatxref} will then
15513 display every unused entity and 'with'ed package.
15514
15515 @ifclear vms
15516 @item -v
15517 Instead of producing the default output, @code{gnatxref} will generate a
15518 @file{tags} file that can be used by vi. For examples how to use this
15519 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15520 to the standard output, thus you will have to redirect it to a file.
15521 @end ifclear
15522
15523 @end table
15524
15525 @noindent
15526 All these switches may be in any order on the command line, and may even
15527 appear after the file names. They need not be separated by spaces, thus
15528 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15529 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15530
15531 @node Switches for gnatfind
15532 @section @code{gnatfind} Switches
15533
15534 @noindent
15535 The command line for @code{gnatfind} is:
15536
15537 @smallexample
15538 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15539       @r{[}@var{file1} @var{file2} @dots{}]
15540 @end smallexample
15541
15542 @noindent
15543 where
15544
15545 @table @var
15546 @item pattern
15547 An entity will be output only if it matches the regular expression found
15548 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15549
15550 Omitting the pattern is equivalent to specifying @samp{*}, which
15551 will match any entity. Note that if you do not provide a pattern, you
15552 have to provide both a sourcefile and a line.
15553
15554 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15555 for matching purposes. At the current time there is no support for
15556 8-bit codes other than Latin-1, or for wide characters in identifiers.
15557
15558 @item sourcefile
15559 @code{gnatfind} will look for references, bodies or declarations
15560 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15561 and column @var{column}. See @ref{Examples of gnatfind Usage}
15562 for syntax examples.
15563
15564 @item line
15565 is a decimal integer identifying the line number containing
15566 the reference to the entity (or entities) to be located.
15567
15568 @item column
15569 is a decimal integer identifying the exact location on the
15570 line of the first character of the identifier for the
15571 entity reference. Columns are numbered from 1.
15572
15573 @item file1 file2 @dots{}
15574 The search will be restricted to these source files. If none are given, then
15575 the search will be done for every library file in the search path.
15576 These file must appear only after the pattern or sourcefile.
15577
15578 These file names are considered to be regular expressions, so for instance
15579 specifying @file{source*.adb} is the same as giving every file in the current
15580 directory whose name starts with @file{source} and whose extension is
15581 @file{adb}.
15582
15583 The location of the spec of the entity will always be displayed, even if it
15584 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15585 occurrences of the entity in the separate units of the ones given on the
15586 command line will also be displayed.
15587
15588 Note that if you specify at least one file in this part, @code{gnatfind} may
15589 sometimes not be able to find the body of the subprograms.
15590
15591 @end table
15592
15593 @noindent
15594 At least one of 'sourcefile' or 'pattern' has to be present on
15595 the command line.
15596
15597 The following switches are available:
15598 @table @option
15599 @c !sort!
15600
15601 @cindex @option{--version} @command{gnatfind}
15602 Display Copyright and version, then exit disregarding all other options.
15603
15604 @item --help
15605 @cindex @option{--help} @command{gnatfind}
15606 If @option{--version} was not used, display usage, then exit disregarding
15607 all other options.
15608
15609 @item ^-a^/ALL_FILES^
15610 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15611 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15612 the read-only files found in the library search path. Otherwise, these files
15613 will be ignored. This option can be used to protect Gnat sources or your own
15614 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15615 much faster, and their output much smaller. Read-only here refers to access
15616 or permission status in the file system for the current user.
15617
15618 @item -aIDIR
15619 @cindex @option{-aIDIR} (@command{gnatfind})
15620 When looking for source files also look in directory DIR. The order in which
15621 source file search is undertaken is the same as for @command{gnatmake}.
15622
15623 @item -aODIR
15624 @cindex @option{-aODIR} (@command{gnatfind})
15625 When searching for library and object files, look in directory
15626 DIR. The order in which library files are searched is the same as for
15627 @command{gnatmake}.
15628
15629 @item -nostdinc
15630 @cindex @option{-nostdinc} (@command{gnatfind})
15631 Do not look for sources in the system default directory.
15632
15633 @item -nostdlib
15634 @cindex @option{-nostdlib} (@command{gnatfind})
15635 Do not look for library files in the system default directory.
15636
15637 @item --ext=@var{extension}
15638 @cindex @option{--ext} (@command{gnatfind})
15639 Specify an alternate ali file extension. The default is @code{ali} and other
15640 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15641 switch. Note that if this switch overrides the default, which means that only
15642 the new extension will be considered.
15643
15644 @item --RTS=@var{rts-path}
15645 @cindex @option{--RTS} (@command{gnatfind})
15646 Specifies the default location of the runtime library. Same meaning as the
15647 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15648
15649 @item ^-d^/DERIVED_TYPE_INFORMATION^
15650 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15651 If this switch is set, then @code{gnatfind} will output the parent type
15652 reference for each matching derived types.
15653
15654 @item ^-e^/EXPRESSIONS^
15655 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15656 By default, @code{gnatfind} accept the simple regular expression set for
15657 @samp{pattern}. If this switch is set, then the pattern will be
15658 considered as full Unix-style regular expression.
15659
15660 @item ^-f^/FULL_PATHNAME^
15661 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15662 If this switch is set, the output file names will be preceded by their
15663 directory (if the file was found in the search path). If this switch is
15664 not set, the directory will not be printed.
15665
15666 @item ^-g^/IGNORE_LOCALS^
15667 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15668 If this switch is set, information is output only for library-level
15669 entities, ignoring local entities. The use of this switch may accelerate
15670 @code{gnatfind} and @code{gnatxref}.
15671
15672 @item -IDIR
15673 @cindex @option{-IDIR} (@command{gnatfind})
15674 Equivalent to @samp{-aODIR -aIDIR}.
15675
15676 @item -pFILE
15677 @cindex @option{-pFILE} (@command{gnatfind})
15678 Specify a project file (@pxref{Project Files}) to use.
15679 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15680 project file in the current directory.
15681
15682 If a project file is either specified or found by the tools, then the content
15683 of the source directory and object directory lines are added as if they
15684 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15685 @samp{^-aO^/OBJECT_SEARCH^}.
15686
15687 @item ^-r^/REFERENCES^
15688 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15689 By default, @code{gnatfind} will output only the information about the
15690 declaration, body or type completion of the entities. If this switch is
15691 set, the @code{gnatfind} will locate every reference to the entities in
15692 the files specified on the command line (or in every file in the search
15693 path if no file is given on the command line).
15694
15695 @item ^-s^/PRINT_LINES^
15696 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15697 If this switch is set, then @code{gnatfind} will output the content
15698 of the Ada source file lines were the entity was found.
15699
15700 @item ^-t^/TYPE_HIERARCHY^
15701 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15702 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15703 the specified type. It act like -d option but recursively from parent
15704 type to parent type. When this switch is set it is not possible to
15705 specify more than one file.
15706
15707 @end table
15708
15709 @noindent
15710 All these switches may be in any order on the command line, and may even
15711 appear after the file names. They need not be separated by spaces, thus
15712 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15713 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15714
15715 As stated previously, gnatfind will search in every directory in the
15716 search path. You can force it to look only in the current directory if
15717 you specify @code{*} at the end of the command line.
15718
15719 @node Project Files for gnatxref and gnatfind
15720 @section Project Files for @command{gnatxref} and @command{gnatfind}
15721
15722 @noindent
15723 Project files allow a programmer to specify how to compile its
15724 application, where to find sources, etc.  These files are used
15725 @ifclear vms
15726 primarily by GPS, but they can also be used
15727 @end ifclear
15728 by the two tools
15729 @code{gnatxref} and @code{gnatfind}.
15730
15731 A project file name must end with @file{.gpr}. If a single one is
15732 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15733 extract the information from it. If multiple project files are found, none of
15734 them is read, and you have to use the @samp{-p} switch to specify the one
15735 you want to use.
15736
15737 The following lines can be included, even though most of them have default
15738 values which can be used in most cases.
15739 The lines can be entered in any order in the file.
15740 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15741 each line. If you have multiple instances, only the last one is taken into
15742 account.
15743
15744 @table @code
15745 @item src_dir=DIR
15746 [default: @code{"^./^[]^"}]
15747 specifies a directory where to look for source files. Multiple @code{src_dir}
15748 lines can be specified and they will be searched in the order they
15749 are specified.
15750
15751 @item obj_dir=DIR
15752 [default: @code{"^./^[]^"}]
15753 specifies a directory where to look for object and library files. Multiple
15754 @code{obj_dir} lines can be specified, and they will be searched in the order
15755 they are specified
15756
15757 @item comp_opt=SWITCHES
15758 [default: @code{""}]
15759 creates a variable which can be referred to subsequently by using
15760 the @code{$@{comp_opt@}} notation. This is intended to store the default
15761 switches given to @command{gnatmake} and @command{gcc}.
15762
15763 @item bind_opt=SWITCHES
15764 [default: @code{""}]
15765 creates a variable which can be referred to subsequently by using
15766 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15767 switches given to @command{gnatbind}.
15768
15769 @item link_opt=SWITCHES
15770 [default: @code{""}]
15771 creates a variable which can be referred to subsequently by using
15772 the @samp{$@{link_opt@}} notation. This is intended to store the default
15773 switches given to @command{gnatlink}.
15774
15775 @item main=EXECUTABLE
15776 [default: @code{""}]
15777 specifies the name of the executable for the application. This variable can
15778 be referred to in the following lines by using the @samp{$@{main@}} notation.
15779
15780 @ifset vms
15781 @item comp_cmd=COMMAND
15782 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15783 @end ifset
15784 @ifclear vms
15785 @item comp_cmd=COMMAND
15786 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15787 @end ifclear
15788 specifies the command used to compile a single file in the application.
15789
15790 @ifset vms
15791 @item make_cmd=COMMAND
15792 [default: @code{"GNAT MAKE $@{main@}
15793 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15794 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15795 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15796 @end ifset
15797 @ifclear vms
15798 @item make_cmd=COMMAND
15799 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15800 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15801 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15802 @end ifclear
15803 specifies the command used to recompile the whole application.
15804
15805 @item run_cmd=COMMAND
15806 [default: @code{"$@{main@}"}]
15807 specifies the command used to run the application.
15808
15809 @item debug_cmd=COMMAND
15810 [default: @code{"gdb $@{main@}"}]
15811 specifies the command used to debug the application
15812
15813 @end table
15814
15815 @noindent
15816 @command{gnatxref} and @command{gnatfind} only take into account the
15817 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15818
15819 @node Regular Expressions in gnatfind and gnatxref
15820 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15821
15822 @noindent
15823 As specified in the section about @command{gnatfind}, the pattern can be a
15824 regular expression. Actually, there are to set of regular expressions
15825 which are recognized by the program:
15826
15827 @table @code
15828 @item globbing patterns
15829 These are the most usual regular expression. They are the same that you
15830 generally used in a Unix shell command line, or in a DOS session.
15831
15832 Here is a more formal grammar:
15833 @smallexample
15834 @group
15835 @iftex
15836 @leftskip=.5cm
15837 @end iftex
15838 regexp ::= term
15839 term   ::= elmt            -- matches elmt
15840 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15841 term   ::= *               -- any string of 0 or more characters
15842 term   ::= ?               -- matches any character
15843 term   ::= [char @{char@}]   -- matches any character listed
15844 term   ::= [char - char]   -- matches any character in range
15845 @end group
15846 @end smallexample
15847
15848 @item full regular expression
15849 The second set of regular expressions is much more powerful. This is the
15850 type of regular expressions recognized by utilities such a @file{grep}.
15851
15852 The following is the form of a regular expression, expressed in Ada
15853 reference manual style BNF is as follows
15854
15855 @smallexample
15856 @iftex
15857 @leftskip=.5cm
15858 @end iftex
15859 @group
15860 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15861
15862 term ::= item @{item@}       -- concatenation (item then item)
15863
15864 item ::= elmt              -- match elmt
15865 item ::= elmt *            -- zero or more elmt's
15866 item ::= elmt +            -- one or more elmt's
15867 item ::= elmt ?            -- matches elmt or nothing
15868 @end group
15869 @group
15870 elmt ::= nschar            -- matches given character
15871 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15872 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15873 elmt ::= [char - char]     -- matches chars in given range
15874 elmt ::= \ char            -- matches given character
15875 elmt ::= .                 -- matches any single character
15876 elmt ::= ( regexp )        -- parens used for grouping
15877
15878 char ::= any character, including special characters
15879 nschar ::= any character except ()[].*+?^^^
15880 @end group
15881 @end smallexample
15882
15883 Following are a few examples:
15884
15885 @table @samp
15886 @item abcde|fghi
15887 will match any of the two strings @samp{abcde} and @samp{fghi},
15888
15889 @item abc*d
15890 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15891 @samp{abcccd}, and so on,
15892
15893 @item [a-z]+
15894 will match any string which has only lowercase characters in it (and at
15895 least one character.
15896
15897 @end table
15898 @end table
15899
15900 @node Examples of gnatxref Usage
15901 @section Examples of @code{gnatxref} Usage
15902
15903 @subsection General Usage
15904
15905 @noindent
15906 For the following examples, we will consider the following units:
15907
15908 @smallexample @c ada
15909 @group
15910 @cartouche
15911 main.ads:
15912 1: with Bar;
15913 2: package Main is
15914 3:     procedure Foo (B : in Integer);
15915 4:     C : Integer;
15916 5: private
15917 6:     D : Integer;
15918 7: end Main;
15919
15920 main.adb:
15921 1: package body Main is
15922 2:     procedure Foo (B : in Integer) is
15923 3:     begin
15924 4:        C := B;
15925 5:        D := B;
15926 6:        Bar.Print (B);
15927 7:        Bar.Print (C);
15928 8:     end Foo;
15929 9: end Main;
15930
15931 bar.ads:
15932 1: package Bar is
15933 2:     procedure Print (B : Integer);
15934 3: end bar;
15935 @end cartouche
15936 @end group
15937 @end smallexample
15938
15939 @table @code
15940
15941 @noindent
15942 The first thing to do is to recompile your application (for instance, in
15943 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15944 the cross-referencing information.
15945 You can then issue any of the following commands:
15946
15947 @item gnatxref main.adb
15948 @code{gnatxref} generates cross-reference information for main.adb
15949 and every unit 'with'ed by main.adb.
15950
15951 The output would be:
15952 @smallexample
15953 @iftex
15954 @leftskip=0cm
15955 @end iftex
15956 B                                                      Type: Integer
15957   Decl: bar.ads           2:22
15958 B                                                      Type: Integer
15959   Decl: main.ads          3:20
15960   Body: main.adb          2:20
15961   Ref:  main.adb          4:13     5:13     6:19
15962 Bar                                                    Type: Unit
15963   Decl: bar.ads           1:9
15964   Ref:  main.adb          6:8      7:8
15965        main.ads           1:6
15966 C                                                      Type: Integer
15967   Decl: main.ads          4:5
15968   Modi: main.adb          4:8
15969   Ref:  main.adb          7:19
15970 D                                                      Type: Integer
15971   Decl: main.ads          6:5
15972   Modi: main.adb          5:8
15973 Foo                                                    Type: Unit
15974   Decl: main.ads          3:15
15975   Body: main.adb          2:15
15976 Main                                                    Type: Unit
15977   Decl: main.ads          2:9
15978   Body: main.adb          1:14
15979 Print                                                   Type: Unit
15980   Decl: bar.ads           2:15
15981   Ref:  main.adb          6:12     7:12
15982 @end smallexample
15983
15984 @noindent
15985 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15986 its body is in main.adb, line 1, column 14 and is not referenced any where.
15987
15988 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15989 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15990
15991 @item gnatxref package1.adb package2.ads
15992 @code{gnatxref} will generates cross-reference information for
15993 package1.adb, package2.ads and any other package 'with'ed by any
15994 of these.
15995
15996 @end table
15997
15998 @ifclear vms
15999 @subsection Using gnatxref with vi
16000
16001 @code{gnatxref} can generate a tags file output, which can be used
16002 directly from @command{vi}. Note that the standard version of @command{vi}
16003 will not work properly with overloaded symbols. Consider using another
16004 free implementation of @command{vi}, such as @command{vim}.
16005
16006 @smallexample
16007 $ gnatxref -v gnatfind.adb > tags
16008 @end smallexample
16009
16010 @noindent
16011 will generate the tags file for @code{gnatfind} itself (if the sources
16012 are in the search path!).
16013
16014 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
16015 (replacing @var{entity} by whatever you are looking for), and vi will
16016 display a new file with the corresponding declaration of entity.
16017 @end ifclear
16018
16019 @node Examples of gnatfind Usage
16020 @section Examples of @code{gnatfind} Usage
16021
16022 @table @code
16023
16024 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
16025 Find declarations for all entities xyz referenced at least once in
16026 main.adb. The references are search in every library file in the search
16027 path.
16028
16029 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
16030 switch is set)
16031
16032 The output will look like:
16033 @smallexample
16034 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16035 ^directory/^[directory]^main.adb:24:10: xyz <= body
16036 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16037 @end smallexample
16038
16039 @noindent
16040 that is to say, one of the entities xyz found in main.adb is declared at
16041 line 12 of main.ads (and its body is in main.adb), and another one is
16042 declared at line 45 of foo.ads
16043
16044 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16045 This is the same command as the previous one, instead @code{gnatfind} will
16046 display the content of the Ada source file lines.
16047
16048 The output will look like:
16049
16050 @smallexample
16051 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16052    procedure xyz;
16053 ^directory/^[directory]^main.adb:24:10: xyz <= body
16054    procedure xyz is
16055 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16056    xyz : Integer;
16057 @end smallexample
16058
16059 @noindent
16060 This can make it easier to find exactly the location your are looking
16061 for.
16062
16063 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16064 Find references to all entities containing an x that are
16065 referenced on line 123 of main.ads.
16066 The references will be searched only in main.ads and foo.adb.
16067
16068 @item gnatfind main.ads:123
16069 Find declarations and bodies for all entities that are referenced on
16070 line 123 of main.ads.
16071
16072 This is the same as @code{gnatfind "*":main.adb:123}.
16073
16074 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16075 Find the declaration for the entity referenced at column 45 in
16076 line 123 of file main.adb in directory mydir. Note that it
16077 is usual to omit the identifier name when the column is given,
16078 since the column position identifies a unique reference.
16079
16080 The column has to be the beginning of the identifier, and should not
16081 point to any character in the middle of the identifier.
16082
16083 @end table
16084
16085 @c *********************************
16086 @node The GNAT Pretty-Printer gnatpp
16087 @chapter The GNAT Pretty-Printer @command{gnatpp}
16088 @findex gnatpp
16089 @cindex Pretty-Printer
16090
16091 @noindent
16092 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16093 for source reformatting / pretty-printing.
16094 It takes an Ada source file as input and generates a reformatted
16095 version as output.
16096 You can specify various style directives via switches; e.g.,
16097 identifier case conventions, rules of indentation, and comment layout.
16098
16099 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16100 tree for the input source and thus requires the input to be syntactically and
16101 semantically legal.
16102 If this condition is not met, @command{gnatpp} will terminate with an
16103 error message; no output file will be generated.
16104
16105 If the source files presented to @command{gnatpp} contain
16106 preprocessing directives, then the output file will
16107 correspond to the generated source after all
16108 preprocessing is carried out. There is no way
16109 using @command{gnatpp} to obtain pretty printed files that
16110 include the preprocessing directives.
16111
16112 If the compilation unit
16113 contained in the input source depends semantically upon units located
16114 outside the current directory, you have to provide the source search path
16115 when invoking @command{gnatpp}, if these units are contained in files with
16116 names that do not follow the GNAT file naming rules, you have to provide
16117 the configuration file describing the corresponding naming scheme;
16118 see the description of the @command{gnatpp}
16119 switches below. Another possibility is to use a project file and to
16120 call @command{gnatpp} through the @command{gnat} driver
16121
16122 The @command{gnatpp} command has the form
16123
16124 @smallexample
16125 $ gnatpp @ovar{switches} @var{filename}
16126 @end smallexample
16127
16128 @noindent
16129 where
16130 @itemize @bullet
16131 @item
16132 @var{switches} is an optional sequence of switches defining such properties as
16133 the formatting rules, the source search path, and the destination for the
16134 output source file
16135
16136 @item
16137 @var{filename} is the name (including the extension) of the source file to
16138 reformat; ``wildcards'' or several file names on the same gnatpp command are
16139 allowed.  The file name may contain path information; it does not have to
16140 follow the GNAT file naming rules
16141 @end itemize
16142
16143 @menu
16144 * Switches for gnatpp::
16145 * Formatting Rules::
16146 @end menu
16147
16148 @node Switches for gnatpp
16149 @section Switches for @command{gnatpp}
16150
16151 @noindent
16152 The following subsections describe the various switches accepted by
16153 @command{gnatpp}, organized by category.
16154
16155 @ifclear vms
16156 You specify a switch by supplying a name and generally also a value.
16157 In many cases the values for a switch with a given name are incompatible with
16158 each other
16159 (for example the switch that controls the casing of a reserved word may have
16160 exactly one value: upper case, lower case, or
16161 mixed case) and thus exactly one such switch can be in effect for an
16162 invocation of @command{gnatpp}.
16163 If more than one is supplied, the last one is used.
16164 However, some values for the same switch are mutually compatible.
16165 You may supply several such switches to @command{gnatpp}, but then
16166 each must be specified in full, with both the name and the value.
16167 Abbreviated forms (the name appearing once, followed by each value) are
16168 not permitted.
16169 For example, to set
16170 the alignment of the assignment delimiter both in declarations and in
16171 assignment statements, you must write @option{-A2A3}
16172 (or @option{-A2 -A3}), but not @option{-A23}.
16173 @end ifclear
16174
16175 @ifset vms
16176 In many cases the set of options for a given qualifier are incompatible with
16177 each other (for example the qualifier that controls the casing of a reserved
16178 word may have exactly one option, which specifies either upper case, lower
16179 case, or mixed case), and thus exactly one such option can be in effect for
16180 an invocation of @command{gnatpp}.
16181 If more than one is supplied, the last one is used.
16182 However, some qualifiers have options that are mutually compatible,
16183 and then you may then supply several such options when invoking
16184 @command{gnatpp}.
16185 @end ifset
16186
16187 In most cases, it is obvious whether or not the
16188 ^values for a switch with a given name^options for a given qualifier^
16189 are compatible with each other.
16190 When the semantics might not be evident, the summaries below explicitly
16191 indicate the effect.
16192
16193 @menu
16194 * Alignment Control::
16195 * Casing Control::
16196 * Construct Layout Control::
16197 * General Text Layout Control::
16198 * Other Formatting Options::
16199 * Setting the Source Search Path::
16200 * Output File Control::
16201 * Other gnatpp Switches::
16202 @end menu
16203
16204 @node Alignment Control
16205 @subsection Alignment Control
16206 @cindex Alignment control in @command{gnatpp}
16207
16208 @noindent
16209 Programs can be easier to read if certain constructs are vertically aligned.
16210 By default all alignments are set ON.
16211 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16212 OFF, and then use one or more of the other
16213 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16214 to activate alignment for specific constructs.
16215
16216 @table @option
16217 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16218
16219 @ifset vms
16220 @item /ALIGN=ON
16221 Set all alignments to ON
16222 @end ifset
16223
16224 @item ^-A0^/ALIGN=OFF^
16225 Set all alignments to OFF
16226
16227 @item ^-A1^/ALIGN=COLONS^
16228 Align @code{:} in declarations
16229
16230 @item ^-A2^/ALIGN=DECLARATIONS^
16231 Align @code{:=} in initializations in declarations
16232
16233 @item ^-A3^/ALIGN=STATEMENTS^
16234 Align @code{:=} in assignment statements
16235
16236 @item ^-A4^/ALIGN=ARROWS^
16237 Align @code{=>} in associations
16238
16239 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16240 Align @code{at} keywords in the component clauses in record
16241 representation clauses
16242 @end table
16243
16244 @noindent
16245 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16246 is allowed.
16247
16248 @node Casing Control
16249 @subsection Casing Control
16250 @cindex Casing control in @command{gnatpp}
16251
16252 @noindent
16253 @command{gnatpp} allows you to specify the casing for reserved words,
16254 pragma names, attribute designators and identifiers.
16255 For identifiers you may define a
16256 general rule for name casing but also override this rule
16257 via a set of dictionary files.
16258
16259 Three types of casing are supported: lower case, upper case, and mixed case.
16260 Lower and upper case are self-explanatory (but since some letters in
16261 Latin1 and other GNAT-supported character sets
16262 exist only in lower-case form, an upper case conversion will have no
16263 effect on them.)
16264 ``Mixed case'' means that the first letter, and also each letter immediately
16265 following an underscore, are converted to their uppercase forms;
16266 all the other letters are converted to their lowercase forms.
16267
16268 @table @option
16269 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16270 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16271 Attribute designators are lower case
16272
16273 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16274 Attribute designators are upper case
16275
16276 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16277 Attribute designators are mixed case (this is the default)
16278
16279 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16280 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16281 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16282 lower case (this is the default)
16283
16284 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16285 Keywords are upper case
16286
16287 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16288 @item ^-nD^/NAME_CASING=AS_DECLARED^
16289 Name casing for defining occurrences are as they appear in the source file
16290 (this is the default)
16291
16292 @item ^-nU^/NAME_CASING=UPPER_CASE^
16293 Names are in upper case
16294
16295 @item ^-nL^/NAME_CASING=LOWER_CASE^
16296 Names are in lower case
16297
16298 @item ^-nM^/NAME_CASING=MIXED_CASE^
16299 Names are in mixed case
16300
16301 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16302 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16303 Pragma names are lower case
16304
16305 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16306 Pragma names are upper case
16307
16308 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16309 Pragma names are mixed case (this is the default)
16310
16311 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16312 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16313 Use @var{file} as a @emph{dictionary file} that defines
16314 the casing for a set of specified names,
16315 thereby overriding the effect on these names by
16316 any explicit or implicit
16317 ^-n^/NAME_CASING^ switch.
16318 To supply more than one dictionary file,
16319 use ^several @option{-D} switches^a list of files as options^.
16320
16321 @noindent
16322 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16323 to define the casing for the Ada predefined names and
16324 the names declared in the GNAT libraries.
16325
16326 @item ^-D-^/SPECIFIC_CASING^
16327 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16328 Do not use the default dictionary file;
16329 instead, use the casing
16330 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16331 dictionary file(s)
16332 @end table
16333
16334 @noindent
16335 The structure of a dictionary file, and details on the conventions
16336 used in the default dictionary file, are defined in @ref{Name Casing}.
16337
16338 The @option{^-D-^/SPECIFIC_CASING^} and
16339 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16340 compatible.
16341
16342 @node Construct Layout Control
16343 @subsection Construct Layout Control
16344 @cindex Layout control in @command{gnatpp}
16345
16346 @noindent
16347 This group of @command{gnatpp} switches controls the layout of comments and
16348 complex syntactic constructs.  See @ref{Formatting Comments} for details
16349 on their effect.
16350
16351 @table @option
16352 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16353 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16354 All the comments remain unchanged
16355
16356 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16357 GNAT-style comment line indentation (this is the default).
16358
16359 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16360 Reference-manual comment line indentation.
16361
16362 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16363 GNAT-style comment beginning
16364
16365 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16366 Reformat comment blocks
16367
16368 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16369 Keep unchanged special form comments
16370
16371 Reformat comment blocks
16372
16373 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16374 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16375 GNAT-style layout (this is the default)
16376
16377 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16378 Compact layout
16379
16380 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16381 Uncompact layout
16382
16383 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16384 @item ^-N^/NOTABS^
16385 All the VT characters are removed from the comment text. All the HT characters
16386 are expanded with the sequences of space characters to get to the next tab
16387 stops.
16388
16389 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16390 @item ^--no-separate-is^/NO_SEPARATE_IS^
16391 Do not place the keyword @code{is} on a separate line in a subprogram body in
16392 case if the spec occupies more then one line.
16393
16394 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16395 @item ^--separate-label^/SEPARATE_LABEL^
16396 Place statement label(s) on a separate line, with the following statement
16397 on the next line.
16398
16399 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16400 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16401 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16402 keyword @code{then} in IF statements on a separate line.
16403
16404 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16405 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16406 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16407 keyword @code{then} in IF statements on a separate line. This option is
16408 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16409
16410 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16411 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16412 Start each USE clause in a context clause from a separate line.
16413
16414 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16415 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16416 Use a separate line for a loop or block statement name, but do not use an extra
16417 indentation level for the statement itself.
16418
16419 @end table
16420
16421 @ifclear vms
16422 @noindent
16423 The @option{-c1} and @option{-c2} switches are incompatible.
16424 The @option{-c3} and @option{-c4} switches are compatible with each other and
16425 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16426 the other comment formatting switches.
16427
16428 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16429 @end ifclear
16430
16431 @ifset vms
16432 @noindent
16433 For the @option{/COMMENTS_LAYOUT} qualifier:
16434 @itemize @bullet
16435 @item
16436 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16437 @item
16438 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16439 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16440 @end itemize
16441
16442 @noindent
16443 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16444 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16445 @end ifset
16446
16447 @node General Text Layout Control
16448 @subsection General Text Layout Control
16449
16450 @noindent
16451 These switches allow control over line length and indentation.
16452
16453 @table @option
16454 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16455 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16456 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16457
16458 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16459 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16460 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16461
16462 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16463 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16464 Indentation level for continuation lines (relative to the line being
16465 continued), @var{nnn} from 1@dots{}9.
16466 The default
16467 value is one less then the (normal) indentation level, unless the
16468 indentation is set to 1 (in which case the default value for continuation
16469 line indentation is also 1)
16470 @end table
16471
16472 @node Other Formatting Options
16473 @subsection Other Formatting Options
16474
16475 @noindent
16476 These switches control the inclusion of missing end/exit labels, and
16477 the indentation level in @b{case} statements.
16478
16479 @table @option
16480 @item ^-e^/NO_MISSED_LABELS^
16481 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16482 Do not insert missing end/exit labels. An end label is the name of
16483 a construct that may optionally be repeated at the end of the
16484 construct's declaration;
16485 e.g., the names of packages, subprograms, and tasks.
16486 An exit label is the name of a loop that may appear as target
16487 of an exit statement within the loop.
16488 By default, @command{gnatpp} inserts these end/exit labels when
16489 they are absent from the original source. This option suppresses such
16490 insertion, so that the formatted source reflects the original.
16491
16492 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16493 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16494 Insert a Form Feed character after a pragma Page.
16495
16496 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16497 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16498 Do not use an additional indentation level for @b{case} alternatives
16499 and variants if there are @var{nnn} or more (the default
16500 value is 10).
16501 If @var{nnn} is 0, an additional indentation level is
16502 used for @b{case} alternatives and variants regardless of their number.
16503 @end table
16504
16505 @node Setting the Source Search Path
16506 @subsection Setting the Source Search Path
16507
16508 @noindent
16509 To define the search path for the input source file, @command{gnatpp}
16510 uses the same switches as the GNAT compiler, with the same effects.
16511
16512 @table @option
16513 @item ^-I^/SEARCH=^@var{dir}
16514 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16515 The same as the corresponding gcc switch
16516
16517 @item ^-I-^/NOCURRENT_DIRECTORY^
16518 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16519 The same as the corresponding gcc switch
16520
16521 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16522 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16523 The same as the corresponding gcc switch
16524
16525 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16526 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16527 The same as the corresponding gcc switch
16528
16529 @end table
16530
16531 @node Output File Control
16532 @subsection Output File Control
16533
16534 @noindent
16535 By default the output is sent to the file whose name is obtained by appending
16536 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16537 (if the file with this name already exists, it is unconditionally overwritten).
16538 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16539 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16540 as output file.
16541 The output may be redirected by the following switches:
16542
16543 @table @option
16544 @item ^-pipe^/STANDARD_OUTPUT^
16545 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16546 Send the output to @code{Standard_Output}
16547
16548 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16549 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16550 Write the output into @var{output_file}.
16551 If @var{output_file} already exists, @command{gnatpp} terminates without
16552 reading or processing the input file.
16553
16554 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16555 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16556 Write the output into @var{output_file}, overwriting the existing file
16557 (if one is present).
16558
16559 @item ^-r^/REPLACE^
16560 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16561 Replace the input source file with the reformatted output, and copy the
16562 original input source into the file whose name is obtained by appending the
16563 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16564 If a file with this name already exists, @command{gnatpp} terminates without
16565 reading or processing the input file.
16566
16567 @item ^-rf^/OVERRIDING_REPLACE^
16568 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16569 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16570 already exists, it is overwritten.
16571
16572 @item ^-rnb^/REPLACE_NO_BACKUP^
16573 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16574 Replace the input source file with the reformatted output without
16575 creating any backup copy of the input source.
16576
16577 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16578 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16579 Specifies the format of the reformatted output file. The @var{xxx}
16580 ^string specified with the switch^option^ may be either
16581 @itemize @bullet
16582 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16583 @item ``@option{^crlf^CRLF^}''
16584 the same as @option{^crlf^CRLF^}
16585 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16586 @item ``@option{^lf^LF^}''
16587 the same as @option{^unix^UNIX^}
16588 @end itemize
16589
16590 @item ^-W^/RESULT_ENCODING=^@var{e}
16591 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16592 Specify the wide character encoding method used to write the code in the
16593 result file
16594 @var{e} is one of the following:
16595
16596 @itemize @bullet
16597
16598 @item ^h^HEX^
16599 Hex encoding
16600
16601 @item ^u^UPPER^
16602 Upper half encoding
16603
16604 @item ^s^SHIFT_JIS^
16605 Shift/JIS encoding
16606
16607 @item ^e^EUC^
16608 EUC encoding
16609
16610 @item ^8^UTF8^
16611 UTF-8 encoding
16612
16613 @item ^b^BRACKETS^
16614 Brackets encoding (default value)
16615 @end itemize
16616
16617 @end table
16618
16619 @noindent
16620 Options @option{^-pipe^/STANDARD_OUTPUT^},
16621 @option{^-o^/OUTPUT^} and
16622 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16623 contains only one file to reformat.
16624 Option
16625 @option{^--eol^/END_OF_LINE^}
16626 and
16627 @option{^-W^/RESULT_ENCODING^}
16628 cannot be used together
16629 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16630
16631 @node Other gnatpp Switches
16632 @subsection Other @code{gnatpp} Switches
16633
16634 @noindent
16635 The additional @command{gnatpp} switches are defined in this subsection.
16636
16637 @table @option
16638 @item ^-files @var{filename}^/FILES=@var{output_file}^
16639 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16640 Take the argument source files from the specified file. This file should be an
16641 ordinary textual file containing file names separated by spaces or
16642 line breaks. You can use this switch more then once in the same call to
16643 @command{gnatpp}. You also can combine this switch with explicit list of
16644 files.
16645
16646 @item ^-v^/VERBOSE^
16647 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16648 Verbose mode;
16649 @command{gnatpp} generates version information and then
16650 a trace of the actions it takes to produce or obtain the ASIS tree.
16651
16652 @item ^-w^/WARNINGS^
16653 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16654 Warning mode;
16655 @command{gnatpp} generates a warning whenever it cannot provide
16656 a required layout in the result source.
16657 @end table
16658
16659 @node Formatting Rules
16660 @section Formatting Rules
16661
16662 @noindent
16663 The following subsections show how @command{gnatpp} treats ``white space'',
16664 comments, program layout, and name casing.
16665 They provide the detailed descriptions of the switches shown above.
16666
16667 @menu
16668 * White Space and Empty Lines::
16669 * Formatting Comments::
16670 * Construct Layout::
16671 * Name Casing::
16672 @end menu
16673
16674 @node White Space and Empty Lines
16675 @subsection White Space and Empty Lines
16676
16677 @noindent
16678 @command{gnatpp} does not have an option to control space characters.
16679 It will add or remove spaces according to the style illustrated by the
16680 examples in the @cite{Ada Reference Manual}.
16681
16682 The only format effectors
16683 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16684 that will appear in the output file are platform-specific line breaks,
16685 and also format effectors within (but not at the end of) comments.
16686 In particular, each horizontal tab character that is not inside
16687 a comment will be treated as a space and thus will appear in the
16688 output file as zero or more spaces depending on
16689 the reformatting of the line in which it appears.
16690 The only exception is a Form Feed character, which is inserted after a
16691 pragma @code{Page} when @option{-ff} is set.
16692
16693 The output file will contain no lines with trailing ``white space'' (spaces,
16694 format effectors).
16695
16696 Empty lines in the original source are preserved
16697 only if they separate declarations or statements.
16698 In such contexts, a
16699 sequence of two or more empty lines is replaced by exactly one empty line.
16700 Note that a blank line will be removed if it separates two ``comment blocks''
16701 (a comment block is a sequence of whole-line comments).
16702 In order to preserve a visual separation between comment blocks, use an
16703 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16704 Likewise, if for some reason you wish to have a sequence of empty lines,
16705 use a sequence of empty comments instead.
16706
16707 @node Formatting Comments
16708 @subsection Formatting Comments
16709
16710 @noindent
16711 Comments in Ada code are of two kinds:
16712 @itemize @bullet
16713 @item
16714 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16715 ``white space'') on a line
16716
16717 @item
16718 an @emph{end-of-line comment}, which follows some other Ada lexical element
16719 on the same line.
16720 @end itemize
16721
16722 @noindent
16723 The indentation of a whole-line comment is that of either
16724 the preceding or following line in
16725 the formatted source, depending on switch settings as will be described below.
16726
16727 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16728 between the end of the preceding Ada lexical element and the beginning
16729 of the comment as appear in the original source,
16730 unless either the comment has to be split to
16731 satisfy the line length limitation, or else the next line contains a
16732 whole line comment that is considered a continuation of this end-of-line
16733 comment (because it starts at the same position).
16734 In the latter two
16735 cases, the start of the end-of-line comment is moved right to the nearest
16736 multiple of the indentation level.
16737 This may result in a ``line overflow'' (the right-shifted comment extending
16738 beyond the maximum line length), in which case the comment is split as
16739 described below.
16740
16741 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16742 (GNAT-style comment line indentation)
16743 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16744 (reference-manual comment line indentation).
16745 With reference-manual style, a whole-line comment is indented as if it
16746 were a declaration or statement at the same place
16747 (i.e., according to the indentation of the preceding line(s)).
16748 With GNAT style, a whole-line comment that is immediately followed by an
16749 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16750 word @b{begin}, is indented based on the construct that follows it.
16751
16752 For example:
16753 @smallexample @c ada
16754 @cartouche
16755 if A then
16756     null;
16757        -- some comment
16758 else
16759    null;
16760 end if;
16761 @end cartouche
16762 @end smallexample
16763
16764 @noindent
16765 Reference-manual indentation produces:
16766
16767 @smallexample @c ada
16768 @cartouche
16769 if A then
16770    null;
16771    --  some comment
16772 else
16773    null;
16774 end if;
16775 @end cartouche
16776 @end smallexample
16777
16778 @noindent
16779 while GNAT-style indentation produces:
16780
16781 @smallexample @c ada
16782 @cartouche
16783 if A then
16784    null;
16785 --  some comment
16786 else
16787    null;
16788 end if;
16789 @end cartouche
16790 @end smallexample
16791
16792 @noindent
16793 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16794 (GNAT style comment beginning) has the following
16795 effect:
16796
16797 @itemize @bullet
16798 @item
16799 For each whole-line comment that does not end with two hyphens,
16800 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16801 to ensure that there are at least two spaces between these hyphens and the
16802 first non-blank character of the comment.
16803 @end itemize
16804
16805 @noindent
16806 For an end-of-line comment, if in the original source the next line is a
16807 whole-line comment that starts at the same position
16808 as the end-of-line comment,
16809 then the whole-line comment (and all whole-line comments
16810 that follow it and that start at the same position)
16811 will start at this position in the output file.
16812
16813 @noindent
16814 That is, if in the original source we have:
16815
16816 @smallexample @c ada
16817 @cartouche
16818 begin
16819 A := B + C;            --  B must be in the range Low1..High1
16820                        --  C must be in the range Low2..High2
16821              --B+C will be in the range Low1+Low2..High1+High2
16822 X := X + 1;
16823 @end cartouche
16824 @end smallexample
16825
16826 @noindent
16827 Then in the formatted source we get
16828
16829 @smallexample @c ada
16830 @cartouche
16831 begin
16832    A := B + C;            --  B must be in the range Low1..High1
16833                           --  C must be in the range Low2..High2
16834    --  B+C will be in the range Low1+Low2..High1+High2
16835    X := X + 1;
16836 @end cartouche
16837 @end smallexample
16838
16839 @noindent
16840 A comment that exceeds the line length limit will be split.
16841 Unless switch
16842 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16843 the line belongs to a reformattable block, splitting the line generates a
16844 @command{gnatpp} warning.
16845 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16846 comments may be reformatted in typical
16847 word processor style (that is, moving words between lines and putting as
16848 many words in a line as possible).
16849
16850 @noindent
16851 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16852 that has a special format (that is, a character that is neither a letter nor digit
16853 not white space nor line break immediately following the leading @code{--} of
16854 the comment) should be without any change moved from the argument source
16855 into reformatted source. This switch allows to preserve comments that are used
16856 as a special marks in the code (e.g.@: SPARK annotation).
16857
16858 @node Construct Layout
16859 @subsection Construct Layout
16860
16861 @noindent
16862 In several cases the suggested layout in the Ada Reference Manual includes
16863 an extra level of indentation that many programmers prefer to avoid. The
16864 affected cases include:
16865
16866 @itemize @bullet
16867
16868 @item Record type declaration (RM 3.8)
16869
16870 @item Record representation clause (RM 13.5.1)
16871
16872 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16873
16874 @item Block statement in case if a block has a statement identifier (RM 5.6)
16875 @end itemize
16876
16877 @noindent
16878 In compact mode (when GNAT style layout or compact layout is set),
16879 the pretty printer uses one level of indentation instead
16880 of two. This is achieved in the record definition and record representation
16881 clause cases by putting the @code{record} keyword on the same line as the
16882 start of the declaration or representation clause, and in the block and loop
16883 case by putting the block or loop header on the same line as the statement
16884 identifier.
16885
16886 @noindent
16887 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16888 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16889 layout on the one hand, and uncompact layout
16890 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16891 can be illustrated by the following examples:
16892
16893 @iftex
16894 @cartouche
16895 @multitable @columnfractions .5 .5
16896 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16897
16898 @item
16899 @smallexample @c ada
16900 type q is record
16901    a : integer;
16902    b : integer;
16903 end record;
16904 @end smallexample
16905 @tab
16906 @smallexample @c ada
16907 type q is
16908    record
16909       a : integer;
16910       b : integer;
16911    end record;
16912 @end smallexample
16913
16914 @item
16915 @smallexample @c ada
16916 for q use record
16917    a at 0 range  0 .. 31;
16918    b at 4 range  0 .. 31;
16919 end record;
16920 @end smallexample
16921 @tab
16922 @smallexample @c ada
16923 for q use
16924    record
16925       a at 0 range  0 .. 31;
16926       b at 4 range  0 .. 31;
16927    end record;
16928 @end smallexample
16929
16930 @item
16931 @smallexample @c ada
16932 Block : declare
16933    A : Integer := 3;
16934 begin
16935    Proc (A, A);
16936 end Block;
16937 @end smallexample
16938 @tab
16939 @smallexample @c ada
16940 Block :
16941    declare
16942       A : Integer := 3;
16943    begin
16944       Proc (A, A);
16945    end Block;
16946 @end smallexample
16947
16948 @item
16949 @smallexample @c ada
16950 Clear : for J in 1 .. 10 loop
16951    A (J) := 0;
16952 end loop Clear;
16953 @end smallexample
16954 @tab
16955 @smallexample @c ada
16956 Clear :
16957    for J in 1 .. 10 loop
16958       A (J) := 0;
16959    end loop Clear;
16960 @end smallexample
16961 @end multitable
16962 @end cartouche
16963 @end iftex
16964
16965 @ifnottex
16966 @smallexample
16967 @cartouche
16968 GNAT style, compact layout              Uncompact layout
16969
16970 type q is record                        type q is
16971    a : integer;                            record
16972    b : integer;                               a : integer;
16973 end record;                                   b : integer;
16974                                            end record;
16975
16976 for q use record                        for q use
16977    a at 0 range  0 .. 31;                  record
16978    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16979 end record;                                   b at 4 range  0 .. 31;
16980                                            end record;
16981
16982 Block : declare                         Block :
16983    A : Integer := 3;                       declare
16984 begin                                         A : Integer := 3;
16985    Proc (A, A);                            begin
16986 end Block;                                    Proc (A, A);
16987                                            end Block;
16988
16989 Clear : for J in 1 .. 10 loop           Clear :
16990    A (J) := 0;                             for J in 1 .. 10 loop
16991 end loop Clear;                               A (J) := 0;
16992                                            end loop Clear;
16993 @end cartouche
16994 @end smallexample
16995 @end ifnottex
16996
16997 @noindent
16998 A further difference between GNAT style layout and compact layout is that
16999 GNAT style layout inserts empty lines as separation for
17000 compound statements, return statements and bodies.
17001
17002 Note that the layout specified by
17003 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
17004 for named block and loop statements overrides the layout defined by these
17005 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
17006 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
17007 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
17008
17009 @node Name Casing
17010 @subsection Name Casing
17011
17012 @noindent
17013 @command{gnatpp} always converts the usage occurrence of a (simple) name to
17014 the same casing as the corresponding defining identifier.
17015
17016 You control the casing for defining occurrences via the
17017 @option{^-n^/NAME_CASING^} switch.
17018 @ifclear vms
17019 With @option{-nD} (``as declared'', which is the default),
17020 @end ifclear
17021 @ifset vms
17022 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
17023 @end ifset
17024 defining occurrences appear exactly as in the source file
17025 where they are declared.
17026 The other ^values for this switch^options for this qualifier^ ---
17027 @option{^-nU^UPPER_CASE^},
17028 @option{^-nL^LOWER_CASE^},
17029 @option{^-nM^MIXED_CASE^} ---
17030 result in
17031 ^upper, lower, or mixed case, respectively^the corresponding casing^.
17032 If @command{gnatpp} changes the casing of a defining
17033 occurrence, it analogously changes the casing of all the
17034 usage occurrences of this name.
17035
17036 If the defining occurrence of a name is not in the source compilation unit
17037 currently being processed by @command{gnatpp}, the casing of each reference to
17038 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
17039 switch (subject to the dictionary file mechanism described below).
17040 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17041 had affected the
17042 casing for the defining occurrence of the name.
17043
17044 Some names may need to be spelled with casing conventions that are not
17045 covered by the upper-, lower-, and mixed-case transformations.
17046 You can arrange correct casing by placing such names in a
17047 @emph{dictionary file},
17048 and then supplying a @option{^-D^/DICTIONARY^} switch.
17049 The casing of names from dictionary files overrides
17050 any @option{^-n^/NAME_CASING^} switch.
17051
17052 To handle the casing of Ada predefined names and the names from GNAT libraries,
17053 @command{gnatpp} assumes a default dictionary file.
17054 The name of each predefined entity is spelled with the same casing as is used
17055 for the entity in the @cite{Ada Reference Manual}.
17056 The name of each entity in the GNAT libraries is spelled with the same casing
17057 as is used in the declaration of that entity.
17058
17059 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17060 default dictionary file.
17061 Instead, the casing for predefined and GNAT-defined names will be established
17062 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17063 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17064 will appear as just shown,
17065 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17066 To ensure that even such names are rendered in uppercase,
17067 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17068 (or else, less conveniently, place these names in upper case in a dictionary
17069 file).
17070
17071 A dictionary file is
17072 a plain text file; each line in this file can be either a blank line
17073 (containing only space characters and ASCII.HT characters), an Ada comment
17074 line, or the specification of exactly one @emph{casing schema}.
17075
17076 A casing schema is a string that has the following syntax:
17077
17078 @smallexample
17079 @cartouche
17080   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17081
17082   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17083 @end cartouche
17084 @end smallexample
17085
17086 @noindent
17087 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17088 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17089
17090 The casing schema string can be followed by white space and/or an Ada-style
17091 comment; any amount of white space is allowed before the string.
17092
17093 If a dictionary file is passed as
17094 @ifclear vms
17095 the value of a @option{-D@var{file}} switch
17096 @end ifclear
17097 @ifset vms
17098 an option to the @option{/DICTIONARY} qualifier
17099 @end ifset
17100 then for every
17101 simple name and every identifier, @command{gnatpp} checks if the dictionary
17102 defines the casing for the name or for some of its parts (the term ``subword''
17103 is used below to denote the part of a name which is delimited by ``_'' or by
17104 the beginning or end of the word and which does not contain any ``_'' inside):
17105
17106 @itemize @bullet
17107 @item
17108 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17109 the casing defined by the dictionary; no subwords are checked for this word
17110
17111 @item
17112 for every subword @command{gnatpp} checks if the dictionary contains the
17113 corresponding string of the form @code{*@var{simple_identifier}*},
17114 and if it does, the casing of this @var{simple_identifier} is used
17115 for this subword
17116
17117 @item
17118 if the whole name does not contain any ``_'' inside, and if for this name
17119 the dictionary contains two entries - one of the form @var{identifier},
17120 and another - of the form *@var{simple_identifier}*, then the first one
17121 is applied to define the casing of this name
17122
17123 @item
17124 if more than one dictionary file is passed as @command{gnatpp} switches, each
17125 dictionary adds new casing exceptions and overrides all the existing casing
17126 exceptions set by the previous dictionaries
17127
17128 @item
17129 when @command{gnatpp} checks if the word or subword is in the dictionary,
17130 this check is not case sensitive
17131 @end itemize
17132
17133 @noindent
17134 For example, suppose we have the following source to reformat:
17135
17136 @smallexample @c ada
17137 @cartouche
17138 procedure test is
17139    name1 : integer := 1;
17140    name4_name3_name2 : integer := 2;
17141    name2_name3_name4 : Boolean;
17142    name1_var : Float;
17143 begin
17144    name2_name3_name4 := name4_name3_name2 > name1;
17145 end;
17146 @end cartouche
17147 @end smallexample
17148
17149 @noindent
17150 And suppose we have two dictionaries:
17151
17152 @smallexample
17153 @cartouche
17154 @i{dict1:}
17155    NAME1
17156    *NaMe3*
17157    *Name1*
17158 @end cartouche
17159
17160 @cartouche
17161 @i{dict2:}
17162   *NAME3*
17163 @end cartouche
17164 @end smallexample
17165
17166 @noindent
17167 If @command{gnatpp} is called with the following switches:
17168
17169 @smallexample
17170 @ifclear vms
17171 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17172 @end ifclear
17173 @ifset vms
17174 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17175 @end ifset
17176 @end smallexample
17177
17178 @noindent
17179 then we will get the following name casing in the @command{gnatpp} output:
17180
17181 @smallexample @c ada
17182 @cartouche
17183 procedure Test is
17184    NAME1             : Integer := 1;
17185    Name4_NAME3_Name2 : Integer := 2;
17186    Name2_NAME3_Name4 : Boolean;
17187    Name1_Var         : Float;
17188 begin
17189    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17190 end Test;
17191 @end cartouche
17192 @end smallexample
17193
17194 @c *********************************
17195 @node The GNAT Metric Tool gnatmetric
17196 @chapter The GNAT Metric Tool @command{gnatmetric}
17197 @findex gnatmetric
17198 @cindex Metric tool
17199
17200 @noindent
17201 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17202 for computing various program metrics.
17203 It takes an Ada source file as input and generates a file containing the
17204 metrics data as output. Various switches control which
17205 metrics are computed and output.
17206
17207 @command{gnatmetric} generates and uses the ASIS
17208 tree for the input source and thus requires the input to be syntactically and
17209 semantically legal.
17210 If this condition is not met, @command{gnatmetric} will generate
17211 an error message; no metric information for this file will be
17212 computed and reported.
17213
17214 If the compilation unit contained in the input source depends semantically
17215 upon units in files located outside the current directory, you have to provide
17216 the source search path when invoking @command{gnatmetric}.
17217 If it depends semantically upon units that are contained
17218 in files with names that do not follow the GNAT file naming rules, you have to
17219 provide the configuration file describing the corresponding naming scheme (see
17220 the description of the @command{gnatmetric} switches below.)
17221 Alternatively, you may use a project file and invoke @command{gnatmetric}
17222 through the @command{gnat} driver.
17223
17224 The @command{gnatmetric} command has the form
17225
17226 @smallexample
17227 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17228 @end smallexample
17229
17230 @noindent
17231 where
17232 @itemize @bullet
17233 @item
17234 @var{switches} specify the metrics to compute and define the destination for
17235 the output
17236
17237 @item
17238 Each @var{filename} is the name (including the extension) of a source
17239 file to process. ``Wildcards'' are allowed, and
17240 the file name may contain path information.
17241 If no @var{filename} is supplied, then the @var{switches} list must contain
17242 at least one
17243 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17244 Including both a @option{-files} switch and one or more
17245 @var{filename} arguments is permitted.
17246
17247 @item
17248 @samp{-cargs @var{gcc_switches}} is a list of switches for
17249 @command{gcc}. They will be passed on to all compiler invocations made by
17250 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17251 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17252 and use the @option{-gnatec} switch to set the configuration file.
17253 @end itemize
17254
17255 @menu
17256 * Switches for gnatmetric::
17257 @end menu
17258
17259 @node Switches for gnatmetric
17260 @section Switches for @command{gnatmetric}
17261
17262 @noindent
17263 The following subsections describe the various switches accepted by
17264 @command{gnatmetric}, organized by category.
17265
17266 @menu
17267 * Output Files Control::
17268 * Disable Metrics For Local Units::
17269 * Specifying a set of metrics to compute::
17270 * Other gnatmetric Switches::
17271 * Generate project-wide metrics::
17272 @end menu
17273
17274 @node Output Files Control
17275 @subsection Output File Control
17276 @cindex Output file control in @command{gnatmetric}
17277
17278 @noindent
17279 @command{gnatmetric} has two output formats. It can generate a
17280 textual (human-readable) form, and also XML. By default only textual
17281 output is generated.
17282
17283 When generating the output in textual form, @command{gnatmetric} creates
17284 for each Ada source file a corresponding text file
17285 containing the computed metrics, except for the case when the set of metrics
17286 specified by gnatmetric parameters consists only of metrics that are computed
17287 for the whole set of analyzed sources, but not for each Ada source.
17288 By default, this file is placed in the same directory as where the source
17289 file is located, and its name is obtained
17290 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17291 input file.
17292
17293 All the output information generated in XML format is placed in a single
17294 file. By default this file is placed in the current directory and has the
17295 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17296
17297 Some of the computed metrics are summed over the units passed to
17298 @command{gnatmetric}; for example, the total number of lines of code.
17299 By default this information is sent to @file{stdout}, but a file
17300 can be specified with the @option{-og} switch.
17301
17302 The following switches control the @command{gnatmetric} output:
17303
17304 @table @option
17305 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17306 @item ^-x^/XML^
17307 Generate the XML output
17308
17309 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17310 @item ^-xs^/XSD^
17311 Generate the XML output and the XML schema file that describes the structure
17312 of the XML metric report, this schema is assigned to the XML file. The schema
17313 file has the same name as the XML output file with @file{.xml} suffix replaced
17314 with @file{.xsd}
17315
17316 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17317 @item ^-nt^/NO_TEXT^
17318 Do not generate the output in text form (implies @option{^-x^/XML^})
17319
17320 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17321 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17322 Put textual files with detailed metrics into @var{output_dir}
17323
17324 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17325 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17326 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17327 in the name of the output file.
17328
17329 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17330 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17331 Put global metrics into @var{file_name}
17332
17333 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17334 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17335 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17336
17337 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17338 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17339 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17340 output includes the name(s) of the Ada source file(s) from which the metrics
17341 are computed.  By default each name includes the absolute path. The
17342 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17343 to exclude all directory information from the file names that are output.)
17344
17345 @end table
17346
17347 @node Disable Metrics For Local Units
17348 @subsection Disable Metrics For Local Units
17349 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17350
17351 @noindent
17352 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17353 one compilation
17354 unit per one source file. It computes line metrics for the whole source
17355 file, and it also computes syntax
17356 and complexity metrics for the file's outermost unit.
17357
17358 By default, @command{gnatmetric} will also compute all metrics for certain
17359 kinds of locally declared program units:
17360
17361 @itemize @bullet
17362 @item
17363 subprogram (and generic subprogram) bodies;
17364
17365 @item
17366 package (and generic package) specs and bodies;
17367
17368 @item
17369 task object and type specifications and bodies;
17370
17371 @item
17372 protected object and type specifications and bodies.
17373 @end itemize
17374
17375 @noindent
17376 These kinds of entities will be referred to as
17377 @emph{eligible local program units}, or simply @emph{eligible local units},
17378 @cindex Eligible local unit (for @command{gnatmetric})
17379 in the discussion below.
17380
17381 Note that a subprogram declaration, generic instantiation,
17382 or renaming declaration only receives metrics
17383 computation when it appear as the outermost entity
17384 in a source file.
17385
17386 Suppression of metrics computation for eligible local units can be
17387 obtained via the following switch:
17388
17389 @table @option
17390 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17391 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17392 Do not compute detailed metrics for eligible local program units
17393
17394 @end table
17395
17396 @node Specifying a set of metrics to compute
17397 @subsection Specifying a set of metrics to compute
17398
17399 @noindent
17400 By default all the metrics are computed and reported. The switches
17401 described in this subsection allow you to control, on an individual
17402 basis, whether metrics are computed and
17403 reported. If at least one positive metric
17404 switch is specified (that is, a switch that defines that a given
17405 metric or set of metrics is to be computed), then only
17406 explicitly specified metrics are reported.
17407
17408 @menu
17409 * Line Metrics Control::
17410 * Syntax Metrics Control::
17411 * Complexity Metrics Control::
17412 * Object-Oriented Metrics Control::
17413 @end menu
17414
17415 @node Line Metrics Control
17416 @subsubsection Line Metrics Control
17417 @cindex Line metrics control in @command{gnatmetric}
17418
17419 @noindent
17420 For any (legal) source file, and for each of its
17421 eligible local program units, @command{gnatmetric} computes the following
17422 metrics:
17423
17424 @itemize @bullet
17425 @item
17426 the total number of lines;
17427
17428 @item
17429 the total number of code lines (i.e., non-blank lines that are not comments)
17430
17431 @item
17432 the number of comment lines
17433
17434 @item
17435 the number of code lines containing end-of-line comments;
17436
17437 @item
17438 the comment percentage: the ratio between the number of lines that contain
17439 comments and the number of all non-blank lines, expressed as a percentage;
17440
17441 @item
17442 the number of empty lines and lines containing only space characters and/or
17443 format effectors (blank lines)
17444
17445 @item
17446 the average number of code lines in subprogram bodies, task bodies, entry
17447 bodies and statement sequences in package bodies (this metric is only computed
17448 across the whole set of the analyzed units)
17449
17450 @end itemize
17451
17452 @noindent
17453 @command{gnatmetric} sums the values of the line metrics for all the
17454 files being processed and then generates the cumulative results. The tool
17455 also computes for all the files being processed the average number of code
17456 lines in bodies.
17457
17458 You can use the following switches to select the specific line metrics
17459 to be computed and reported.
17460
17461 @table @option
17462 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17463
17464 @ifclear vms
17465 @cindex @option{--no-lines@var{x}}
17466 @end ifclear
17467
17468 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17469 Report all the line metrics
17470
17471 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17472 Do not report any of line metrics
17473
17474 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17475 Report the number of all lines
17476
17477 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17478 Do not report the number of all lines
17479
17480 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17481 Report the number of code lines
17482
17483 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17484 Do not report the number of code lines
17485
17486 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17487 Report the number of comment lines
17488
17489 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17490 Do not report the number of comment lines
17491
17492 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17493 Report the number of code lines containing
17494 end-of-line comments
17495
17496 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17497 Do not report the number of code lines containing
17498 end-of-line comments
17499
17500 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17501 Report the comment percentage in the program text
17502
17503 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17504 Do not report the comment percentage in the program text
17505
17506 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17507 Report the number of blank lines
17508
17509 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17510 Do not report the number of blank lines
17511
17512 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17513 Report the average number of code lines in subprogram bodies, task bodies,
17514 entry bodies and statement sequences in package bodies. The metric is computed
17515 and reported for the whole set of processed Ada sources only.
17516
17517 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17518 Do not report the average number of code lines in subprogram bodies,
17519 task bodies, entry bodies and statement sequences in package bodies.
17520
17521 @end table
17522
17523 @node Syntax Metrics Control
17524 @subsubsection Syntax Metrics Control
17525 @cindex Syntax metrics control in @command{gnatmetric}
17526
17527 @noindent
17528 @command{gnatmetric} computes various syntactic metrics for the
17529 outermost unit and for each eligible local unit:
17530
17531 @table @emph
17532 @item LSLOC (``Logical Source Lines Of Code'')
17533 The total number of declarations and the total number of statements
17534
17535 @item Maximal static nesting level of inner program units
17536 According to
17537 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17538 package, a task unit, a protected unit, a
17539 protected entry, a generic unit, or an explicitly declared subprogram other
17540 than an enumeration literal.''
17541
17542 @item Maximal nesting level of composite syntactic constructs
17543 This corresponds to the notion of the
17544 maximum nesting level in the GNAT built-in style checks
17545 (@pxref{Style Checking})
17546 @end table
17547
17548 @noindent
17549 For the outermost unit in the file, @command{gnatmetric} additionally computes
17550 the following metrics:
17551
17552 @table @emph
17553 @item Public subprograms
17554 This metric is computed for package specs. It is the
17555 number of subprograms and generic subprograms declared in the visible
17556 part (including the visible part of nested packages, protected objects, and
17557 protected types).
17558
17559 @item All subprograms
17560 This metric is computed for bodies and subunits. The
17561 metric is equal to a total number of subprogram bodies in the compilation
17562 unit.
17563 Neither generic instantiations nor renamings-as-a-body nor body stubs
17564 are counted. Any subprogram body is counted, independently of its nesting
17565 level and enclosing constructs. Generic bodies and bodies of protected
17566 subprograms are counted in the same way as ``usual'' subprogram bodies.
17567
17568 @item Public types
17569 This metric is computed for package specs and
17570 generic package declarations. It is the total number of types
17571 that can be referenced from outside this compilation unit, plus the
17572 number of types from all the visible parts of all the visible generic
17573 packages. Generic formal types are not counted.  Only types, not subtypes,
17574 are included.
17575
17576 @noindent
17577 Along with the total number of public types, the following
17578 types are counted and reported separately:
17579
17580 @itemize @bullet
17581 @item
17582 Abstract types
17583
17584 @item
17585 Root tagged types (abstract, non-abstract, private, non-private). Type
17586 extensions are @emph{not} counted
17587
17588 @item
17589 Private types (including private extensions)
17590
17591 @item
17592 Task types
17593
17594 @item
17595 Protected types
17596
17597 @end itemize
17598
17599 @item All types
17600 This metric is computed for any compilation unit. It is equal to the total
17601 number of the declarations of different types given in the compilation unit.
17602 The private and the corresponding full type declaration are counted as one
17603 type declaration. Incomplete type declarations and generic formal types
17604 are not counted.
17605 No distinction is made among different kinds of types (abstract,
17606 private etc.); the total number of types is computed and reported.
17607
17608 @end table
17609
17610 @noindent
17611 By default, all the syntax metrics are computed and reported. You can use the
17612 following switches to select specific syntax metrics.
17613
17614 @table @option
17615
17616 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17617
17618 @ifclear vms
17619 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17620 @end ifclear
17621
17622 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17623 Report all the syntax metrics
17624
17625 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17626 Do not report any of syntax metrics
17627
17628 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17629 Report the total number of declarations
17630
17631 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17632 Do not report the total number of declarations
17633
17634 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17635 Report the total number of statements
17636
17637 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17638 Do not report the total number of statements
17639
17640 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17641 Report the number of public subprograms in a compilation unit
17642
17643 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17644 Do not report the number of public subprograms in a compilation unit
17645
17646 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17647 Report the number of all the subprograms in a compilation unit
17648
17649 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17650 Do not report the number of all the subprograms in a compilation unit
17651
17652 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17653 Report the number of public types in a compilation unit
17654
17655 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17656 Do not report the number of public types in a compilation unit
17657
17658 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17659 Report the number of all the types in a compilation unit
17660
17661 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17662 Do not report the number of all the types in a compilation unit
17663
17664 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17665 Report the maximal program unit nesting level
17666
17667 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17668 Do not report the maximal program unit nesting level
17669
17670 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17671 Report the maximal construct nesting level
17672
17673 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17674 Do not report the maximal construct nesting level
17675
17676 @end table
17677
17678 @node Complexity Metrics Control
17679 @subsubsection Complexity Metrics Control
17680 @cindex Complexity metrics control in @command{gnatmetric}
17681
17682 @noindent
17683 For a program unit that is an executable body (a subprogram body (including
17684 generic bodies), task body, entry body or a package body containing
17685 its own statement sequence) @command{gnatmetric} computes the following
17686 complexity metrics:
17687
17688 @itemize @bullet
17689 @item
17690 McCabe cyclomatic complexity;
17691
17692 @item
17693 McCabe essential complexity;
17694
17695 @item
17696 maximal loop nesting level
17697
17698 @end itemize
17699
17700 @noindent
17701 The McCabe complexity metrics are defined
17702 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17703
17704 According to McCabe, both control statements and short-circuit control forms
17705 should be taken into account when computing cyclomatic complexity. For each
17706 body, we compute three metric values:
17707
17708 @itemize @bullet
17709 @item
17710 the complexity introduced by control
17711 statements only, without taking into account short-circuit forms,
17712
17713 @item
17714 the complexity introduced by short-circuit control forms only, and
17715
17716 @item
17717 the total
17718 cyclomatic complexity, which is the sum of these two values.
17719 @end itemize
17720
17721 @noindent
17722 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17723 the code in the exception handlers and in all the nested program units.
17724
17725 By default, all the complexity metrics are computed and reported.
17726 For more fine-grained control you can use
17727 the following switches:
17728
17729 @table @option
17730 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17731
17732 @ifclear vms
17733 @cindex @option{--no-complexity@var{x}}
17734 @end ifclear
17735
17736 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17737 Report all the complexity metrics
17738
17739 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17740 Do not report any of complexity metrics
17741
17742 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17743 Report the McCabe Cyclomatic Complexity
17744
17745 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17746 Do not report the McCabe Cyclomatic Complexity
17747
17748 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17749 Report the Essential Complexity
17750
17751 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17752 Do not report the Essential Complexity
17753
17754 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17755 Report maximal loop nesting level
17756
17757 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17758 Do not report maximal loop nesting level
17759
17760 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17761 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17762 task bodies, entry bodies and statement sequences in package bodies.
17763 The metric is computed and reported for whole set of processed Ada sources
17764 only.
17765
17766 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17767 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17768 bodies, task bodies, entry bodies and statement sequences in package bodies
17769
17770 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17771 @item ^-ne^/NO_EXITS_AS_GOTOS^
17772 Do not consider @code{exit} statements as @code{goto}s when
17773 computing Essential Complexity
17774
17775 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17776 Report the extra exit points for subprogram bodies. As an exit point, this
17777 metric counts @code{return} statements and raise statements in case when the
17778 raised exception is not handled in the same body. In case of a function this
17779 metric subtracts 1 from the number of exit points, because a function body
17780 must contain at least one @code{return} statement.
17781
17782 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17783 Do not report the extra exit points for subprogram bodies
17784 @end table
17785
17786
17787 @node Object-Oriented Metrics Control
17788 @subsubsection Object-Oriented Metrics Control
17789 @cindex Object-Oriented metrics control in @command{gnatmetric}
17790
17791 @noindent
17792 @cindex Coupling metrics (in in @command{gnatmetric})
17793 Coupling metrics are object-oriented metrics that measure the
17794 dependencies between a given class (or a group of classes) and the
17795 ``external world'' (that is, the other classes in the program). In this
17796 subsection the term ``class'' is used in its
17797 traditional object-oriented programming sense
17798 (an instantiable module that contains data and/or method members).
17799 A @emph{category} (of classes)
17800 is a group of closely related classes that are reused and/or
17801 modified together.
17802
17803 A class @code{K}'s @emph{efferent coupling} is the number of classes
17804 that @code{K} depends upon.
17805 A category's efferent coupling is the number of classes outside the
17806 category that the classes inside the category depend upon.
17807
17808 A class @code{K}'s @emph{afferent coupling} is the number of classes
17809 that depend upon @code{K}.
17810 A category's afferent coupling is the number of classes outside the
17811 category that depend on classes belonging to the category.
17812
17813 Ada's implementation of the object-oriented paradigm does not use the
17814 traditional class notion, so the definition of the coupling
17815 metrics for Ada maps the class and class category notions
17816 onto Ada constructs.
17817
17818 For the coupling metrics, several kinds of modules -- a library package,
17819 a library generic package, and a library generic package instantiation --
17820 that define a tagged type or an interface type are
17821 considered to be a class. A category consists of a library package (or
17822 a library generic package) that defines a tagged or an interface type,
17823 together with all its descendant (generic) packages that define tagged
17824 or interface types. For any package counted as a class,
17825 its body and subunits (if any) are considered
17826 together with its spec when counting the dependencies, and coupling
17827 metrics are reported for spec units only. For dependencies
17828 between classes, the Ada semantic dependencies are considered.
17829 For coupling metrics, only dependencies on units that are considered as
17830 classes, are considered.
17831
17832 When computing coupling metrics, @command{gnatmetric} counts only
17833 dependencies between units that are arguments of the gnatmetric call.
17834 Coupling metrics are program-wide (or project-wide) metrics, so to
17835 get a valid result, you should call @command{gnatmetric} for
17836 the whole set of sources that make up your program. It can be done
17837 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17838 option (see See @ref{The GNAT Driver and Project Files} for details.
17839
17840 By default, all the coupling metrics are disabled. You can use the following
17841 switches to specify the coupling metrics to be computed and reported:
17842
17843 @table @option
17844
17845 @ifclear vms
17846 @cindex @option{--package@var{x}} (@command{gnatmetric})
17847 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17848 @cindex @option{--category@var{x}} (@command{gnatmetric})
17849 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17850 @end ifclear
17851
17852 @ifset vms
17853 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17854 @end ifset
17855
17856 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17857 Report all the coupling metrics
17858
17859 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17860 Do not report any of  metrics
17861
17862 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17863 Report package efferent coupling
17864
17865 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17866 Do not report package efferent coupling
17867
17868 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17869 Report package afferent coupling
17870
17871 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17872 Do not report package afferent coupling
17873
17874 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17875 Report category efferent coupling
17876
17877 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17878 Do not report category efferent coupling
17879
17880 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17881 Report category afferent coupling
17882
17883 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17884 Do not report category afferent coupling
17885
17886 @end table
17887
17888 @node Other gnatmetric Switches
17889 @subsection Other @code{gnatmetric} Switches
17890
17891 @noindent
17892 Additional @command{gnatmetric} switches are as follows:
17893
17894 @table @option
17895 @item ^-files @var{filename}^/FILES=@var{filename}^
17896 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17897 Take the argument source files from the specified file. This file should be an
17898 ordinary text file containing file names separated by spaces or
17899 line breaks. You can use this switch more then once in the same call to
17900 @command{gnatmetric}. You also can combine this switch with
17901 an explicit list of files.
17902
17903 @item ^-v^/VERBOSE^
17904 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17905 Verbose mode;
17906 @command{gnatmetric} generates version information and then
17907 a trace of sources being processed.
17908
17909 @item ^-dv^/DEBUG_OUTPUT^
17910 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17911 Debug mode;
17912 @command{gnatmetric} generates various messages useful to understand what
17913 happens during the metrics computation
17914
17915 @item ^-q^/QUIET^
17916 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17917 Quiet mode.
17918 @end table
17919
17920 @node Generate project-wide metrics
17921 @subsection Generate project-wide metrics
17922
17923 In order to compute metrics on all units of a given project, you can use
17924 the @command{gnat} driver along with the @option{-P} option:
17925 @smallexample
17926    gnat metric -Pproj
17927 @end smallexample
17928
17929 @noindent
17930 If the project @code{proj} depends upon other projects, you can compute
17931 the metrics on the project closure using the @option{-U} option:
17932 @smallexample
17933    gnat metric -Pproj -U
17934 @end smallexample
17935
17936 @noindent
17937 Finally, if not all the units are relevant to a particular main
17938 program in the project closure, you can generate metrics for the set
17939 of units needed to create a given main program (unit closure) using
17940 the @option{-U} option followed by the name of the main unit:
17941 @smallexample
17942    gnat metric -Pproj -U main
17943 @end smallexample
17944
17945
17946 @c ***********************************
17947 @node File Name Krunching Using gnatkr
17948 @chapter File Name Krunching Using @code{gnatkr}
17949 @findex gnatkr
17950
17951 @noindent
17952 This chapter discusses the method used by the compiler to shorten
17953 the default file names chosen for Ada units so that they do not
17954 exceed the maximum length permitted. It also describes the
17955 @code{gnatkr} utility that can be used to determine the result of
17956 applying this shortening.
17957 @menu
17958 * About gnatkr::
17959 * Using gnatkr::
17960 * Krunching Method::
17961 * Examples of gnatkr Usage::
17962 @end menu
17963
17964 @node About gnatkr
17965 @section About @code{gnatkr}
17966
17967 @noindent
17968 The default file naming rule in GNAT
17969 is that the file name must be derived from
17970 the unit name. The exact default rule is as follows:
17971 @itemize @bullet
17972 @item
17973 Take the unit name and replace all dots by hyphens.
17974 @item
17975 If such a replacement occurs in the
17976 second character position of a name, and the first character is
17977 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17978 then replace the dot by the character
17979 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17980 instead of a minus.
17981 @end itemize
17982 The reason for this exception is to avoid clashes
17983 with the standard names for children of System, Ada, Interfaces,
17984 and GNAT, which use the prefixes
17985 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17986 respectively.
17987
17988 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17989 switch of the compiler activates a ``krunching''
17990 circuit that limits file names to nn characters (where nn is a decimal
17991 integer). For example, using OpenVMS,
17992 where the maximum file name length is
17993 39, the value of nn is usually set to 39, but if you want to generate
17994 a set of files that would be usable if ported to a system with some
17995 different maximum file length, then a different value can be specified.
17996 The default value of 39 for OpenVMS need not be specified.
17997
17998 The @code{gnatkr} utility can be used to determine the krunched name for
17999 a given file, when krunched to a specified maximum length.
18000
18001 @node Using gnatkr
18002 @section Using @code{gnatkr}
18003
18004 @noindent
18005 The @code{gnatkr} command has the form
18006
18007 @ifclear vms
18008 @smallexample
18009 $ gnatkr @var{name} @ovar{length}
18010 @end smallexample
18011 @end ifclear
18012
18013 @ifset vms
18014 @smallexample
18015 $ gnatkr @var{name} /COUNT=nn
18016 @end smallexample
18017 @end ifset
18018
18019 @noindent
18020 @var{name} is the uncrunched file name, derived from the name of the unit
18021 in the standard manner described in the previous section (i.e., in particular
18022 all dots are replaced by hyphens). The file name may or may not have an
18023 extension (defined as a suffix of the form period followed by arbitrary
18024 characters other than period). If an extension is present then it will
18025 be preserved in the output. For example, when krunching @file{hellofile.ads}
18026 to eight characters, the result will be hellofil.ads.
18027
18028 Note: for compatibility with previous versions of @code{gnatkr} dots may
18029 appear in the name instead of hyphens, but the last dot will always be
18030 taken as the start of an extension. So if @code{gnatkr} is given an argument
18031 such as @file{Hello.World.adb} it will be treated exactly as if the first
18032 period had been a hyphen, and for example krunching to eight characters
18033 gives the result @file{hellworl.adb}.
18034
18035 Note that the result is always all lower case (except on OpenVMS where it is
18036 all upper case). Characters of the other case are folded as required.
18037
18038 @var{length} represents the length of the krunched name. The default
18039 when no argument is given is ^8^39^ characters. A length of zero stands for
18040 unlimited, in other words do not chop except for system files where the
18041 implied crunching length is always eight characters.
18042
18043 @noindent
18044 The output is the krunched name. The output has an extension only if the
18045 original argument was a file name with an extension.
18046
18047 @node Krunching Method
18048 @section Krunching Method
18049
18050 @noindent
18051 The initial file name is determined by the name of the unit that the file
18052 contains. The name is formed by taking the full expanded name of the
18053 unit and replacing the separating dots with hyphens and
18054 using ^lowercase^uppercase^
18055 for all letters, except that a hyphen in the second character position is
18056 replaced by a ^tilde^dollar sign^ if the first character is
18057 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18058 The extension is @code{.ads} for a
18059 spec and @code{.adb} for a body.
18060 Krunching does not affect the extension, but the file name is shortened to
18061 the specified length by following these rules:
18062
18063 @itemize @bullet
18064 @item
18065 The name is divided into segments separated by hyphens, tildes or
18066 underscores and all hyphens, tildes, and underscores are
18067 eliminated. If this leaves the name short enough, we are done.
18068
18069 @item
18070 If the name is too long, the longest segment is located (left-most
18071 if there are two of equal length), and shortened by dropping
18072 its last character. This is repeated until the name is short enough.
18073
18074 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18075 to fit the name into 8 characters as required by some operating systems.
18076
18077 @smallexample
18078 our-strings-wide_fixed 22
18079 our strings wide fixed 19
18080 our string  wide fixed 18
18081 our strin   wide fixed 17
18082 our stri    wide fixed 16
18083 our stri    wide fixe  15
18084 our str     wide fixe  14
18085 our str     wid  fixe  13
18086 our str     wid  fix   12
18087 ou  str     wid  fix   11
18088 ou  st      wid  fix   10
18089 ou  st      wi   fix   9
18090 ou  st      wi   fi    8
18091 Final file name: oustwifi.adb
18092 @end smallexample
18093
18094 @item
18095 The file names for all predefined units are always krunched to eight
18096 characters. The krunching of these predefined units uses the following
18097 special prefix replacements:
18098
18099 @table @file
18100 @item ada-
18101 replaced by @file{^a^A^-}
18102
18103 @item gnat-
18104 replaced by @file{^g^G^-}
18105
18106 @item interfaces-
18107 replaced by @file{^i^I^-}
18108
18109 @item system-
18110 replaced by @file{^s^S^-}
18111 @end table
18112
18113 These system files have a hyphen in the second character position. That
18114 is why normal user files replace such a character with a
18115 ^tilde^dollar sign^, to
18116 avoid confusion with system file names.
18117
18118 As an example of this special rule, consider
18119 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18120
18121 @smallexample
18122 ada-strings-wide_fixed 22
18123 a-  strings wide fixed 18
18124 a-  string  wide fixed 17
18125 a-  strin   wide fixed 16
18126 a-  stri    wide fixed 15
18127 a-  stri    wide fixe  14
18128 a-  str     wide fixe  13
18129 a-  str     wid  fixe  12
18130 a-  str     wid  fix   11
18131 a-  st      wid  fix   10
18132 a-  st      wi   fix   9
18133 a-  st      wi   fi    8
18134 Final file name: a-stwifi.adb
18135 @end smallexample
18136 @end itemize
18137
18138 Of course no file shortening algorithm can guarantee uniqueness over all
18139 possible unit names, and if file name krunching is used then it is your
18140 responsibility to ensure that no name clashes occur. The utility
18141 program @code{gnatkr} is supplied for conveniently determining the
18142 krunched name of a file.
18143
18144 @node Examples of gnatkr Usage
18145 @section Examples of @code{gnatkr} Usage
18146
18147 @smallexample
18148 @iftex
18149 @leftskip=0cm
18150 @end iftex
18151 @ifclear vms
18152 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18153 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18154 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18155 $ gnatkr grandparent-parent-child     --> grparchi
18156 @end ifclear
18157 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18158 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18159 @end smallexample
18160
18161 @node Preprocessing Using gnatprep
18162 @chapter Preprocessing Using @code{gnatprep}
18163 @findex gnatprep
18164
18165 @noindent
18166 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18167 preprocessing.
18168 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18169 special GNAT features.
18170 For further discussion of conditional compilation in general, see
18171 @ref{Conditional Compilation}.
18172
18173 @menu
18174 * Preprocessing Symbols::
18175 * Using gnatprep::
18176 * Switches for gnatprep::
18177 * Form of Definitions File::
18178 * Form of Input Text for gnatprep::
18179 @end menu
18180
18181 @node Preprocessing Symbols
18182 @section Preprocessing Symbols
18183
18184 @noindent
18185 Preprocessing symbols are defined in definition files and referred to in
18186 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18187 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18188 all characters need to be in the ASCII set (no accented letters).
18189
18190 @node Using gnatprep
18191 @section Using @code{gnatprep}
18192
18193 @noindent
18194 To call @code{gnatprep} use
18195
18196 @smallexample
18197 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18198 @end smallexample
18199
18200 @noindent
18201 where
18202 @table @var
18203 @item switches
18204 is an optional sequence of switches as described in the next section.
18205
18206 @item infile
18207 is the full name of the input file, which is an Ada source
18208 file containing preprocessor directives.
18209
18210 @item outfile
18211 is the full name of the output file, which is an Ada source
18212 in standard Ada form. When used with GNAT, this file name will
18213 normally have an ads or adb suffix.
18214
18215 @item deffile
18216 is the full name of a text file containing definitions of
18217 preprocessing symbols to be referenced by the preprocessor. This argument is
18218 optional, and can be replaced by the use of the @option{-D} switch.
18219
18220 @end table
18221
18222 @node Switches for gnatprep
18223 @section Switches for @code{gnatprep}
18224
18225 @table @option
18226 @c !sort!
18227
18228 @item ^-b^/BLANK_LINES^
18229 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18230 Causes both preprocessor lines and the lines deleted by
18231 preprocessing to be replaced by blank lines in the output source file,
18232 preserving line numbers in the output file.
18233
18234 @item ^-c^/COMMENTS^
18235 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18236 Causes both preprocessor lines and the lines deleted
18237 by preprocessing to be retained in the output source as comments marked
18238 with the special string @code{"--! "}. This option will result in line numbers
18239 being preserved in the output file.
18240
18241 @item ^-C^/REPLACE_IN_COMMENTS^
18242 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18243 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18244 If this option is specified, then comments are scanned and any $symbol
18245 substitutions performed as in program text. This is particularly useful
18246 when structured comments are used (e.g., when writing programs in the
18247 SPARK dialect of Ada). Note that this switch is not available when
18248 doing integrated preprocessing (it would be useless in this context
18249 since comments are ignored by the compiler in any case).
18250
18251 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18252 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18253 Defines a new preprocessing symbol, associated with value. If no value is given
18254 on the command line, then symbol is considered to be @code{True}. This switch
18255 can be used in place of a definition file.
18256
18257 @ifset vms
18258 @item /REMOVE
18259 @cindex @option{/REMOVE} (@command{gnatprep})
18260 This is the default setting which causes lines deleted by preprocessing
18261 to be entirely removed from the output file.
18262 @end ifset
18263
18264 @item ^-r^/REFERENCE^
18265 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18266 Causes a @code{Source_Reference} pragma to be generated that
18267 references the original input file, so that error messages will use
18268 the file name of this original file. The use of this switch implies
18269 that preprocessor lines are not to be removed from the file, so its
18270 use will force @option{^-b^/BLANK_LINES^} mode if
18271 @option{^-c^/COMMENTS^}
18272 has not been specified explicitly.
18273
18274 Note that if the file to be preprocessed contains multiple units, then
18275 it will be necessary to @code{gnatchop} the output file from
18276 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18277 in the preprocessed file, it will be respected by
18278 @code{gnatchop ^-r^/REFERENCE^}
18279 so that the final chopped files will correctly refer to the original
18280 input source file for @code{gnatprep}.
18281
18282 @item ^-s^/SYMBOLS^
18283 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18284 Causes a sorted list of symbol names and values to be
18285 listed on the standard output file.
18286
18287 @item ^-u^/UNDEFINED^
18288 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18289 Causes undefined symbols to be treated as having the value FALSE in the context
18290 of a preprocessor test. In the absence of this option, an undefined symbol in
18291 a @code{#if} or @code{#elsif} test will be treated as an error.
18292
18293 @end table
18294
18295 @ifclear vms
18296 @noindent
18297 Note: if neither @option{-b} nor @option{-c} is present,
18298 then preprocessor lines and
18299 deleted lines are completely removed from the output, unless -r is
18300 specified, in which case -b is assumed.
18301 @end ifclear
18302
18303 @node Form of Definitions File
18304 @section Form of Definitions File
18305
18306 @noindent
18307 The definitions file contains lines of the form
18308
18309 @smallexample
18310 symbol := value
18311 @end smallexample
18312
18313 @noindent
18314 where symbol is a preprocessing symbol, and value is one of the following:
18315
18316 @itemize @bullet
18317 @item
18318 Empty, corresponding to a null substitution
18319 @item
18320 A string literal using normal Ada syntax
18321 @item
18322 Any sequence of characters from the set
18323 (letters, digits, period, underline).
18324 @end itemize
18325
18326 @noindent
18327 Comment lines may also appear in the definitions file, starting with
18328 the usual @code{--},
18329 and comments may be added to the definitions lines.
18330
18331 @node Form of Input Text for gnatprep
18332 @section Form of Input Text for @code{gnatprep}
18333
18334 @noindent
18335 The input text may contain preprocessor conditional inclusion lines,
18336 as well as general symbol substitution sequences.
18337
18338 The preprocessor conditional inclusion commands have the form
18339
18340 @smallexample
18341 @group
18342 @cartouche
18343 #if @i{expression} @r{[}then@r{]}
18344    lines
18345 #elsif @i{expression} @r{[}then@r{]}
18346    lines
18347 #elsif @i{expression} @r{[}then@r{]}
18348    lines
18349 @dots{}
18350 #else
18351    lines
18352 #end if;
18353 @end cartouche
18354 @end group
18355 @end smallexample
18356
18357 @noindent
18358 In this example, @i{expression} is defined by the following grammar:
18359 @smallexample
18360 @i{expression} ::=  <symbol>
18361 @i{expression} ::=  <symbol> = "<value>"
18362 @i{expression} ::=  <symbol> = <symbol>
18363 @i{expression} ::=  <symbol> 'Defined
18364 @i{expression} ::=  not @i{expression}
18365 @i{expression} ::=  @i{expression} and @i{expression}
18366 @i{expression} ::=  @i{expression} or @i{expression}
18367 @i{expression} ::=  @i{expression} and then @i{expression}
18368 @i{expression} ::=  @i{expression} or else @i{expression}
18369 @i{expression} ::=  ( @i{expression} )
18370 @end smallexample
18371
18372 The following restriction exists: it is not allowed to have "and" or "or"
18373 following "not" in the same expression without parentheses. For example, this
18374 is not allowed:
18375
18376 @smallexample
18377    not X or Y
18378 @end smallexample
18379
18380 This should be one of the following:
18381
18382 @smallexample
18383    (not X) or Y
18384    not (X or Y)
18385 @end smallexample
18386
18387 @noindent
18388 For the first test (@i{expression} ::= <symbol>) the symbol must have
18389 either the value true or false, that is to say the right-hand of the
18390 symbol definition must be one of the (case-insensitive) literals
18391 @code{True} or @code{False}. If the value is true, then the
18392 corresponding lines are included, and if the value is false, they are
18393 excluded.
18394
18395 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18396 the symbol has been defined in the definition file or by a @option{-D}
18397 switch on the command line. Otherwise, the test is false.
18398
18399 The equality tests are case insensitive, as are all the preprocessor lines.
18400
18401 If the symbol referenced is not defined in the symbol definitions file,
18402 then the effect depends on whether or not switch @option{-u}
18403 is specified. If so, then the symbol is treated as if it had the value
18404 false and the test fails. If this switch is not specified, then
18405 it is an error to reference an undefined symbol. It is also an error to
18406 reference a symbol that is defined with a value other than @code{True}
18407 or @code{False}.
18408
18409 The use of the @code{not} operator inverts the sense of this logical test.
18410 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18411 operators, without parentheses. For example, "if not X or Y then" is not
18412 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18413
18414 The @code{then} keyword is optional as shown
18415
18416 The @code{#} must be the first non-blank character on a line, but
18417 otherwise the format is free form. Spaces or tabs may appear between
18418 the @code{#} and the keyword. The keywords and the symbols are case
18419 insensitive as in normal Ada code. Comments may be used on a
18420 preprocessor line, but other than that, no other tokens may appear on a
18421 preprocessor line. Any number of @code{elsif} clauses can be present,
18422 including none at all. The @code{else} is optional, as in Ada.
18423
18424 The @code{#} marking the start of a preprocessor line must be the first
18425 non-blank character on the line, i.e., it must be preceded only by
18426 spaces or horizontal tabs.
18427
18428 Symbol substitution outside of preprocessor lines is obtained by using
18429 the sequence
18430
18431 @smallexample
18432 $symbol
18433 @end smallexample
18434
18435 @noindent
18436 anywhere within a source line, except in a comment or within a
18437 string literal. The identifier
18438 following the @code{$} must match one of the symbols defined in the symbol
18439 definition file, and the result is to substitute the value of the
18440 symbol in place of @code{$symbol} in the output file.
18441
18442 Note that although the substitution of strings within a string literal
18443 is not possible, it is possible to have a symbol whose defined value is
18444 a string literal. So instead of setting XYZ to @code{hello} and writing:
18445
18446 @smallexample
18447 Header : String := "$XYZ";
18448 @end smallexample
18449
18450 @noindent
18451 you should set XYZ to @code{"hello"} and write:
18452
18453 @smallexample
18454 Header : String := $XYZ;
18455 @end smallexample
18456
18457 @noindent
18458 and then the substitution will occur as desired.
18459
18460 @ifset vms
18461 @node The GNAT Run-Time Library Builder gnatlbr
18462 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18463 @findex gnatlbr
18464 @cindex Library builder
18465
18466 @noindent
18467 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18468 supplied configuration pragmas.
18469
18470 @menu
18471 * Running gnatlbr::
18472 * Switches for gnatlbr::
18473 * Examples of gnatlbr Usage::
18474 @end menu
18475
18476 @node Running gnatlbr
18477 @section Running @code{gnatlbr}
18478
18479 @noindent
18480 The @code{gnatlbr} command has the form
18481
18482 @smallexample
18483 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18484 @end smallexample
18485
18486 @node Switches for gnatlbr
18487 @section Switches for @code{gnatlbr}
18488
18489 @noindent
18490 @code{gnatlbr} recognizes the following switches:
18491
18492 @table @option
18493 @c !sort!
18494 @item /CREATE=directory
18495 @cindex @code{/CREATE} (@code{gnatlbr})
18496 Create the new run-time library in the specified directory.
18497
18498 @item /SET=directory
18499 @cindex @code{/SET} (@code{gnatlbr})
18500 Make the library in the specified directory the current run-time library.
18501
18502 @item /DELETE=directory
18503 @cindex @code{/DELETE} (@code{gnatlbr})
18504 Delete the run-time library in the specified directory.
18505
18506 @item /CONFIG=file
18507 @cindex @code{/CONFIG} (@code{gnatlbr})
18508 With /CREATE: Use the configuration pragmas in the specified file when
18509 building the library.
18510
18511 With /SET: Use the configuration pragmas in the specified file when
18512 compiling.
18513
18514 @end table
18515
18516 @node Examples of gnatlbr Usage
18517 @section Example of @code{gnatlbr} Usage
18518
18519 @smallexample
18520 Contents of VAXFLOAT.ADC:
18521 pragma Float_Representation (VAX_Float);
18522
18523 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18524
18525 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18526
18527 @end smallexample
18528 @end ifset
18529
18530 @node The GNAT Library Browser gnatls
18531 @chapter The GNAT Library Browser @code{gnatls}
18532 @findex gnatls
18533 @cindex Library browser
18534
18535 @noindent
18536 @code{gnatls} is a tool that outputs information about compiled
18537 units. It gives the relationship between objects, unit names and source
18538 files. It can also be used to check the source dependencies of a unit
18539 as well as various characteristics.
18540
18541 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18542 driver (see @ref{The GNAT Driver and Project Files}).
18543
18544 @menu
18545 * Running gnatls::
18546 * Switches for gnatls::
18547 * Examples of gnatls Usage::
18548 @end menu
18549
18550 @node Running gnatls
18551 @section Running @code{gnatls}
18552
18553 @noindent
18554 The @code{gnatls} command has the form
18555
18556 @smallexample
18557 $ gnatls switches @var{object_or_ali_file}
18558 @end smallexample
18559
18560 @noindent
18561 The main argument is the list of object or @file{ali} files
18562 (@pxref{The Ada Library Information Files})
18563 for which information is requested.
18564
18565 In normal mode, without additional option, @code{gnatls} produces a
18566 four-column listing. Each line represents information for a specific
18567 object. The first column gives the full path of the object, the second
18568 column gives the name of the principal unit in this object, the third
18569 column gives the status of the source and the fourth column gives the
18570 full path of the source representing this unit.
18571 Here is a simple example of use:
18572
18573 @smallexample
18574 $ gnatls *.o
18575 ^./^[]^demo1.o            demo1            DIF demo1.adb
18576 ^./^[]^demo2.o            demo2             OK demo2.adb
18577 ^./^[]^hello.o            h1                OK hello.adb
18578 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18579 ^./^[]^instr.o            instr             OK instr.adb
18580 ^./^[]^tef.o              tef              DIF tef.adb
18581 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18582 ^./^[]^tgef.o             tgef             DIF tgef.adb
18583 @end smallexample
18584
18585 @noindent
18586 The first line can be interpreted as follows: the main unit which is
18587 contained in
18588 object file @file{demo1.o} is demo1, whose main source is in
18589 @file{demo1.adb}. Furthermore, the version of the source used for the
18590 compilation of demo1 has been modified (DIF). Each source file has a status
18591 qualifier which can be:
18592
18593 @table @code
18594 @item OK (unchanged)
18595 The version of the source file used for the compilation of the
18596 specified unit corresponds exactly to the actual source file.
18597
18598 @item MOK (slightly modified)
18599 The version of the source file used for the compilation of the
18600 specified unit differs from the actual source file but not enough to
18601 require recompilation. If you use gnatmake with the qualifier
18602 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18603 MOK will not be recompiled.
18604
18605 @item DIF (modified)
18606 No version of the source found on the path corresponds to the source
18607 used to build this object.
18608
18609 @item ??? (file not found)
18610 No source file was found for this unit.
18611
18612 @item HID (hidden,  unchanged version not first on PATH)
18613 The version of the source that corresponds exactly to the source used
18614 for compilation has been found on the path but it is hidden by another
18615 version of the same source that has been modified.
18616
18617 @end table
18618
18619 @node Switches for gnatls
18620 @section Switches for @code{gnatls}
18621
18622 @noindent
18623 @code{gnatls} recognizes the following switches:
18624
18625 @table @option
18626 @c !sort!
18627 @cindex @option{--version} @command{gnatls}
18628 Display Copyright and version, then exit disregarding all other options.
18629
18630 @item --help
18631 @cindex @option{--help} @command{gnatls}
18632 If @option{--version} was not used, display usage, then exit disregarding
18633 all other options.
18634
18635 @item ^-a^/ALL_UNITS^
18636 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18637 Consider all units, including those of the predefined Ada library.
18638 Especially useful with @option{^-d^/DEPENDENCIES^}.
18639
18640 @item ^-d^/DEPENDENCIES^
18641 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18642 List sources from which specified units depend on.
18643
18644 @item ^-h^/OUTPUT=OPTIONS^
18645 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18646 Output the list of options.
18647
18648 @item ^-o^/OUTPUT=OBJECTS^
18649 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18650 Only output information about object files.
18651
18652 @item ^-s^/OUTPUT=SOURCES^
18653 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18654 Only output information about source files.
18655
18656 @item ^-u^/OUTPUT=UNITS^
18657 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18658 Only output information about compilation units.
18659
18660 @item ^-files^/FILES^=@var{file}
18661 @cindex @option{^-files^/FILES^} (@code{gnatls})
18662 Take as arguments the files listed in text file @var{file}.
18663 Text file @var{file} may contain empty lines that are ignored.
18664 Each nonempty line should contain the name of an existing file.
18665 Several such switches may be specified simultaneously.
18666
18667 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18668 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18669 @itemx ^-I^/SEARCH=^@var{dir}
18670 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18671 @itemx -nostdinc
18672 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18673 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18674 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18675 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18676 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18677 flags (@pxref{Switches for gnatmake}).
18678
18679 @item --RTS=@var{rts-path}
18680 @cindex @option{--RTS} (@code{gnatls})
18681 Specifies the default location of the runtime library. Same meaning as the
18682 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18683
18684 @item ^-v^/OUTPUT=VERBOSE^
18685 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18686 Verbose mode. Output the complete source, object and project paths. Do not use
18687 the default column layout but instead use long format giving as much as
18688 information possible on each requested units, including special
18689 characteristics such as:
18690
18691 @table @code
18692 @item  Preelaborable
18693 The unit is preelaborable in the Ada sense.
18694
18695 @item No_Elab_Code
18696 No elaboration code has been produced by the compiler for this unit.
18697
18698 @item Pure
18699 The unit is pure in the Ada sense.
18700
18701 @item Elaborate_Body
18702 The unit contains a pragma Elaborate_Body.
18703
18704 @item Remote_Types
18705 The unit contains a pragma Remote_Types.
18706
18707 @item Shared_Passive
18708 The unit contains a pragma Shared_Passive.
18709
18710 @item Predefined
18711 This unit is part of the predefined environment and cannot be modified
18712 by the user.
18713
18714 @item Remote_Call_Interface
18715 The unit contains a pragma Remote_Call_Interface.
18716
18717 @end table
18718
18719 @end table
18720
18721 @node Examples of gnatls Usage
18722 @section Example of @code{gnatls} Usage
18723 @ifclear vms
18724
18725 @noindent
18726 Example of using the verbose switch. Note how the source and
18727 object paths are affected by the -I switch.
18728
18729 @smallexample
18730 $ gnatls -v -I.. demo1.o
18731
18732 GNATLS 5.03w (20041123-34)
18733 Copyright 1997-2004 Free Software Foundation, Inc.
18734
18735 Source Search Path:
18736    <Current_Directory>
18737    ../
18738    /home/comar/local/adainclude/
18739
18740 Object Search Path:
18741    <Current_Directory>
18742    ../
18743    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18744
18745 Project Search Path:
18746    <Current_Directory>
18747    /home/comar/local/lib/gnat/
18748
18749 ./demo1.o
18750    Unit =>
18751      Name   => demo1
18752      Kind   => subprogram body
18753      Flags  => No_Elab_Code
18754      Source => demo1.adb    modified
18755 @end smallexample
18756
18757 @noindent
18758 The following is an example of use of the dependency list.
18759 Note the use of the -s switch
18760 which gives a straight list of source files. This can be useful for
18761 building specialized scripts.
18762
18763 @smallexample
18764 $ gnatls -d demo2.o
18765 ./demo2.o   demo2        OK demo2.adb
18766                          OK gen_list.ads
18767                          OK gen_list.adb
18768                          OK instr.ads
18769                          OK instr-child.ads
18770
18771 $ gnatls -d -s -a demo1.o
18772 demo1.adb
18773 /home/comar/local/adainclude/ada.ads
18774 /home/comar/local/adainclude/a-finali.ads
18775 /home/comar/local/adainclude/a-filico.ads
18776 /home/comar/local/adainclude/a-stream.ads
18777 /home/comar/local/adainclude/a-tags.ads
18778 gen_list.ads
18779 gen_list.adb
18780 /home/comar/local/adainclude/gnat.ads
18781 /home/comar/local/adainclude/g-io.ads
18782 instr.ads
18783 /home/comar/local/adainclude/system.ads
18784 /home/comar/local/adainclude/s-exctab.ads
18785 /home/comar/local/adainclude/s-finimp.ads
18786 /home/comar/local/adainclude/s-finroo.ads
18787 /home/comar/local/adainclude/s-secsta.ads
18788 /home/comar/local/adainclude/s-stalib.ads
18789 /home/comar/local/adainclude/s-stoele.ads
18790 /home/comar/local/adainclude/s-stratt.ads
18791 /home/comar/local/adainclude/s-tasoli.ads
18792 /home/comar/local/adainclude/s-unstyp.ads
18793 /home/comar/local/adainclude/unchconv.ads
18794 @end smallexample
18795 @end ifclear
18796
18797 @ifset vms
18798 @smallexample
18799 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18800
18801 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18802 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18803 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18804 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18805 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18806 demo1.adb
18807 gen_list.ads
18808 gen_list.adb
18809 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18810 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18811 instr.ads
18812 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18813 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18814 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18815 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18816 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18817 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18818 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18819 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18820 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18822 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18823 @end smallexample
18824 @end ifset
18825
18826 @node Cleaning Up Using gnatclean
18827 @chapter Cleaning Up Using @code{gnatclean}
18828 @findex gnatclean
18829 @cindex Cleaning tool
18830
18831 @noindent
18832 @code{gnatclean} is a tool that allows the deletion of files produced by the
18833 compiler, binder and linker, including ALI files, object files, tree files,
18834 expanded source files, library files, interface copy source files, binder
18835 generated files and executable files.
18836
18837 @menu
18838 * Running gnatclean::
18839 * Switches for gnatclean::
18840 @c * Examples of gnatclean Usage::
18841 @end menu
18842
18843 @node Running gnatclean
18844 @section Running @code{gnatclean}
18845
18846 @noindent
18847 The @code{gnatclean} command has the form:
18848
18849 @smallexample
18850 $ gnatclean switches @var{names}
18851 @end smallexample
18852
18853 @noindent
18854 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18855 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18856 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18857
18858 @noindent
18859 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18860 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18861 the linker. In informative-only mode, specified by switch
18862 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18863 normal mode is listed, but no file is actually deleted.
18864
18865 @node Switches for gnatclean
18866 @section Switches for @code{gnatclean}
18867
18868 @noindent
18869 @code{gnatclean} recognizes the following switches:
18870
18871 @table @option
18872 @c !sort!
18873 @cindex @option{--version} @command{gnatclean}
18874 Display Copyright and version, then exit disregarding all other options.
18875
18876 @item --help
18877 @cindex @option{--help} @command{gnatclean}
18878 If @option{--version} was not used, display usage, then exit disregarding
18879 all other options.
18880
18881 @item ^-c^/COMPILER_FILES_ONLY^
18882 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18883 Only attempt to delete the files produced by the compiler, not those produced
18884 by the binder or the linker. The files that are not to be deleted are library
18885 files, interface copy files, binder generated files and executable files.
18886
18887 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18888 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18889 Indicate that ALI and object files should normally be found in directory
18890 @var{dir}.
18891
18892 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18893 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18894 When using project files, if some errors or warnings are detected during
18895 parsing and verbose mode is not in effect (no use of switch
18896 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18897 file, rather than its simple file name.
18898
18899 @item ^-h^/HELP^
18900 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18901 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18902
18903 @item ^-n^/NODELETE^
18904 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18905 Informative-only mode. Do not delete any files. Output the list of the files
18906 that would have been deleted if this switch was not specified.
18907
18908 @item ^-P^/PROJECT_FILE=^@var{project}
18909 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18910 Use project file @var{project}. Only one such switch can be used.
18911 When cleaning a project file, the files produced by the compilation of the
18912 immediate sources or inherited sources of the project files are to be
18913 deleted. This is not depending on the presence or not of executable names
18914 on the command line.
18915
18916 @item ^-q^/QUIET^
18917 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18918 Quiet output. If there are no errors, do not output anything, except in
18919 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18920 (switch ^-n^/NODELETE^).
18921
18922 @item ^-r^/RECURSIVE^
18923 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18924 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18925 clean all imported and extended project files, recursively. If this switch
18926 is not specified, only the files related to the main project file are to be
18927 deleted. This switch has no effect if no project file is specified.
18928
18929 @item ^-v^/VERBOSE^
18930 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18931 Verbose mode.
18932
18933 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18934 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18935 Indicates the verbosity of the parsing of GNAT project files.
18936 @xref{Switches Related to Project Files}.
18937
18938 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18939 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18940 Indicates that external variable @var{name} has the value @var{value}.
18941 The Project Manager will use this value for occurrences of
18942 @code{external(name)} when parsing the project file.
18943 @xref{Switches Related to Project Files}.
18944
18945 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18946 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18947 When searching for ALI and object files, look in directory
18948 @var{dir}.
18949
18950 @item ^-I^/SEARCH=^@var{dir}
18951 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18952 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18953
18954 @item ^-I-^/NOCURRENT_DIRECTORY^
18955 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18956 @cindex Source files, suppressing search
18957 Do not look for ALI or object files in the directory
18958 where @code{gnatclean} was invoked.
18959
18960 @end table
18961
18962 @c @node Examples of gnatclean Usage
18963 @c @section Examples of @code{gnatclean} Usage
18964
18965 @ifclear vms
18966 @node GNAT and Libraries
18967 @chapter GNAT and Libraries
18968 @cindex Library, building, installing, using
18969
18970 @noindent
18971 This chapter describes how to build and use libraries with GNAT, and also shows
18972 how to recompile the GNAT run-time library. You should be familiar with the
18973 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18974 chapter.
18975
18976 @menu
18977 * Introduction to Libraries in GNAT::
18978 * General Ada Libraries::
18979 * Stand-alone Ada Libraries::
18980 * Rebuilding the GNAT Run-Time Library::
18981 @end menu
18982
18983 @node Introduction to Libraries in GNAT
18984 @section Introduction to Libraries in GNAT
18985
18986 @noindent
18987 A library is, conceptually, a collection of objects which does not have its
18988 own main thread of execution, but rather provides certain services to the
18989 applications that use it. A library can be either statically linked with the
18990 application, in which case its code is directly included in the application,
18991 or, on platforms that support it, be dynamically linked, in which case
18992 its code is shared by all applications making use of this library.
18993
18994 GNAT supports both types of libraries.
18995 In the static case, the compiled code can be provided in different ways. The
18996 simplest approach is to provide directly the set of objects resulting from
18997 compilation of the library source files. Alternatively, you can group the
18998 objects into an archive using whatever commands are provided by the operating
18999 system. For the latter case, the objects are grouped into a shared library.
19000
19001 In the GNAT environment, a library has three types of components:
19002 @itemize @bullet
19003 @item
19004 Source files.
19005 @item
19006 @file{ALI} files.
19007 @xref{The Ada Library Information Files}.
19008 @item
19009 Object files, an archive or a shared library.
19010 @end itemize
19011
19012 @noindent
19013 A GNAT library may expose all its source files, which is useful for
19014 documentation purposes. Alternatively, it may expose only the units needed by
19015 an external user to make use of the library. That is to say, the specs
19016 reflecting the library services along with all the units needed to compile
19017 those specs, which can include generic bodies or any body implementing an
19018 inlined routine. In the case of @emph{stand-alone libraries} those exposed
19019 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
19020
19021 All compilation units comprising an application, including those in a library,
19022 need to be elaborated in an order partially defined by Ada's semantics. GNAT
19023 computes the elaboration order from the @file{ALI} files and this is why they
19024 constitute a mandatory part of GNAT libraries.
19025 @emph{Stand-alone libraries} are the exception to this rule because a specific
19026 library elaboration routine is produced independently of the application(s)
19027 using the library.
19028
19029 @node General Ada Libraries
19030 @section General Ada Libraries
19031
19032 @menu
19033 * Building a library::
19034 * Installing a library::
19035 * Using a library::
19036 @end menu
19037
19038 @node Building a library
19039 @subsection Building a library
19040
19041 @noindent
19042 The easiest way to build a library is to use the Project Manager,
19043 which supports a special type of project called a @emph{Library Project}
19044 (@pxref{Library Projects}).
19045
19046 A project is considered a library project, when two project-level attributes
19047 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19048 control different aspects of library configuration, additional optional
19049 project-level attributes can be specified:
19050 @table @code
19051 @item Library_Kind
19052 This attribute controls whether the library is to be static or dynamic
19053
19054 @item Library_Version
19055 This attribute specifies the library version; this value is used
19056 during dynamic linking of shared libraries to determine if the currently
19057 installed versions of the binaries are compatible.
19058
19059 @item Library_Options
19060 @item Library_GCC
19061 These attributes specify additional low-level options to be used during
19062 library generation, and redefine the actual application used to generate
19063 library.
19064 @end table
19065
19066 @noindent
19067 The GNAT Project Manager takes full care of the library maintenance task,
19068 including recompilation of the source files for which objects do not exist
19069 or are not up to date, assembly of the library archive, and installation of
19070 the library (i.e., copying associated source, object and @file{ALI} files
19071 to the specified location).
19072
19073 Here is a simple library project file:
19074 @smallexample @c ada
19075 project My_Lib is
19076    for Source_Dirs use ("src1", "src2");
19077    for Object_Dir use "obj";
19078    for Library_Name use "mylib";
19079    for Library_Dir use "lib";
19080    for Library_Kind use "dynamic";
19081 end My_lib;
19082 @end smallexample
19083
19084 @noindent
19085 and the compilation command to build and install the library:
19086
19087 @smallexample @c ada
19088   $ gnatmake -Pmy_lib
19089 @end smallexample
19090
19091 @noindent
19092 It is not entirely trivial to perform manually all the steps required to
19093 produce a library. We recommend that you use the GNAT Project Manager
19094 for this task. In special cases where this is not desired, the necessary
19095 steps are discussed below.
19096
19097 There are various possibilities for compiling the units that make up the
19098 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19099 with a conventional script. For simple libraries, it is also possible to create
19100 a dummy main program which depends upon all the packages that comprise the
19101 interface of the library. This dummy main program can then be given to
19102 @command{gnatmake}, which will ensure that all necessary objects are built.
19103
19104 After this task is accomplished, you should follow the standard procedure
19105 of the underlying operating system to produce the static or shared library.
19106
19107 Here is an example of such a dummy program:
19108 @smallexample @c ada
19109 @group
19110 with My_Lib.Service1;
19111 with My_Lib.Service2;
19112 with My_Lib.Service3;
19113 procedure My_Lib_Dummy is
19114 begin
19115    null;
19116 end;
19117 @end group
19118 @end smallexample
19119
19120 @noindent
19121 Here are the generic commands that will build an archive or a shared library.
19122
19123 @smallexample
19124 # compiling the library
19125 $ gnatmake -c my_lib_dummy.adb
19126
19127 # we don't need the dummy object itself
19128 $ rm my_lib_dummy.o my_lib_dummy.ali
19129
19130 # create an archive with the remaining objects
19131 $ ar rc libmy_lib.a *.o
19132 # some systems may require "ranlib" to be run as well
19133
19134 # or create a shared library
19135 $ gcc -shared -o libmy_lib.so *.o
19136 # some systems may require the code to have been compiled with -fPIC
19137
19138 # remove the object files that are now in the library
19139 $ rm *.o
19140
19141 # Make the ALI files read-only so that gnatmake will not try to
19142 # regenerate the objects that are in the library
19143 $ chmod -w *.ali
19144 @end smallexample
19145
19146 @noindent
19147 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19148 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19149 be accessed by the directive @option{-l@var{xxx}} at link time.
19150
19151 @node Installing a library
19152 @subsection Installing a library
19153 @cindex @code{ADA_PROJECT_PATH}
19154 @cindex @code{GPR_PROJECT_PATH}
19155
19156 @noindent
19157 If you use project files, library installation is part of the library build
19158 process. Thus no further action is needed in order to make use of the
19159 libraries that are built as part of the general application build. A usable
19160 version of the library is installed in the directory specified by the
19161 @code{Library_Dir} attribute of the library project file.
19162
19163 You may want to install a library in a context different from where the library
19164 is built. This situation arises with third party suppliers, who may want
19165 to distribute a library in binary form where the user is not expected to be
19166 able to recompile the library. The simplest option in this case is to provide
19167 a project file slightly different from the one used to build the library, by
19168 using the @code{externally_built} attribute. For instance, the project
19169 file used to build the library in the previous section can be changed into the
19170 following one when the library is installed:
19171
19172 @smallexample @c projectfile
19173 project My_Lib is
19174    for Source_Dirs use ("src1", "src2");
19175    for Library_Name use "mylib";
19176    for Library_Dir use "lib";
19177    for Library_Kind use "dynamic";
19178    for Externally_Built use "true";
19179 end My_lib;
19180 @end smallexample
19181
19182 @noindent
19183 This project file assumes that the directories @file{src1},
19184 @file{src2}, and @file{lib} exist in
19185 the directory containing the project file. The @code{externally_built}
19186 attribute makes it clear to the GNAT builder that it should not attempt to
19187 recompile any of the units from this library. It allows the library provider to
19188 restrict the source set to the minimum necessary for clients to make use of the
19189 library as described in the first section of this chapter. It is the
19190 responsibility of the library provider to install the necessary sources, ALI
19191 files and libraries in the directories mentioned in the project file. For
19192 convenience, the user's library project file should be installed in a location
19193 that will be searched automatically by the GNAT
19194 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19195 environment variable (@pxref{Importing Projects}), and also the default GNAT
19196 library location that can be queried with @command{gnatls -v} and is usually of
19197 the form $gnat_install_root/lib/gnat.
19198
19199 When project files are not an option, it is also possible, but not recommended,
19200 to install the library so that the sources needed to use the library are on the
19201 Ada source path and the ALI files & libraries be on the Ada Object path (see
19202 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19203 administrator can place general-purpose libraries in the default compiler
19204 paths, by specifying the libraries' location in the configuration files
19205 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19206 must be located in the GNAT installation tree at the same place as the gcc spec
19207 file. The location of the gcc spec file can be determined as follows:
19208 @smallexample
19209 $ gcc -v
19210 @end smallexample
19211
19212 @noindent
19213 The configuration files mentioned above have a simple format: each line
19214 must contain one unique directory name.
19215 Those names are added to the corresponding path
19216 in their order of appearance in the file. The names can be either absolute
19217 or relative; in the latter case, they are relative to where theses files
19218 are located.
19219
19220 The files @file{ada_source_path} and @file{ada_object_path} might not be
19221 present in a
19222 GNAT installation, in which case, GNAT will look for its run-time library in
19223 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19224 objects and @file{ALI} files). When the files exist, the compiler does not
19225 look in @file{adainclude} and @file{adalib}, and thus the
19226 @file{ada_source_path} file
19227 must contain the location for the GNAT run-time sources (which can simply
19228 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19229 contain the location for the GNAT run-time objects (which can simply
19230 be @file{adalib}).
19231
19232 You can also specify a new default path to the run-time library at compilation
19233 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19234 the run-time library you want your program to be compiled with. This switch is
19235 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19236 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19237
19238 It is possible to install a library before or after the standard GNAT
19239 library, by reordering the lines in the configuration files. In general, a
19240 library must be installed before the GNAT library if it redefines
19241 any part of it.
19242
19243 @node Using a library
19244 @subsection Using a library
19245
19246 @noindent Once again, the project facility greatly simplifies the use of
19247 libraries. In this context, using a library is just a matter of adding a
19248 @code{with} clause in the user project. For instance, to make use of the
19249 library @code{My_Lib} shown in examples in earlier sections, you can
19250 write:
19251
19252 @smallexample @c projectfile
19253 with "my_lib";
19254 project My_Proj is
19255   @dots{}
19256 end My_Proj;
19257 @end smallexample
19258
19259 Even if you have a third-party, non-Ada library, you can still use GNAT's
19260 Project Manager facility to provide a wrapper for it. For example, the
19261 following project, when @code{with}ed by your main project, will link with the
19262 third-party library @file{liba.a}:
19263
19264 @smallexample @c projectfile
19265 @group
19266 project Liba is
19267    for Externally_Built use "true";
19268    for Source_Files use ();
19269    for Library_Dir use "lib";
19270    for Library_Name use "a";
19271    for Library_Kind use "static";
19272 end Liba;
19273 @end group
19274 @end smallexample
19275 This is an alternative to the use of @code{pragma Linker_Options}. It is
19276 especially interesting in the context of systems with several interdependent
19277 static libraries where finding a proper linker order is not easy and best be
19278 left to the tools having visibility over project dependence information.
19279
19280 @noindent
19281 In order to use an Ada library manually, you need to make sure that this
19282 library is on both your source and object path
19283 (see @ref{Search Paths and the Run-Time Library (RTL)}
19284 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19285 in an archive or a shared library, you need to specify the desired
19286 library at link time.
19287
19288 For example, you can use the library @file{mylib} installed in
19289 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19290
19291 @smallexample
19292 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19293   -largs -lmy_lib
19294 @end smallexample
19295
19296 @noindent
19297 This can be expressed more simply:
19298 @smallexample
19299 $ gnatmake my_appl
19300 @end smallexample
19301 @noindent
19302 when the following conditions are met:
19303 @itemize @bullet
19304 @item
19305 @file{/dir/my_lib_src} has been added by the user to the environment
19306 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19307 @file{ada_source_path}
19308 @item
19309 @file{/dir/my_lib_obj} has been added by the user to the environment
19310 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19311 @file{ada_object_path}
19312 @item
19313 a pragma @code{Linker_Options} has been added to one of the sources.
19314 For example:
19315
19316 @smallexample @c ada
19317 pragma Linker_Options ("-lmy_lib");
19318 @end smallexample
19319 @end itemize
19320
19321 @node Stand-alone Ada Libraries
19322 @section Stand-alone Ada Libraries
19323 @cindex Stand-alone library, building, using
19324
19325 @menu
19326 * Introduction to Stand-alone Libraries::
19327 * Building a Stand-alone Library::
19328 * Creating a Stand-alone Library to be used in a non-Ada context::
19329 * Restrictions in Stand-alone Libraries::
19330 @end menu
19331
19332 @node Introduction to Stand-alone Libraries
19333 @subsection Introduction to Stand-alone Libraries
19334
19335 @noindent
19336 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19337 necessary code to
19338 elaborate the Ada units that are included in the library. In contrast with
19339 an ordinary library, which consists of all sources, objects and @file{ALI}
19340 files of the
19341 library, a SAL may specify a restricted subset of compilation units
19342 to serve as a library interface. In this case, the fully
19343 self-sufficient set of files will normally consist of an objects
19344 archive, the sources of interface units' specs, and the @file{ALI}
19345 files of interface units.
19346 If an interface spec contains a generic unit or an inlined subprogram,
19347 the body's
19348 source must also be provided; if the units that must be provided in the source
19349 form depend on other units, the source and @file{ALI} files of those must
19350 also be provided.
19351
19352 The main purpose of a SAL is to minimize the recompilation overhead of client
19353 applications when a new version of the library is installed. Specifically,
19354 if the interface sources have not changed, client applications do not need to
19355 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19356 version, controlled by @code{Library_Version} attribute, is not changed,
19357 then the clients do not need to be relinked.
19358
19359 SALs also allow the library providers to minimize the amount of library source
19360 text exposed to the clients.  Such ``information hiding'' might be useful or
19361 necessary for various reasons.
19362
19363 Stand-alone libraries are also well suited to be used in an executable whose
19364 main routine is not written in Ada.
19365
19366 @node Building a Stand-alone Library
19367 @subsection Building a Stand-alone Library
19368
19369 @noindent
19370 GNAT's Project facility provides a simple way of building and installing
19371 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19372 To be a Stand-alone Library Project, in addition to the two attributes
19373 that make a project a Library Project (@code{Library_Name} and
19374 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19375 @code{Library_Interface} must be defined.  For example:
19376
19377 @smallexample @c projectfile
19378 @group
19379    for Library_Dir use "lib_dir";
19380    for Library_Name use "dummy";
19381    for Library_Interface use ("int1", "int1.child");
19382 @end group
19383 @end smallexample
19384
19385 @noindent
19386 Attribute @code{Library_Interface} has a non-empty string list value,
19387 each string in the list designating a unit contained in an immediate source
19388 of the project file.
19389
19390 When a Stand-alone Library is built, first the binder is invoked to build
19391 a package whose name depends on the library name
19392 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19393 This binder-generated package includes initialization and
19394 finalization procedures whose
19395 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19396 in the example
19397 above). The object corresponding to this package is included in the library.
19398
19399 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19400 calling of these procedures if a static SAL is built, or if a shared SAL
19401 is built
19402 with the project-level attribute @code{Library_Auto_Init} set to
19403 @code{"false"}.
19404
19405 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19406 (those that are listed in attribute @code{Library_Interface}) are copied to
19407 the Library Directory. As a consequence, only the Interface Units may be
19408 imported from Ada units outside of the library. If other units are imported,
19409 the binding phase will fail.
19410
19411 The attribute @code{Library_Src_Dir} may be specified for a
19412 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19413 single string value. Its value must be the path (absolute or relative to the
19414 project directory) of an existing directory. This directory cannot be the
19415 object directory or one of the source directories, but it can be the same as
19416 the library directory. The sources of the Interface
19417 Units of the library that are needed by an Ada client of the library will be
19418 copied to the designated directory, called the Interface Copy directory.
19419 These sources include the specs of the Interface Units, but they may also
19420 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19421 are used, or when there is a generic unit in the spec. Before the sources
19422 are copied to the Interface Copy directory, an attempt is made to delete all
19423 files in the Interface Copy directory.
19424
19425 Building stand-alone libraries by hand is somewhat tedious, but for those
19426 occasions when it is necessary here are the steps that you need to perform:
19427 @itemize @bullet
19428 @item
19429 Compile all library sources.
19430
19431 @item
19432 Invoke the binder with the switch @option{-n} (No Ada main program),
19433 with all the @file{ALI} files of the interfaces, and
19434 with the switch @option{-L} to give specific names to the @code{init}
19435 and @code{final} procedures.  For example:
19436 @smallexample
19437   gnatbind -n int1.ali int2.ali -Lsal1
19438 @end smallexample
19439
19440 @item
19441 Compile the binder generated file:
19442 @smallexample
19443   gcc -c b~int2.adb
19444 @end smallexample
19445
19446 @item
19447 Link the dynamic library with all the necessary object files,
19448 indicating to the linker the names of the @code{init} (and possibly
19449 @code{final}) procedures for automatic initialization (and finalization).
19450 The built library should be placed in a directory different from
19451 the object directory.
19452
19453 @item
19454 Copy the @code{ALI} files of the interface to the library directory,
19455 add in this copy an indication that it is an interface to a SAL
19456 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19457 with letter ``P'') and make the modified copy of the @file{ALI} file
19458 read-only.
19459 @end itemize
19460
19461 @noindent
19462 Using SALs is not different from using other libraries
19463 (see @ref{Using a library}).
19464
19465 @node Creating a Stand-alone Library to be used in a non-Ada context
19466 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19467
19468 @noindent
19469 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19470 a non-Ada context.
19471
19472 The only extra step required is to ensure that library interface subprograms
19473 are compatible with the main program, by means of @code{pragma Export}
19474 or @code{pragma Convention}.
19475
19476 Here is an example of simple library interface for use with C main program:
19477
19478 @smallexample @c ada
19479 package My_Package is
19480
19481    procedure Do_Something;
19482    pragma Export (C, Do_Something, "do_something");
19483
19484    procedure Do_Something_Else;
19485    pragma Export (C, Do_Something_Else, "do_something_else");
19486
19487 end My_Package;
19488 @end smallexample
19489
19490 @noindent
19491 On the foreign language side, you must provide a ``foreign'' view of the
19492 library interface; remember that it should contain elaboration routines in
19493 addition to interface subprograms.
19494
19495 The example below shows the content of @code{mylib_interface.h} (note
19496 that there is no rule for the naming of this file, any name can be used)
19497 @smallexample
19498 /* the library elaboration procedure */
19499 extern void mylibinit (void);
19500
19501 /* the library finalization procedure */
19502 extern void mylibfinal (void);
19503
19504 /* the interface exported by the library */
19505 extern void do_something (void);
19506 extern void do_something_else (void);
19507 @end smallexample
19508
19509 @noindent
19510 Libraries built as explained above can be used from any program, provided
19511 that the elaboration procedures (named @code{mylibinit} in the previous
19512 example) are called before the library services are used. Any number of
19513 libraries can be used simultaneously, as long as the elaboration
19514 procedure of each library is called.
19515
19516 Below is an example of a C program that uses the @code{mylib} library.
19517
19518 @smallexample
19519 #include "mylib_interface.h"
19520
19521 int
19522 main (void)
19523 @{
19524    /* First, elaborate the library before using it */
19525    mylibinit ();
19526
19527    /* Main program, using the library exported entities */
19528    do_something ();
19529    do_something_else ();
19530
19531    /* Library finalization at the end of the program */
19532    mylibfinal ();
19533    return 0;
19534 @}
19535 @end smallexample
19536
19537 @noindent
19538 Note that invoking any library finalization procedure generated by
19539 @code{gnatbind} shuts down the Ada run-time environment.
19540 Consequently, the
19541 finalization of all Ada libraries must be performed at the end of the program.
19542 No call to these libraries or to the Ada run-time library should be made
19543 after the finalization phase.
19544
19545 @node Restrictions in Stand-alone Libraries
19546 @subsection Restrictions in Stand-alone Libraries
19547
19548 @noindent
19549 The pragmas listed below should be used with caution inside libraries,
19550 as they can create incompatibilities with other Ada libraries:
19551 @itemize @bullet
19552 @item pragma @code{Locking_Policy}
19553 @item pragma @code{Queuing_Policy}
19554 @item pragma @code{Task_Dispatching_Policy}
19555 @item pragma @code{Unreserve_All_Interrupts}
19556 @end itemize
19557
19558 @noindent
19559 When using a library that contains such pragmas, the user must make sure
19560 that all libraries use the same pragmas with the same values. Otherwise,
19561 @code{Program_Error} will
19562 be raised during the elaboration of the conflicting
19563 libraries. The usage of these pragmas and its consequences for the user
19564 should therefore be well documented.
19565
19566 Similarly, the traceback in the exception occurrence mechanism should be
19567 enabled or disabled in a consistent manner across all libraries.
19568 Otherwise, Program_Error will be raised during the elaboration of the
19569 conflicting libraries.
19570
19571 If the @code{Version} or @code{Body_Version}
19572 attributes are used inside a library, then you need to
19573 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19574 libraries, so that version identifiers can be properly computed.
19575 In practice these attributes are rarely used, so this is unlikely
19576 to be a consideration.
19577
19578 @node  Rebuilding the GNAT Run-Time Library
19579 @section Rebuilding the GNAT Run-Time Library
19580 @cindex GNAT Run-Time Library, rebuilding
19581 @cindex Building the GNAT Run-Time Library
19582 @cindex Rebuilding the GNAT Run-Time Library
19583 @cindex Run-Time Library, rebuilding
19584
19585 @noindent
19586 It may be useful to recompile the GNAT library in various contexts, the
19587 most important one being the use of partition-wide configuration pragmas
19588 such as @code{Normalize_Scalars}. A special Makefile called
19589 @code{Makefile.adalib} is provided to that effect and can be found in
19590 the directory containing the GNAT library. The location of this
19591 directory depends on the way the GNAT environment has been installed and can
19592 be determined by means of the command:
19593
19594 @smallexample
19595 $ gnatls -v
19596 @end smallexample
19597
19598 @noindent
19599 The last entry in the object search path usually contains the
19600 gnat library. This Makefile contains its own documentation and in
19601 particular the set of instructions needed to rebuild a new library and
19602 to use it.
19603
19604 @node Using the GNU make Utility
19605 @chapter Using the GNU @code{make} Utility
19606 @findex make
19607
19608 @noindent
19609 This chapter offers some examples of makefiles that solve specific
19610 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19611 make, make, GNU @code{make}}), nor does it try to replace the
19612 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19613
19614 All the examples in this section are specific to the GNU version of
19615 make. Although @command{make} is a standard utility, and the basic language
19616 is the same, these examples use some advanced features found only in
19617 @code{GNU make}.
19618
19619 @menu
19620 * Using gnatmake in a Makefile::
19621 * Automatically Creating a List of Directories::
19622 * Generating the Command Line Switches::
19623 * Overcoming Command Line Length Limits::
19624 @end menu
19625
19626 @node Using gnatmake in a Makefile
19627 @section Using gnatmake in a Makefile
19628 @findex makefile
19629 @cindex GNU make
19630
19631 @noindent
19632 Complex project organizations can be handled in a very powerful way by
19633 using GNU make combined with gnatmake. For instance, here is a Makefile
19634 which allows you to build each subsystem of a big project into a separate
19635 shared library. Such a makefile allows you to significantly reduce the link
19636 time of very big applications while maintaining full coherence at
19637 each step of the build process.
19638
19639 The list of dependencies are handled automatically by
19640 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19641 the appropriate directories.
19642
19643 Note that you should also read the example on how to automatically
19644 create the list of directories
19645 (@pxref{Automatically Creating a List of Directories})
19646 which might help you in case your project has a lot of subdirectories.
19647
19648 @smallexample
19649 @iftex
19650 @leftskip=0cm
19651 @font@heightrm=cmr8
19652 @heightrm
19653 @end iftex
19654 ## This Makefile is intended to be used with the following directory
19655 ## configuration:
19656 ##  - The sources are split into a series of csc (computer software components)
19657 ##    Each of these csc is put in its own directory.
19658 ##    Their name are referenced by the directory names.
19659 ##    They will be compiled into shared library (although this would also work
19660 ##    with static libraries
19661 ##  - The main program (and possibly other packages that do not belong to any
19662 ##    csc is put in the top level directory (where the Makefile is).
19663 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19664 ##                    \_ second_csc (sources) __ lib (will contain the library)
19665 ##                    \_ @dots{}
19666 ## Although this Makefile is build for shared library, it is easy to modify
19667 ## to build partial link objects instead (modify the lines with -shared and
19668 ## gnatlink below)
19669 ##
19670 ## With this makefile, you can change any file in the system or add any new
19671 ## file, and everything will be recompiled correctly (only the relevant shared
19672 ## objects will be recompiled, and the main program will be re-linked).
19673
19674 # The list of computer software component for your project. This might be
19675 # generated automatically.
19676 CSC_LIST=aa bb cc
19677
19678 # Name of the main program (no extension)
19679 MAIN=main
19680
19681 # If we need to build objects with -fPIC, uncomment the following line
19682 #NEED_FPIC=-fPIC
19683
19684 # The following variable should give the directory containing libgnat.so
19685 # You can get this directory through 'gnatls -v'. This is usually the last
19686 # directory in the Object_Path.
19687 GLIB=@dots{}
19688
19689 # The directories for the libraries
19690 # (This macro expands the list of CSC to the list of shared libraries, you
19691 # could simply use the expanded form:
19692 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19693 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19694
19695 $@{MAIN@}: objects $@{LIB_DIR@}
19696     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19697     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19698
19699 objects::
19700     # recompile the sources
19701     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19702
19703 # Note: In a future version of GNAT, the following commands will be simplified
19704 # by a new tool, gnatmlib
19705 $@{LIB_DIR@}:
19706     mkdir -p $@{dir $@@ @}
19707     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19708     cd $@{dir $@@ @} && cp -f ../*.ali .
19709
19710 # The dependencies for the modules
19711 # Note that we have to force the expansion of *.o, since in some cases
19712 # make won't be able to do it itself.
19713 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19714 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19715 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19716
19717 # Make sure all of the shared libraries are in the path before starting the
19718 # program
19719 run::
19720     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19721
19722 clean::
19723     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19724     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19725     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19726     $@{RM@} *.o *.ali $@{MAIN@}
19727 @end smallexample
19728
19729 @node Automatically Creating a List of Directories
19730 @section Automatically Creating a List of Directories
19731
19732 @noindent
19733 In most makefiles, you will have to specify a list of directories, and
19734 store it in a variable. For small projects, it is often easier to
19735 specify each of them by hand, since you then have full control over what
19736 is the proper order for these directories, which ones should be
19737 included.
19738
19739 However, in larger projects, which might involve hundreds of
19740 subdirectories, it might be more convenient to generate this list
19741 automatically.
19742
19743 The example below presents two methods. The first one, although less
19744 general, gives you more control over the list. It involves wildcard
19745 characters, that are automatically expanded by @command{make}. Its
19746 shortcoming is that you need to explicitly specify some of the
19747 organization of your project, such as for instance the directory tree
19748 depth, whether some directories are found in a separate tree, @enddots{}
19749
19750 The second method is the most general one. It requires an external
19751 program, called @command{find}, which is standard on all Unix systems. All
19752 the directories found under a given root directory will be added to the
19753 list.
19754
19755 @smallexample
19756 @iftex
19757 @leftskip=0cm
19758 @font@heightrm=cmr8
19759 @heightrm
19760 @end iftex
19761 # The examples below are based on the following directory hierarchy:
19762 # All the directories can contain any number of files
19763 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19764 #                       ->  ab
19765 #                       ->  ac
19766 #                ->  b  ->  ba  ->  baa
19767 #                       ->  bb
19768 #                       ->  bc
19769 # This Makefile creates a variable called DIRS, that can be reused any time
19770 # you need this list (see the other examples in this section)
19771
19772 # The root of your project's directory hierarchy
19773 ROOT_DIRECTORY=.
19774
19775 ####
19776 # First method: specify explicitly the list of directories
19777 # This allows you to specify any subset of all the directories you need.
19778 ####
19779
19780 DIRS := a/aa/ a/ab/ b/ba/
19781
19782 ####
19783 # Second method: use wildcards
19784 # Note that the argument(s) to wildcard below should end with a '/'.
19785 # Since wildcards also return file names, we have to filter them out
19786 # to avoid duplicate directory names.
19787 # We thus use make's @code{dir} and @code{sort} functions.
19788 # It sets DIRs to the following value (note that the directories aaa and baa
19789 # are not given, unless you change the arguments to wildcard).
19790 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19791 ####
19792
19793 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19794                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19795
19796 ####
19797 # Third method: use an external program
19798 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19799 # This is the most complete command: it sets DIRs to the following value:
19800 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19801 ####
19802
19803 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19804
19805 @end smallexample
19806
19807 @node Generating the Command Line Switches
19808 @section Generating the Command Line Switches
19809
19810 @noindent
19811 Once you have created the list of directories as explained in the
19812 previous section (@pxref{Automatically Creating a List of Directories}),
19813 you can easily generate the command line arguments to pass to gnatmake.
19814
19815 For the sake of completeness, this example assumes that the source path
19816 is not the same as the object path, and that you have two separate lists
19817 of directories.
19818
19819 @smallexample
19820 # see "Automatically creating a list of directories" to create
19821 # these variables
19822 SOURCE_DIRS=
19823 OBJECT_DIRS=
19824
19825 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19826 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19827
19828 all:
19829         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19830 @end smallexample
19831
19832 @node Overcoming Command Line Length Limits
19833 @section Overcoming Command Line Length Limits
19834
19835 @noindent
19836 One problem that might be encountered on big projects is that many
19837 operating systems limit the length of the command line. It is thus hard to give
19838 gnatmake the list of source and object directories.
19839
19840 This example shows how you can set up environment variables, which will
19841 make @command{gnatmake} behave exactly as if the directories had been
19842 specified on the command line, but have a much higher length limit (or
19843 even none on most systems).
19844
19845 It assumes that you have created a list of directories in your Makefile,
19846 using one of the methods presented in
19847 @ref{Automatically Creating a List of Directories}.
19848 For the sake of completeness, we assume that the object
19849 path (where the ALI files are found) is different from the sources patch.
19850
19851 Note a small trick in the Makefile below: for efficiency reasons, we
19852 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19853 expanded immediately by @code{make}. This way we overcome the standard
19854 make behavior which is to expand the variables only when they are
19855 actually used.
19856
19857 On Windows, if you are using the standard Windows command shell, you must
19858 replace colons with semicolons in the assignments to these variables.
19859
19860 @smallexample
19861 @iftex
19862 @leftskip=0cm
19863 @font@heightrm=cmr8
19864 @heightrm
19865 @end iftex
19866 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19867 # This is the same thing as putting the -I arguments on the command line.
19868 # (the equivalent of using -aI on the command line would be to define
19869 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19870 # You can of course have different values for these variables.
19871 #
19872 # Note also that we need to keep the previous values of these variables, since
19873 # they might have been set before running 'make' to specify where the GNAT
19874 # library is installed.
19875
19876 # see "Automatically creating a list of directories" to create these
19877 # variables
19878 SOURCE_DIRS=
19879 OBJECT_DIRS=
19880
19881 empty:=
19882 space:=$@{empty@} $@{empty@}
19883 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19884 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19885 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19886 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19887 export ADA_INCLUDE_PATH
19888 export ADA_OBJECT_PATH
19889
19890 all:
19891         gnatmake main_unit
19892 @end smallexample
19893 @end ifclear
19894
19895 @node Memory Management Issues
19896 @chapter Memory Management Issues
19897
19898 @noindent
19899 This chapter describes some useful memory pools provided in the GNAT library
19900 and in particular the GNAT Debug Pool facility, which can be used to detect
19901 incorrect uses of access values (including ``dangling references'').
19902 @ifclear vms
19903 It also describes the @command{gnatmem} tool, which can be used to track down
19904 ``memory leaks''.
19905 @end ifclear
19906
19907 @menu
19908 * Some Useful Memory Pools::
19909 * The GNAT Debug Pool Facility::
19910 @ifclear vms
19911 * The gnatmem Tool::
19912 @end ifclear
19913 @end menu
19914
19915 @node Some Useful Memory Pools
19916 @section Some Useful Memory Pools
19917 @findex Memory Pool
19918 @cindex storage, pool
19919
19920 @noindent
19921 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19922 storage pool. Allocations use the standard system call @code{malloc} while
19923 deallocations use the standard system call @code{free}. No reclamation is
19924 performed when the pool goes out of scope. For performance reasons, the
19925 standard default Ada allocators/deallocators do not use any explicit storage
19926 pools but if they did, they could use this storage pool without any change in
19927 behavior. That is why this storage pool is used  when the user
19928 manages to make the default implicit allocator explicit as in this example:
19929 @smallexample @c ada
19930    type T1 is access Something;
19931     -- no Storage pool is defined for T2
19932    type T2 is access Something_Else;
19933    for T2'Storage_Pool use T1'Storage_Pool;
19934    -- the above is equivalent to
19935    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19936 @end smallexample
19937
19938 @noindent
19939 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19940 pool. The allocation strategy is similar to @code{Pool_Local}'s
19941 except that the all
19942 storage allocated with this pool is reclaimed when the pool object goes out of
19943 scope. This pool provides a explicit mechanism similar to the implicit one
19944 provided by several Ada 83 compilers for allocations performed through a local
19945 access type and whose purpose was to reclaim memory when exiting the
19946 scope of a given local access. As an example, the following program does not
19947 leak memory even though it does not perform explicit deallocation:
19948
19949 @smallexample @c ada
19950 with System.Pool_Local;
19951 procedure Pooloc1 is
19952    procedure Internal is
19953       type A is access Integer;
19954       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19955       for A'Storage_Pool use X;
19956       v : A;
19957    begin
19958       for I in  1 .. 50 loop
19959          v := new Integer;
19960       end loop;
19961    end Internal;
19962 begin
19963    for I in  1 .. 100 loop
19964       Internal;
19965    end loop;
19966 end Pooloc1;
19967 @end smallexample
19968
19969 @noindent
19970 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19971 @code{Storage_Size} is specified for an access type.
19972 The whole storage for the pool is
19973 allocated at once, usually on the stack at the point where the access type is
19974 elaborated. It is automatically reclaimed when exiting the scope where the
19975 access type is defined. This package is not intended to be used directly by the
19976 user and it is implicitly used for each such declaration:
19977
19978 @smallexample @c ada
19979    type T1 is access Something;
19980    for T1'Storage_Size use 10_000;
19981 @end smallexample
19982
19983 @node The GNAT Debug Pool Facility
19984 @section The GNAT Debug Pool Facility
19985 @findex Debug Pool
19986 @cindex storage, pool, memory corruption
19987
19988 @noindent
19989 The use of unchecked deallocation and unchecked conversion can easily
19990 lead to incorrect memory references. The problems generated by such
19991 references are usually difficult to tackle because the symptoms can be
19992 very remote from the origin of the problem. In such cases, it is
19993 very helpful to detect the problem as early as possible. This is the
19994 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19995
19996 In order to use the GNAT specific debugging pool, the user must
19997 associate a debug pool object with each of the access types that may be
19998 related to suspected memory problems. See Ada Reference Manual 13.11.
19999 @smallexample @c ada
20000 type Ptr is access Some_Type;
20001 Pool : GNAT.Debug_Pools.Debug_Pool;
20002 for Ptr'Storage_Pool use Pool;
20003 @end smallexample
20004
20005 @noindent
20006 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
20007 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
20008 allow the user to redefine allocation and deallocation strategies. They
20009 also provide a checkpoint for each dereference, through the use of
20010 the primitive operation @code{Dereference} which is implicitly called at
20011 each dereference of an access value.
20012
20013 Once an access type has been associated with a debug pool, operations on
20014 values of the type may raise four distinct exceptions,
20015 which correspond to four potential kinds of memory corruption:
20016 @itemize @bullet
20017 @item
20018 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
20019 @item
20020 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
20021 @item
20022 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
20023 @item
20024 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
20025 @end itemize
20026
20027 @noindent
20028 For types associated with a Debug_Pool, dynamic allocation is performed using
20029 the standard GNAT allocation routine. References to all allocated chunks of
20030 memory are kept in an internal dictionary. Several deallocation strategies are
20031 provided, whereupon the user can choose to release the memory to the system,
20032 keep it allocated for further invalid access checks, or fill it with an easily
20033 recognizable pattern for debug sessions. The memory pattern is the old IBM
20034 hexadecimal convention: @code{16#DEADBEEF#}.
20035
20036 See the documentation in the file g-debpoo.ads for more information on the
20037 various strategies.
20038
20039 Upon each dereference, a check is made that the access value denotes a
20040 properly allocated memory location. Here is a complete example of use of
20041 @code{Debug_Pools}, that includes typical instances of  memory corruption:
20042 @smallexample @c ada
20043 @iftex
20044 @leftskip=0cm
20045 @end iftex
20046 with Gnat.Io; use Gnat.Io;
20047 with Unchecked_Deallocation;
20048 with Unchecked_Conversion;
20049 with GNAT.Debug_Pools;
20050 with System.Storage_Elements;
20051 with Ada.Exceptions; use Ada.Exceptions;
20052 procedure Debug_Pool_Test is
20053
20054    type T is access Integer;
20055    type U is access all T;
20056
20057    P : GNAT.Debug_Pools.Debug_Pool;
20058    for T'Storage_Pool use P;
20059
20060    procedure Free is new Unchecked_Deallocation (Integer, T);
20061    function UC is new Unchecked_Conversion (U, T);
20062    A, B : aliased T;
20063
20064    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20065
20066 begin
20067    Info (P);
20068    A := new Integer;
20069    B := new Integer;
20070    B := A;
20071    Info (P);
20072    Free (A);
20073    begin
20074       Put_Line (Integer'Image(B.all));
20075    exception
20076       when E : others => Put_Line ("raised: " & Exception_Name (E));
20077    end;
20078    begin
20079       Free (B);
20080    exception
20081       when E : others => Put_Line ("raised: " & Exception_Name (E));
20082    end;
20083    B := UC(A'Access);
20084    begin
20085       Put_Line (Integer'Image(B.all));
20086    exception
20087       when E : others => Put_Line ("raised: " & Exception_Name (E));
20088    end;
20089    begin
20090       Free (B);
20091    exception
20092       when E : others => Put_Line ("raised: " & Exception_Name (E));
20093    end;
20094    Info (P);
20095 end Debug_Pool_Test;
20096 @end smallexample
20097
20098 @noindent
20099 The debug pool mechanism provides the following precise diagnostics on the
20100 execution of this erroneous program:
20101 @smallexample
20102 Debug Pool info:
20103   Total allocated bytes :  0
20104   Total deallocated bytes :  0
20105   Current Water Mark:  0
20106   High Water Mark:  0
20107
20108 Debug Pool info:
20109   Total allocated bytes :  8
20110   Total deallocated bytes :  0
20111   Current Water Mark:  8
20112   High Water Mark:  8
20113
20114 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20115 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20116 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20117 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20118 Debug Pool info:
20119   Total allocated bytes :  8
20120   Total deallocated bytes :  4
20121   Current Water Mark:  4
20122   High Water Mark:  8
20123 @end smallexample
20124
20125 @ifclear vms
20126 @node The gnatmem Tool
20127 @section The @command{gnatmem} Tool
20128 @findex gnatmem
20129
20130 @noindent
20131 The @code{gnatmem} utility monitors dynamic allocation and
20132 deallocation activity in a program, and displays information about
20133 incorrect deallocations and possible sources of memory leaks.
20134 It is designed to work in association with a static runtime library
20135 only and in this context provides three types of information:
20136 @itemize @bullet
20137 @item
20138 General information concerning memory management, such as the total
20139 number of allocations and deallocations, the amount of allocated
20140 memory and the high water mark, i.e.@: the largest amount of allocated
20141 memory in the course of program execution.
20142
20143 @item
20144 Backtraces for all incorrect deallocations, that is to say deallocations
20145 which do not correspond to a valid allocation.
20146
20147 @item
20148 Information on each allocation that is potentially the origin of a memory
20149 leak.
20150 @end itemize
20151
20152 @menu
20153 * Running gnatmem::
20154 * Switches for gnatmem::
20155 * Example of gnatmem Usage::
20156 @end menu
20157
20158 @node Running gnatmem
20159 @subsection Running @code{gnatmem}
20160
20161 @noindent
20162 @code{gnatmem} makes use of the output created by the special version of
20163 allocation and deallocation routines that record call information. This
20164 allows to obtain accurate dynamic memory usage history at a minimal cost to
20165 the execution speed. Note however, that @code{gnatmem} is not supported on
20166 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20167 Solaris and Windows NT/2000/XP (x86).
20168
20169 @noindent
20170 The @code{gnatmem} command has the form
20171
20172 @smallexample
20173    $ gnatmem @ovar{switches} user_program
20174 @end smallexample
20175
20176 @noindent
20177 The program must have been linked with the instrumented version of the
20178 allocation and deallocation routines. This is done by linking with the
20179 @file{libgmem.a} library. For correct symbolic backtrace information,
20180 the user program should be compiled with debugging options
20181 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20182
20183 @smallexample
20184 $ gnatmake -g my_program -largs -lgmem
20185 @end smallexample
20186
20187 @noindent
20188 As library @file{libgmem.a} contains an alternate body for package
20189 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20190 when an executable is linked with library @file{libgmem.a}. It is then not
20191 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20192
20193 @noindent
20194 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20195 This file contains information about all allocations and deallocations
20196 performed by the program. It is produced by the instrumented allocations and
20197 deallocations routines and will be used by @code{gnatmem}.
20198
20199 In order to produce symbolic backtrace information for allocations and
20200 deallocations performed by the GNAT run-time library, you need to use a
20201 version of that library that has been compiled with the @option{-g} switch
20202 (see @ref{Rebuilding the GNAT Run-Time Library}).
20203
20204 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20205 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20206 @option{-i} switch, gnatmem will assume that this file can be found in the
20207 current directory. For example, after you have executed @file{my_program},
20208 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20209
20210 @smallexample
20211 $ gnatmem my_program
20212 @end smallexample
20213
20214 @noindent
20215 This will produce the output with the following format:
20216
20217 *************** debut cc
20218 @smallexample
20219 $ gnatmem my_program
20220
20221 Global information
20222 ------------------
20223    Total number of allocations        :  45
20224    Total number of deallocations      :   6
20225    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20226    High Water Mark                    :  11.40 Kilobytes
20227
20228 .
20229 .
20230 .
20231 Allocation Root # 2
20232 -------------------
20233  Number of non freed allocations    :  11
20234  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20235  High Water Mark                    :   1.27 Kilobytes
20236  Backtrace                          :
20237    my_program.adb:23 my_program.alloc
20238 .
20239 .
20240 .
20241 @end smallexample
20242
20243 The first block of output gives general information. In this case, the
20244 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20245 Unchecked_Deallocation routine occurred.
20246
20247 @noindent
20248 Subsequent paragraphs display  information on all allocation roots.
20249 An allocation root is a specific point in the execution of the program
20250 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20251 construct. This root is represented by an execution backtrace (or subprogram
20252 call stack). By default the backtrace depth for allocations roots is 1, so
20253 that a root corresponds exactly to a source location. The backtrace can
20254 be made deeper, to make the root more specific.
20255
20256 @node Switches for gnatmem
20257 @subsection Switches for @code{gnatmem}
20258
20259 @noindent
20260 @code{gnatmem} recognizes the following switches:
20261
20262 @table @option
20263
20264 @item -q
20265 @cindex @option{-q} (@code{gnatmem})
20266 Quiet. Gives the minimum output needed to identify the origin of the
20267 memory leaks. Omits statistical information.
20268
20269 @item @var{N}
20270 @cindex @var{N} (@code{gnatmem})
20271 N is an integer literal (usually between 1 and 10) which controls the
20272 depth of the backtraces defining allocation root. The default value for
20273 N is 1. The deeper the backtrace, the more precise the localization of
20274 the root. Note that the total number of roots can depend on this
20275 parameter. This parameter must be specified @emph{before} the name of the
20276 executable to be analyzed, to avoid ambiguity.
20277
20278 @item -b n
20279 @cindex @option{-b} (@code{gnatmem})
20280 This switch has the same effect as just depth parameter.
20281
20282 @item -i @var{file}
20283 @cindex @option{-i} (@code{gnatmem})
20284 Do the @code{gnatmem} processing starting from @file{file}, rather than
20285 @file{gmem.out} in the current directory.
20286
20287 @item -m n
20288 @cindex @option{-m} (@code{gnatmem})
20289 This switch causes @code{gnatmem} to mask the allocation roots that have less
20290 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20291 examine even the roots that didn't result in leaks.
20292
20293 @item -s order
20294 @cindex @option{-s} (@code{gnatmem})
20295 This switch causes @code{gnatmem} to sort the allocation roots according to the
20296 specified order of sort criteria, each identified by a single letter. The
20297 currently supported criteria are @code{n, h, w} standing respectively for
20298 number of unfreed allocations, high watermark, and final watermark
20299 corresponding to a specific root. The default order is @code{nwh}.
20300
20301 @end table
20302
20303 @node Example of gnatmem Usage
20304 @subsection Example of @code{gnatmem} Usage
20305
20306 @noindent
20307 The following example shows the use of @code{gnatmem}
20308 on a simple memory-leaking program.
20309 Suppose that we have the following Ada program:
20310
20311 @smallexample @c ada
20312 @group
20313 @cartouche
20314 with Unchecked_Deallocation;
20315 procedure Test_Gm is
20316
20317    type T is array (1..1000) of Integer;
20318    type Ptr is access T;
20319    procedure Free is new Unchecked_Deallocation (T, Ptr);
20320    A : Ptr;
20321
20322    procedure My_Alloc is
20323    begin
20324       A := new T;
20325    end My_Alloc;
20326
20327    procedure My_DeAlloc is
20328       B : Ptr := A;
20329    begin
20330       Free (B);
20331    end My_DeAlloc;
20332
20333 begin
20334    My_Alloc;
20335    for I in 1 .. 5 loop
20336       for J in I .. 5 loop
20337          My_Alloc;
20338       end loop;
20339       My_Dealloc;
20340    end loop;
20341 end;
20342 @end cartouche
20343 @end group
20344 @end smallexample
20345
20346 @noindent
20347 The program needs to be compiled with debugging option and linked with
20348 @code{gmem} library:
20349
20350 @smallexample
20351 $ gnatmake -g test_gm -largs -lgmem
20352 @end smallexample
20353
20354 @noindent
20355 Then we execute the program as usual:
20356
20357 @smallexample
20358 $ test_gm
20359 @end smallexample
20360
20361 @noindent
20362 Then @code{gnatmem} is invoked simply with
20363 @smallexample
20364 $ gnatmem test_gm
20365 @end smallexample
20366
20367 @noindent
20368 which produces the following output (result may vary on different platforms):
20369
20370 @smallexample
20371 Global information
20372 ------------------
20373    Total number of allocations        :  18
20374    Total number of deallocations      :   5
20375    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20376    High Water Mark                    :  56.90 Kilobytes
20377
20378 Allocation Root # 1
20379 -------------------
20380  Number of non freed allocations    :  11
20381  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20382  High Water Mark                    :  46.88 Kilobytes
20383  Backtrace                          :
20384    test_gm.adb:11 test_gm.my_alloc
20385
20386 Allocation Root # 2
20387 -------------------
20388  Number of non freed allocations    :   1
20389  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20390  High Water Mark                    :  10.02 Kilobytes
20391  Backtrace                          :
20392    s-secsta.adb:81 system.secondary_stack.ss_init
20393
20394 Allocation Root # 3
20395 -------------------
20396  Number of non freed allocations    :   1
20397  Final Water Mark (non freed mem)   :  12 Bytes
20398  High Water Mark                    :  12 Bytes
20399  Backtrace                          :
20400    s-secsta.adb:181 system.secondary_stack.ss_init
20401 @end smallexample
20402
20403 @noindent
20404 Note that the GNAT run time contains itself a certain number of
20405 allocations that have no  corresponding deallocation,
20406 as shown here for root #2 and root
20407 #3. This is a normal behavior when the number of non-freed allocations
20408 is one, it allocates dynamic data structures that the run time needs for
20409 the complete lifetime of the program. Note also that there is only one
20410 allocation root in the user program with a single line back trace:
20411 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20412 program shows that 'My_Alloc' is called at 2 different points in the
20413 source (line 21 and line 24). If those two allocation roots need to be
20414 distinguished, the backtrace depth parameter can be used:
20415
20416 @smallexample
20417 $ gnatmem 3 test_gm
20418 @end smallexample
20419
20420 @noindent
20421 which will give the following output:
20422
20423 @smallexample
20424 Global information
20425 ------------------
20426    Total number of allocations        :  18
20427    Total number of deallocations      :   5
20428    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20429    High Water Mark                    :  56.90 Kilobytes
20430
20431 Allocation Root # 1
20432 -------------------
20433  Number of non freed allocations    :  10
20434  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20435  High Water Mark                    :  42.97 Kilobytes
20436  Backtrace                          :
20437    test_gm.adb:11 test_gm.my_alloc
20438    test_gm.adb:24 test_gm
20439    b_test_gm.c:52 main
20440
20441 Allocation Root # 2
20442 -------------------
20443  Number of non freed allocations    :   1
20444  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20445  High Water Mark                    :  10.02 Kilobytes
20446  Backtrace                          :
20447    s-secsta.adb:81  system.secondary_stack.ss_init
20448    s-secsta.adb:283 <system__secondary_stack___elabb>
20449    b_test_gm.c:33   adainit
20450
20451 Allocation Root # 3
20452 -------------------
20453  Number of non freed allocations    :   1
20454  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20455  High Water Mark                    :   3.91 Kilobytes
20456  Backtrace                          :
20457    test_gm.adb:11 test_gm.my_alloc
20458    test_gm.adb:21 test_gm
20459    b_test_gm.c:52 main
20460
20461 Allocation Root # 4
20462 -------------------
20463  Number of non freed allocations    :   1
20464  Final Water Mark (non freed mem)   :  12 Bytes
20465  High Water Mark                    :  12 Bytes
20466  Backtrace                          :
20467    s-secsta.adb:181 system.secondary_stack.ss_init
20468    s-secsta.adb:283 <system__secondary_stack___elabb>
20469    b_test_gm.c:33   adainit
20470 @end smallexample
20471
20472 @noindent
20473 The allocation root #1 of the first example has been split in 2 roots #1
20474 and #3 thanks to the more precise associated backtrace.
20475
20476 @end ifclear
20477
20478 @node Stack Related Facilities
20479 @chapter Stack Related Facilities
20480
20481 @noindent
20482 This chapter describes some useful tools associated with stack
20483 checking and analysis. In
20484 particular, it deals with dynamic and static stack usage measurements.
20485
20486 @menu
20487 * Stack Overflow Checking::
20488 * Static Stack Usage Analysis::
20489 * Dynamic Stack Usage Analysis::
20490 @end menu
20491
20492 @node Stack Overflow Checking
20493 @section Stack Overflow Checking
20494 @cindex Stack Overflow Checking
20495 @cindex -fstack-check
20496
20497 @noindent
20498 For most operating systems, @command{gcc} does not perform stack overflow
20499 checking by default. This means that if the main environment task or
20500 some other task exceeds the available stack space, then unpredictable
20501 behavior will occur. Most native systems offer some level of protection by
20502 adding a guard page at the end of each task stack. This mechanism is usually
20503 not enough for dealing properly with stack overflow situations because
20504 a large local variable could ``jump'' above the guard page.
20505 Furthermore, when the
20506 guard page is hit, there may not be any space left on the stack for executing
20507 the exception propagation code. Enabling stack checking avoids
20508 such situations.
20509
20510 To activate stack checking, compile all units with the gcc option
20511 @option{-fstack-check}. For example:
20512
20513 @smallexample
20514 gcc -c -fstack-check package1.adb
20515 @end smallexample
20516
20517 @noindent
20518 Units compiled with this option will generate extra instructions to check
20519 that any use of the stack (for procedure calls or for declaring local
20520 variables in declare blocks) does not exceed the available stack space.
20521 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20522
20523 For declared tasks, the stack size is controlled by the size
20524 given in an applicable @code{Storage_Size} pragma or by the value specified
20525 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20526 the default size as defined in the GNAT runtime otherwise.
20527
20528 For the environment task, the stack size depends on
20529 system defaults and is unknown to the compiler. Stack checking
20530 may still work correctly if a fixed
20531 size stack is allocated, but this cannot be guaranteed.
20532 @ifclear vms
20533 To ensure that a clean exception is signalled for stack
20534 overflow, set the environment variable
20535 @env{GNAT_STACK_LIMIT} to indicate the maximum
20536 stack area that can be used, as in:
20537 @cindex GNAT_STACK_LIMIT
20538
20539 @smallexample
20540 SET GNAT_STACK_LIMIT 1600
20541 @end smallexample
20542
20543 @noindent
20544 The limit is given in kilobytes, so the above declaration would
20545 set the stack limit of the environment task to 1.6 megabytes.
20546 Note that the only purpose of this usage is to limit the amount
20547 of stack used by the environment task. If it is necessary to
20548 increase the amount of stack for the environment task, then this
20549 is an operating systems issue, and must be addressed with the
20550 appropriate operating systems commands.
20551 @end ifclear
20552 @ifset vms
20553 To have a fixed size stack in the environment task, the stack must be put
20554 in the P0 address space and its size specified.  Use these switches to
20555 create a p0 image:
20556
20557 @smallexample
20558 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20559 @end smallexample
20560
20561 @noindent
20562 The quotes are required to keep case.  The number after @samp{STACK=} is the
20563 size of the environmental task stack in pagelets (512 bytes).  In this example
20564 the stack size is about 2 megabytes.
20565
20566 @noindent
20567 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20568 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20569 more details about the @option{/p0image} qualifier and the @option{stack}
20570 option.
20571 @end ifset
20572
20573 @node Static Stack Usage Analysis
20574 @section Static Stack Usage Analysis
20575 @cindex Static Stack Usage Analysis
20576 @cindex -fstack-usage
20577
20578 @noindent
20579 A unit compiled with @option{-fstack-usage} will generate an extra file
20580 that specifies
20581 the maximum amount of stack used, on a per-function basis.
20582 The file has the same
20583 basename as the target object file with a @file{.su} extension.
20584 Each line of this file is made up of three fields:
20585
20586 @itemize
20587 @item
20588 The name of the function.
20589 @item
20590 A number of bytes.
20591 @item
20592 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20593 @end itemize
20594
20595 The second field corresponds to the size of the known part of the function
20596 frame.
20597
20598 The qualifier @code{static} means that the function frame size
20599 is purely static.
20600 It usually means that all local variables have a static size.
20601 In this case, the second field is a reliable measure of the function stack
20602 utilization.
20603
20604 The qualifier @code{dynamic} means that the function frame size is not static.
20605 It happens mainly when some local variables have a dynamic size. When this
20606 qualifier appears alone, the second field is not a reliable measure
20607 of the function stack analysis. When it is qualified with  @code{bounded}, it
20608 means that the second field is a reliable maximum of the function stack
20609 utilization.
20610
20611 @node Dynamic Stack Usage Analysis
20612 @section Dynamic Stack Usage Analysis
20613
20614 @noindent
20615 It is possible to measure the maximum amount of stack used by a task, by
20616 adding a switch to @command{gnatbind}, as:
20617
20618 @smallexample
20619 $ gnatbind -u0 file
20620 @end smallexample
20621
20622 @noindent
20623 With this option, at each task termination, its stack usage is  output on
20624 @file{stderr}.
20625 It is not always convenient to output the stack usage when the program
20626 is still running. Hence, it is possible to delay this output until program
20627 termination. for a given number of tasks specified as the argument of the
20628 @option{-u} option. For instance:
20629
20630 @smallexample
20631 $ gnatbind -u100 file
20632 @end smallexample
20633
20634 @noindent
20635 will buffer the stack usage information of the first 100 tasks to terminate and
20636 output this info at program termination. Results are displayed in four
20637 columns:
20638
20639 @noindent
20640 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20641
20642 @noindent
20643 where:
20644
20645 @table @emph
20646 @item Index
20647 is a number associated with each task.
20648
20649 @item Task Name
20650 is the name of the task analyzed.
20651
20652 @item Stack Size
20653 is the maximum size for the stack.
20654
20655 @item Stack Usage
20656 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20657 is not entirely analyzed, and it's not possible to know exactly how
20658 much has actually been used. The report thus contains the theoretical stack usage
20659 (Value) and the possible variation (Variation) around this value.
20660
20661 @end table
20662
20663 @noindent
20664 The environment task stack, e.g., the stack that contains the main unit, is
20665 only processed when the environment variable GNAT_STACK_LIMIT is set.
20666
20667
20668 @c *********************************
20669 @c *            GNATCHECK          *
20670 @c *********************************
20671 @node Verifying Properties Using gnatcheck
20672 @chapter Verifying Properties Using @command{gnatcheck}
20673 @findex gnatcheck
20674 @cindex @command{gnatcheck}
20675
20676 @noindent
20677 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20678 of Ada source files according to a given set of semantic rules.
20679 @cindex ASIS
20680
20681 In order to check compliance with a given rule, @command{gnatcheck} has to
20682 semantically analyze the Ada sources.
20683 Therefore, checks can only be performed on
20684 legal Ada units. Moreover, when a unit depends semantically upon units located
20685 outside the current directory, the source search path has to be provided when
20686 calling @command{gnatcheck}, either through a specified project file or
20687 through @command{gnatcheck} switches as described below.
20688
20689 A number of rules are predefined in @command{gnatcheck} and are described
20690 later in this chapter.
20691 You can also add new rules, by modifying the @command{gnatcheck} code and
20692 rebuilding the tool. In order to add a simple rule making some local checks,
20693 a small amount of straightforward ASIS-based programming is usually needed.
20694
20695 Project support for @command{gnatcheck} is provided by the GNAT
20696 driver (see @ref{The GNAT Driver and Project Files}).
20697
20698 Invoking @command{gnatcheck} on the command line has the form:
20699
20700 @smallexample
20701 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20702       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20703       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20704 @end smallexample
20705
20706 @noindent
20707 where
20708 @itemize @bullet
20709 @item
20710 @var{switches} specify the general tool options
20711
20712 @item
20713 Each @var{filename} is the name (including the extension) of a source
20714 file to process. ``Wildcards'' are allowed, and
20715 the file name may contain path information.
20716
20717 @item
20718 Each @var{arg_list_filename} is the name (including the extension) of a text
20719 file containing the names of the source files to process, separated by spaces
20720 or line breaks.
20721
20722 @item
20723 @var{gcc_switches} is a list of switches for
20724 @command{gcc}. They will be passed on to all compiler invocations made by
20725 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20726 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20727 and use the @option{-gnatec} switch to set the configuration file.
20728
20729 @item
20730 @var{rule_options} is a list of options for controlling a set of
20731 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20732 @end itemize
20733
20734 @noindent
20735 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20736 supplied.
20737
20738 @menu
20739 * Format of the Report File::
20740 * General gnatcheck Switches::
20741 * gnatcheck Rule Options::
20742 * Adding the Results of Compiler Checks to gnatcheck Output::
20743 * Project-Wide Checks::
20744 * Rule exemption::
20745 * Predefined Rules::
20746 * Example of gnatcheck Usage::
20747 @end menu
20748
20749 @node Format of the Report File
20750 @section Format of the Report File
20751 @cindex Report file (for @code{gnatcheck})
20752
20753 @noindent
20754 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20755 rule violations.
20756 It also creates a text file  that
20757 contains the complete report of the last gnatcheck run. By default this file
20758 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20759 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20760 name and/or location of the report file. This report contains:
20761 @itemize @bullet
20762 @item date and time of @command{gnatcheck} run, the version of
20763 the tool that has generated this report and the full parameters
20764 of the  @command{gnatcheck} invocation;
20765 @item list of enabled rules;
20766 @item total number of detected violations;
20767 @item list of source files where rule violations have been detected;
20768 @item list of source files where no violations have been detected.
20769 @end itemize
20770
20771 @node General gnatcheck Switches
20772 @section General @command{gnatcheck} Switches
20773
20774 @noindent
20775 The following switches control the general @command{gnatcheck} behavior
20776
20777 @table @option
20778 @c !sort!
20779 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20780 @item ^-a^/ALL^
20781 Process all units including those with read-only ALI files such as
20782 those from the GNAT Run-Time library.
20783
20784 @ifclear vms
20785 @ignore
20786 @cindex @option{-d} (@command{gnatcheck})
20787 @item -d
20788 Debug mode
20789 @end ignore
20790
20791 @cindex @option{-dd} (@command{gnatcheck})
20792 @item -dd
20793 Progress indicator mode (for use in GPS).
20794 @end ifclear
20795
20796 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20797 @item ^-h^/HELP^
20798 List the predefined and user-defined rules. For more details see
20799 @ref{Predefined Rules}.
20800
20801 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20802 @item ^-l^/LOCS^
20803 Use full source locations references in the report file. For a construct from
20804 a generic instantiation a full source location is a chain from the location
20805 of this construct in the generic unit to the place where this unit is
20806 instantiated.
20807
20808 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20809 @item ^-log^/LOG^
20810 Duplicate all the output sent to @file{stderr} into a log file. The log file
20811 is named @file{gnatcheck.log} and is located in the current directory.
20812
20813 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20814 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20815 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20816 the range 0@dots{}1000;
20817 the default value is 500. Zero means that there is no limitation on
20818 the number of diagnostic messages to be output.
20819
20820 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20821 @item ^-q^/QUIET^
20822 Quiet mode. All the diagnostics about rule violations are placed in the
20823 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20824
20825 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20826 @item ^-s^/SHORT^
20827 Short format of the report file (no version information, no list of applied
20828 rules, no list of checked sources is included)
20829
20830 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
20831 @item ^--include-file^/INCLUDE_FILE^
20832 Append the content of the specified text file to the report file
20833
20834 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20835 @item ^-t^/TIME^
20836 Print out execution time.
20837
20838 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20839 @item ^-v^/VERBOSE^
20840 Verbose mode; @command{gnatcheck} generates version information and then
20841 a trace of sources being processed.
20842
20843 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20844 @item ^-o ^/OUTPUT=^@var{report_file}
20845 Set name of report file file to @var{report_file} .
20846
20847 @end table
20848
20849 @noindent
20850 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20851 @option{^-s2^/BY_RULES^} or
20852 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20853 then the  @command{gnatcheck} report file will only contain sections
20854 explicitly denoted by these options.
20855
20856 @node gnatcheck Rule Options
20857 @section @command{gnatcheck} Rule Options
20858
20859 @noindent
20860 The following options control the processing performed by
20861 @command{gnatcheck}.
20862
20863 @table @option
20864 @cindex @option{+ALL} (@command{gnatcheck})
20865 @item +ALL
20866 Turn all the rule checks ON.
20867
20868 @cindex @option{-ALL} (@command{gnatcheck})
20869 @item -ALL
20870 Turn all the rule checks OFF.
20871
20872 @cindex @option{+R} (@command{gnatcheck})
20873 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20874 Turn on the check for a specified rule with the specified parameter, if any.
20875 @var{rule_id} must be the identifier of one of the currently implemented rules
20876 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20877 are not case-sensitive. The @var{param} item must
20878 be a string representing a valid parameter(s) for the specified rule.
20879 If it contains any space characters then this string must be enclosed in
20880 quotation marks.
20881
20882 @cindex @option{-R} (@command{gnatcheck})
20883 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20884 Turn off the check for a specified rule with the specified parameter, if any.
20885
20886 @cindex @option{-from} (@command{gnatcheck})
20887 @item -from=@var{rule_option_filename}
20888 Read the rule options from the text file @var{rule_option_filename}, referred
20889 to as a ``coding standard file'' below.
20890
20891 @end table
20892
20893 @noindent
20894 The default behavior is that all the rule checks are disabled.
20895
20896 A coding standard file is a text file that contains a set of rule options
20897 described above.
20898 @cindex Coding standard file (for @code{gnatcheck})
20899 The file may contain empty lines and Ada-style comments (comment
20900 lines and end-of-line comments). There can be several rule options on a
20901 single line (separated by a space).
20902
20903 A coding standard file may reference other coding standard files by including
20904 more @option{-from=@var{rule_option_filename}}
20905 options, each such option being replaced with the content of the
20906 corresponding coding standard file during processing. In case a
20907 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20908 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20909 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20910 processing fails with an error message.
20911
20912
20913 @node Adding the Results of Compiler Checks to gnatcheck Output
20914 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20915
20916 @noindent
20917 The @command{gnatcheck} tool can include in the generated diagnostic messages
20918 and in
20919 the report file the results of the checks performed by the compiler. Though
20920 disabled by default, this effect may be obtained by using @option{+R} with
20921 the following rule identifiers and parameters:
20922
20923 @table @option
20924 @item Restrictions
20925 To record restrictions violations (which are performed by the compiler if the
20926 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20927 use the @code{Restrictions} rule
20928 with the same parameters as pragma
20929 @code{Restrictions} or @code{Restriction_Warnings}.
20930
20931 @item Style_Checks
20932 To record compiler style checks (@pxref{Style Checking}), use the
20933 @code{Style_Checks} rule.
20934 This rule takes a parameter in one of the following forms:
20935 @itemize
20936 @item
20937 @code{All_Checks},
20938 which enables the standard style checks corresponding to the @option{-gnatyy}
20939 GNAT style check option, or
20940
20941 @item
20942 a string with the same
20943 structure and semantics as the @code{string_LITERAL} parameter of the
20944 GNAT pragma @code{Style_Checks}
20945 (for further information about this pragma,
20946 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20947 @end itemize
20948
20949 @noindent
20950 For example, the
20951 @code{+RStyle_Checks:O} rule option activates
20952 the compiler style check that corresponds to
20953 @code{-gnatyO} style check option.
20954
20955 @item Warnings
20956 To record compiler warnings (@pxref{Warning Message Control}), use the
20957 @code{Warnings} rule with a parameter that is a valid
20958 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20959 (for further information about this pragma,
20960 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20961 Note that in case of gnatcheck
20962 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20963 all the specific warnings, but not suppresses the warning mode,
20964 and 'e' parameter, corresponding to @option{-gnatwe} that means
20965 "treat warnings as errors", does not have any effect.
20966
20967 @end table
20968
20969 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20970 option with the corresponding restriction name as a parameter. @code{-R} is
20971 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20972 warnings and style checks, use the corresponding warning and style options.
20973
20974 @node Project-Wide Checks
20975 @section Project-Wide Checks
20976 @cindex Project-wide checks (for @command{gnatcheck})
20977
20978 @noindent
20979 In order to perform checks on all units of a given project, you can use
20980 the GNAT driver along with the @option{-P} option:
20981 @smallexample
20982    gnat check -Pproj -rules -from=my_rules
20983 @end smallexample
20984
20985 @noindent
20986 If the project @code{proj} depends upon other projects, you can perform
20987 checks on the project closure using the @option{-U} option:
20988 @smallexample
20989    gnat check -Pproj -U -rules -from=my_rules
20990 @end smallexample
20991
20992 @noindent
20993 Finally, if not all the units are relevant to a particular main
20994 program in the project closure, you can perform checks for the set
20995 of units needed to create a given main program (unit closure) using
20996 the @option{-U} option followed by the name of the main unit:
20997 @smallexample
20998    gnat check -Pproj -U main -rules -from=my_rules
20999 @end smallexample
21000
21001
21002 @node Rule exemption
21003 @section Rule exemption
21004 @cindex Rule exemption (for @command{gnatcheck})
21005
21006 @noindent
21007 One of the most useful applications of @command{gnatcheck} is to
21008 automate the enforcement of project-specific coding standards,
21009 for example in safety-critical systems where particular features
21010 must be restricted in order to simplify the certification effort.
21011 However, it may sometimes be appropriate to violate a coding standard rule,
21012 and in such cases the rationale for the violation should be provided
21013 in the source program itself so that the individuals
21014 reviewing or maintaining the program can immediately understand the intent.
21015
21016 The @command{gnatcheck} tool supports this practice with the notion of
21017 a ``rule exemption'' covering a specific source code section. Normally
21018 rule violation messages are issued both on @file{stderr}
21019 and in a report file. In contrast, exempted violations are not listed on
21020 @file{stderr}; thus users invoking @command{gnatcheck} interactively
21021 (e.g. in its GPS interface) do not need to pay attention to known and
21022 justified violations. However, exempted violations along with their
21023 justification are documented in a special section of the report file that
21024 @command{gnatcheck} generates.
21025
21026 @menu
21027 * Using pragma Annotate to Control Rule Exemption::
21028 * gnatcheck Annotations Rules::
21029 @end menu
21030
21031 @node Using pragma Annotate to Control Rule Exemption
21032 @subsection Using pragma @code{Annotate} to Control Rule Exemption
21033 @cindex Using pragma Annotate to control rule exemption
21034
21035 @noindent
21036 Rule exemption is controlled by pragma @code{Annotate} when its first
21037 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21038 exemption control annotations is as follows:
21039
21040 @smallexample @c ada
21041 @group
21042 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21043
21044 @i{exemption_control} ::= Exempt_On | Exempt_Off
21045
21046 @i{Rule_Name}         ::= string_literal
21047
21048 @i{justification}     ::= string_literal
21049 @end group
21050 @end smallexample
21051
21052 @noindent
21053 When a @command{gnatcheck} annotation has more then four arguments,
21054 @command{gnatcheck} issues a warning and ignores the additional arguments.
21055 If the additional arguments do not follow the syntax above,
21056 @command{gnatcheck} emits a warning and ignores the annotation.
21057
21058 The @i{@code{Rule_Name}} argument should be the name of some existing
21059 @command{gnatcheck} rule.
21060 Otherwise a warning message is generated and the pragma is
21061 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21062 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21063
21064 A source code section where an exemption is active for a given rule is
21065 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21066
21067 @smallexample @c ada
21068 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
21069 -- source code section
21070 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
21071 @end smallexample
21072
21073
21074 @node gnatcheck Annotations Rules
21075 @subsection @command{gnatcheck} Annotations Rules
21076 @cindex @command{gnatcheck} annotations rules
21077
21078 @itemize @bullet
21079
21080 @item
21081 An ``Exempt_Off'' annotation can only appear after a corresponding
21082 ``Exempt_On'' annotation.
21083
21084 @item
21085 Exempted source code sections are only based on the source location of the
21086 annotations. Any source construct between the two
21087 annotations is part of the exempted source code section.
21088
21089 @item
21090 Exempted source code sections for different rules are independent. They can
21091 be nested or intersect with one another without limitation.
21092 Creating nested or intersecting source code sections for the same rule is
21093 not allowed.
21094
21095 @item
21096 Malformed exempted source code sections are reported by a warning, and
21097 the corresponding rule exemptions are ignored.
21098
21099 @item
21100 When an exempted source code section does not contain at least one violation
21101 of the exempted rule, a warning is emitted on @file{stderr}.
21102
21103 @item
21104 If an ``Exempt_On'' annotation pragma does not have a matching
21105 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21106 exemption for the given rule is ignored and a warning is issued.
21107 @end itemize
21108
21109
21110 @node Predefined Rules
21111 @section Predefined Rules
21112 @cindex Predefined rules (for @command{gnatcheck})
21113
21114 @ignore
21115 @c (Jan 2007) Since the global rules are still under development and are not
21116 @c documented, there is no point in explaining the difference between
21117 @c global and local rules
21118 @noindent
21119 A rule in @command{gnatcheck} is either local or global.
21120 A @emph{local rule} is a rule that applies to a well-defined section
21121 of a program and that can be checked by analyzing only this section.
21122 A @emph{global rule} requires analysis of some global properties of the
21123 whole program (mostly related to the program call graph).
21124 As of @value{NOW}, the implementation of global rules should be
21125 considered to be at a preliminary stage. You can use the
21126 @option{+GLOBAL} option to enable all the global rules, and the
21127 @option{-GLOBAL} rule option to disable all the global rules.
21128
21129 All the global rules in the list below are
21130 so indicated by marking them ``GLOBAL''.
21131 This +GLOBAL and -GLOBAL options are not
21132 included in the list of gnatcheck options above, because at the moment they
21133 are considered as a temporary debug options.
21134
21135 @command{gnatcheck} performs rule checks for generic
21136 instances only for global rules.  This limitation may be relaxed in a later
21137 release.
21138 @end ignore
21139
21140 @noindent
21141 The following subsections document the rules implemented in
21142 @command{gnatcheck}.
21143 The subsection title is the same as the rule identifier, which may be
21144 used as a parameter of the @option{+R} or @option{-R} options.
21145
21146
21147 @menu
21148 * Abstract_Type_Declarations::
21149 * Anonymous_Arrays::
21150 * Anonymous_Subtypes::
21151 * Blocks::
21152 * Boolean_Relational_Operators::
21153 @ignore
21154 * Ceiling_Violations::
21155 @end ignore
21156 * Complex_Inlined_Subprograms::
21157 * Controlled_Type_Declarations::
21158 * Declarations_In_Blocks::
21159 * Deep_Inheritance_Hierarchies::
21160 * Deeply_Nested_Generics::
21161 * Deeply_Nested_Inlining::
21162 @ignore
21163 * Deeply_Nested_Local_Inlining::
21164 @end ignore
21165 * Default_Parameters::
21166 * Direct_Calls_To_Primitives::
21167 * Discriminated_Records::
21168 * Enumeration_Ranges_In_CASE_Statements::
21169 * Exceptions_As_Control_Flow::
21170 * Exits_From_Conditional_Loops::
21171 * EXIT_Statements_With_No_Loop_Name::
21172 * Expanded_Loop_Exit_Names::
21173 * Explicit_Full_Discrete_Ranges::
21174 * Float_Equality_Checks::
21175 * Forbidden_Attributes::
21176 * Forbidden_Pragmas::
21177 * Function_Style_Procedures::
21178 * Generics_In_Subprograms::
21179 * GOTO_Statements::
21180 * Implicit_IN_Mode_Parameters::
21181 * Implicit_SMALL_For_Fixed_Point_Types::
21182 * Improperly_Located_Instantiations::
21183 * Improper_Returns::
21184 * Library_Level_Subprograms::
21185 * Local_Packages::
21186 @ignore
21187 * Improperly_Called_Protected_Entries::
21188 @end ignore
21189 * Metrics::
21190 * Misnamed_Controlling_Parameters::
21191 * Misnamed_Identifiers::
21192 * Multiple_Entries_In_Protected_Definitions::
21193 * Name_Clashes::
21194 * Non_Qualified_Aggregates::
21195 * Non_Short_Circuit_Operators::
21196 * Non_SPARK_Attributes::
21197 * Non_Tagged_Derived_Types::
21198 * Non_Visible_Exceptions::
21199 * Numeric_Literals::
21200 * OTHERS_In_Aggregates::
21201 * OTHERS_In_CASE_Statements::
21202 * OTHERS_In_Exception_Handlers::
21203 * Outer_Loop_Exits::
21204 * Overloaded_Operators::
21205 * Overly_Nested_Control_Structures::
21206 * Parameters_Out_Of_Order::
21207 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21208 * Positional_Actuals_For_Defaulted_Parameters::
21209 * Positional_Components::
21210 * Positional_Generic_Parameters::
21211 * Positional_Parameters::
21212 * Predefined_Numeric_Types::
21213 * Raising_External_Exceptions::
21214 * Raising_Predefined_Exceptions::
21215 * Separate_Numeric_Error_Handlers::
21216 @ignore
21217 * Recursion::
21218 * Side_Effect_Functions::
21219 @end ignore
21220 * Slices::
21221 * Too_Many_Parents::
21222 * Unassigned_OUT_Parameters::
21223 * Uncommented_BEGIN_In_Package_Bodies::
21224 * Unconditional_Exits::
21225 * Unconstrained_Array_Returns::
21226 * Universal_Ranges::
21227 * Unnamed_Blocks_And_Loops::
21228 @ignore
21229 * Unused_Subprograms::
21230 @end ignore
21231 * USE_PACKAGE_Clauses::
21232 * Visible_Components::
21233 * Volatile_Objects_Without_Address_Clauses::
21234 @end menu
21235
21236
21237 @node Abstract_Type_Declarations
21238 @subsection @code{Abstract_Type_Declarations}
21239 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21240
21241 @noindent
21242 Flag all declarations of abstract types. For an abstract private
21243 type, both the private and full type declarations are flagged.
21244
21245 This rule has no parameters.
21246
21247
21248 @node Anonymous_Arrays
21249 @subsection @code{Anonymous_Arrays}
21250 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21251
21252 @noindent
21253 Flag all anonymous array type definitions (by Ada semantics these can only
21254 occur in object declarations).
21255
21256 This rule has no parameters.
21257
21258 @node Anonymous_Subtypes
21259 @subsection @code{Anonymous_Subtypes}
21260 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21261
21262 @noindent
21263 Flag all uses of anonymous subtypes (except cases when subtype indication
21264 is a part of a record component definition, and this subtype indication
21265 depends on a discriminant). A use of an anonymous subtype is
21266 any instance of a subtype indication with a constraint, other than one
21267 that occurs immediately within a subtype declaration. Any use of a range
21268 other than as a constraint used immediately within a subtype declaration
21269 is considered as an anonymous subtype.
21270
21271 An effect of this rule is that @code{for} loops such as the following are
21272 flagged (since @code{1..N} is formally a ``range''):
21273
21274 @smallexample @c ada
21275 for I in 1 .. N loop
21276    @dots{}
21277 end loop;
21278 @end smallexample
21279
21280 @noindent
21281 Declaring an explicit subtype solves the problem:
21282
21283 @smallexample @c ada
21284 subtype S is Integer range 1..N;
21285 @dots{}
21286 for I in S loop
21287    @dots{}
21288 end loop;
21289 @end smallexample
21290
21291 @noindent
21292 This rule has no parameters.
21293
21294 @node Blocks
21295 @subsection @code{Blocks}
21296 @cindex @code{Blocks} rule (for @command{gnatcheck})
21297
21298 @noindent
21299 Flag each block statement.
21300
21301 This rule has no parameters.
21302
21303 @node Boolean_Relational_Operators
21304 @subsection @code{Boolean_Relational_Operators}
21305 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21306
21307 @noindent
21308 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21309 ``>='', ``='' and ``/='') for the predefined Boolean type.
21310 (This rule is useful in enforcing the SPARK language restrictions.)
21311
21312 Calls to predefined relational operators of any type derived from
21313 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21314 with these designators, and uses of operators that are renamings
21315 of the predefined relational operators for @code{Standard.Boolean},
21316 are likewise not detected.
21317
21318 This rule has no parameters.
21319
21320 @ignore
21321 @node Ceiling_Violations
21322 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21323 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21324
21325 @noindent
21326 Flag invocations of a protected operation by a task whose priority exceeds
21327 the protected object's ceiling.
21328
21329 As of @value{NOW}, this rule has the following limitations:
21330
21331 @itemize @bullet
21332
21333 @item
21334  We consider only pragmas Priority and Interrupt_Priority as means to define
21335   a task/protected operation priority. We do not consider the effect of using
21336   Ada.Dynamic_Priorities.Set_Priority procedure;
21337
21338 @item
21339  We consider only base task priorities, and no priority inheritance. That is,
21340   we do not make a difference between calls issued during task activation and
21341   execution of the sequence of statements from task body;
21342
21343 @item
21344  Any situation when the priority of protected operation caller is set by a
21345   dynamic expression (that is, the corresponding Priority or
21346   Interrupt_Priority pragma has a non-static expression as an argument) we
21347   treat as a priority inconsistency (and, therefore, detect this situation).
21348 @end itemize
21349
21350 @noindent
21351 At the moment the notion of the main subprogram is not implemented in
21352 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21353 if this subprogram can be a main subprogram of a partition) changes the
21354 priority of an environment task. So if we have more then one such pragma in
21355 the set of processed sources, the pragma that is processed last, defines the
21356 priority of an environment task.
21357
21358 This rule has no parameters.
21359 @end ignore
21360
21361 @node Controlled_Type_Declarations
21362 @subsection @code{Controlled_Type_Declarations}
21363 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21364
21365 @noindent
21366 Flag all declarations of controlled types. A declaration of a private type
21367 is flagged if its full declaration declares a controlled type. A declaration
21368 of a derived type is flagged if its ancestor type is controlled. Subtype
21369 declarations are not checked. A declaration of a type that itself is not a
21370 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21371 component is not checked.
21372
21373 This rule has no parameters.
21374
21375
21376 @node Complex_Inlined_Subprograms
21377 @subsection @code{Complex_Inlined_Subprograms}
21378 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21379
21380 @noindent
21381 Flags a subprogram (or generic subprogram) if
21382 pragma Inline is applied to the subprogram and at least one of the following
21383 conditions is met:
21384
21385 @itemize @bullet
21386 @item
21387 it contains at least one complex declaration such as a subprogram body,
21388 package, task, protected declaration, or a generic instantiation
21389 (except instantiation of @code{Ada.Unchecked_Conversion});
21390
21391 @item
21392 it contains at least one complex statement such as a loop, a case
21393 or a if statement, or a short circuit control form;
21394
21395 @item
21396 the number of statements exceeds
21397 a value specified by the @option{N} rule parameter;
21398 @end itemize
21399
21400 @noindent
21401 This rule has the following (mandatory) parameter for the @option{+R} option:
21402
21403 @table @emph
21404 @item N
21405 Positive integer specifying the maximum allowed total number of statements
21406 in the subprogram body.
21407 @end table
21408
21409
21410 @node Declarations_In_Blocks
21411 @subsection @code{Declarations_In_Blocks}
21412 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21413
21414 @noindent
21415 Flag all block statements containing local declarations. A @code{declare}
21416 block with an empty @i{declarative_part} or with a @i{declarative part}
21417 containing only pragmas and/or @code{use} clauses is not flagged.
21418
21419 This rule has no parameters.
21420
21421
21422 @node Deep_Inheritance_Hierarchies
21423 @subsection @code{Deep_Inheritance_Hierarchies}
21424 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21425
21426 @noindent
21427 Flags a tagged derived type declaration or an interface type declaration if
21428 its depth (in its inheritance
21429 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21430
21431 The inheritance depth of a tagged type or interface type is defined as 0 for
21432 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21433 depths of the immediate parent and immediate progenitors.
21434
21435 This rule does not flag private extension
21436 declarations. In the case of a private extension, the corresponding full
21437 declaration is checked.
21438
21439 This rule has the following (mandatory) parameter for the @option{+R} option:
21440
21441 @table @emph
21442 @item N
21443 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21444 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21445 of tagged and interface types.
21446 @end table
21447
21448
21449 @node Deeply_Nested_Generics
21450 @subsection @code{Deeply_Nested_Generics}
21451 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21452
21453 @noindent
21454 Flags a generic declaration nested in another generic declaration if
21455 the nesting level of the inner generic exceeds
21456 a value specified by the @option{N} rule parameter.
21457 The nesting level is the number of generic declaratons that enclose the given
21458 (generic) declaration. Formal packages are not flagged by this rule.
21459
21460 This rule has the following (mandatory) parameters for the @option{+R} option:
21461
21462 @table @emph
21463 @item N
21464 Positive integer specifying the maximal allowed nesting level
21465 for a generic declaration.
21466 @end table
21467
21468 @node Deeply_Nested_Inlining
21469 @subsection @code{Deeply_Nested_Inlining}
21470 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21471
21472 @noindent
21473 Flags a subprogram (or generic subprogram) if
21474 pragma Inline has been applied to the subprogram but the subprogram
21475 calls to another inlined subprogram that results in nested inlining
21476 with nesting depth exceeding the value specified by the
21477 @option{N} rule parameter.
21478
21479 This rule requires the global analysis of all the compilation units that
21480 are @command{gnatcheck} arguments; such analysis may affect the tool's
21481 performance.
21482
21483 This rule has the following (mandatory) parameter for the @option{+R} option:
21484
21485 @table @emph
21486 @item N
21487 Positive integer specifying the maximal allowed level of nested inlining.
21488 @end table
21489
21490
21491 @ignore
21492 @node Deeply_Nested_Local_Inlining
21493 @subsection @code{Deeply_Nested_Local_Inlining}
21494 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21495
21496 @noindent
21497 Flags a subprogram body if a pragma @code{Inline} is applied to the
21498 corresponding subprogram (or generic subprogram) and the body contains a call
21499 to another inlined subprogram that results in nested inlining with nesting
21500 depth more then a value specified by the @option{N} rule parameter.
21501 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21502 assumes that calls to subprograms in
21503 with'ed units are not inlided, so all the analysis of the depth of inlining is
21504 limited by the compilation unit where the subprogram body is located and the
21505 units it depends semantically upon. Such analysis may be usefull for the case
21506 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21507 the executable.
21508
21509 This rule has the following (mandatory) parameters for the @option{+R} option:
21510
21511 @table @emph
21512 @item N
21513 Positive integer specifying the maximal allowed level of nested inlining.
21514 @end table
21515
21516 @end ignore
21517
21518 @node Default_Parameters
21519 @subsection @code{Default_Parameters}
21520 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21521
21522 @noindent
21523 Flag all default expressions for subprogram parameters. Parameter
21524 declarations of formal and generic subprograms are also checked.
21525
21526 This rule has no parameters.
21527
21528
21529 @node Direct_Calls_To_Primitives
21530 @subsection @code{Direct_Calls_To_Primitives}
21531 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21532
21533 @noindent
21534 Flags any non-dispatching call to a dispatching primitive operation, except
21535 for the common idiom where a primitive subprogram for a tagged type
21536 directly calls the same primitive subprogram of the type's immediate ancestor.
21537
21538 This rule has no parameters.
21539
21540
21541 @node Discriminated_Records
21542 @subsection @code{Discriminated_Records}
21543 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21544
21545 @noindent
21546 Flag all declarations of record types with discriminants. Only the
21547 declarations of record and record extension types are checked. Incomplete,
21548 formal, private, derived and private extension type declarations are not
21549 checked. Task and protected type declarations also are not checked.
21550
21551 This rule has no parameters.
21552
21553
21554 @node Enumeration_Ranges_In_CASE_Statements
21555 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21556 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21557
21558 @noindent
21559 Flag each use of a range of enumeration literals as a choice in a
21560 @code{case} statement.
21561 All forms for specifying a range (explicit ranges
21562 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21563 An enumeration range is
21564 flagged even if contains exactly one enumeration value or no values at all. A
21565 type derived from an enumeration type is considered as an enumeration type.
21566
21567 This rule helps prevent maintenance problems arising from adding an
21568 enumeration value to a type and having it implicitly handled by an existing
21569 @code{case} statement with an enumeration range that includes the new literal.
21570
21571 This rule has no parameters.
21572
21573
21574 @node Exceptions_As_Control_Flow
21575 @subsection @code{Exceptions_As_Control_Flow}
21576 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21577
21578 @noindent
21579 Flag each place where an exception is explicitly raised and handled in the
21580 same subprogram body. A @code{raise} statement in an exception handler,
21581 package body, task body or entry body is not flagged.
21582
21583 The rule has no parameters.
21584
21585 @node Exits_From_Conditional_Loops
21586 @subsection @code{Exits_From_Conditional_Loops}
21587 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21588
21589 @noindent
21590 Flag any exit statement if it transfers the control out of a @code{for} loop
21591 or a @code{while} loop. This includes cases when the @code{exit} statement
21592 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21593 in some @code{for} or @code{while} loop, but transfers the control from some
21594 outer (inconditional) @code{loop} statement.
21595
21596 The rule has no parameters.
21597
21598
21599 @node EXIT_Statements_With_No_Loop_Name
21600 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21601 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21602
21603 @noindent
21604 Flag each @code{exit} statement that does not specify the name of the loop
21605 being exited.
21606
21607 The rule has no parameters.
21608
21609
21610 @node Expanded_Loop_Exit_Names
21611 @subsection @code{Expanded_Loop_Exit_Names}
21612 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21613
21614 @noindent
21615 Flag all expanded loop names in @code{exit} statements.
21616
21617 This rule has no parameters.
21618
21619 @node Explicit_Full_Discrete_Ranges
21620 @subsection @code{Explicit_Full_Discrete_Ranges}
21621 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21622
21623 @noindent
21624 Flag each discrete range that has the form @code{A'First .. A'Last}.
21625
21626 This rule has no parameters.
21627
21628 @node Float_Equality_Checks
21629 @subsection @code{Float_Equality_Checks}
21630 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21631
21632 @noindent
21633 Flag all calls to the predefined equality operations for floating-point types.
21634 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21635 User-defined equality operations are not flagged, nor are ``@code{=}''
21636 and ``@code{/=}'' operations for fixed-point types.
21637
21638 This rule has no parameters.
21639
21640
21641 @node Forbidden_Attributes
21642 @subsection @code{Forbidden_Attributes}
21643 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21644
21645 @noindent
21646 Flag each use of the specified attributes. The attributes to be detected are
21647 named in the rule's parameters.
21648
21649 This rule has the following parameters:
21650
21651 @itemize @bullet
21652 @item For the @option{+R} option
21653
21654 @table @asis
21655 @item @emph{Attribute_Designator}
21656 Adds the specified attribute to the set of attributes to be detected and sets
21657 the detection checks for all the specified attributes ON.
21658 If @emph{Attribute_Designator}
21659 does not denote any attribute defined in the Ada standard
21660 or in
21661 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21662 Manual}, it is treated as the name of unknown attribute.
21663
21664 @item @code{GNAT}
21665 All the GNAT-specific attributes are detected; this sets
21666 the detection checks for all the specified attributes ON.
21667
21668 @item @code{ALL}
21669 All attributes are detected; this sets the rule ON.
21670 @end table
21671
21672 @item For the @option{-R} option
21673 @table @asis
21674 @item @emph{Attribute_Designator}
21675 Removes the specified attribute from the set of attributes to be
21676 detected without affecting detection checks for
21677 other attributes. If @emph{Attribute_Designator} does not correspond to any
21678 attribute defined in the Ada standard or in
21679 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21680 this option is treated as turning OFF detection of all unknown attributes.
21681
21682 @item GNAT
21683 Turn OFF detection of all GNAT-specific attributes
21684
21685 @item ALL
21686 Clear the list of the attributes to be detected and
21687 turn the rule OFF.
21688 @end table
21689 @end itemize
21690
21691 @noindent
21692 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21693 have the syntax of an Ada identifier and therefore can not be considered as a
21694 (part of an) attribute designator, a diagnostic message is generated and the
21695 corresponding parameter is ignored. (If an attribute allows a static
21696 expression to be a part of the attribute designator, this expression is
21697 ignored by this rule.)
21698
21699 When more then one parameter is given in the same rule option, the parameters
21700 must be separated by commas.
21701
21702 If more then one option for this rule is specified for the gnatcheck call, a
21703 new option overrides the previous one(s).
21704
21705 The @option{+R} option with no parameters turns the rule ON, with the set of
21706 attributes to be detected defined by the previous rule options.
21707 (By default this set is empty, so if the only option specified for the rule is
21708 @option{+RForbidden_Attributes} (with
21709 no parameter), then the rule is enabled, but it does not detect anything).
21710 The @option{-R} option with no parameter turns the rule OFF, but it does not
21711 affect the set of attributes to be detected.
21712
21713
21714 @node Forbidden_Pragmas
21715 @subsection @code{Forbidden_Pragmas}
21716 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21717
21718 @noindent
21719 Flag each use of the specified pragmas.  The pragmas to be detected
21720 are named in the rule's  parameters.
21721
21722 This rule has the following parameters:
21723
21724 @itemize @bullet
21725 @item For the @option{+R} option
21726
21727 @table @asis
21728 @item @emph{Pragma_Name}
21729 Adds the specified pragma to the set of pragmas to be
21730 checked and sets the checks for all the specified pragmas
21731 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21732 does not correspond to any pragma name defined in the Ada
21733 standard or to the name of a GNAT-specific pragma defined
21734 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21735 Manual}, it is treated as the name of unknown pragma.
21736
21737 @item @code{GNAT}
21738 All the GNAT-specific pragmas are detected; this sets
21739 the checks for all the specified pragmas ON.
21740
21741 @item @code{ALL}
21742 All pragmas are detected; this sets the rule ON.
21743 @end table
21744
21745 @item For the @option{-R} option
21746 @table @asis
21747 @item @emph{Pragma_Name}
21748 Removes the specified pragma from the set of pragmas to be
21749 checked without affecting checks for
21750 other pragmas. @emph{Pragma_Name} is treated as a name
21751 of a pragma. If it does not correspond to any pragma
21752 defined in the Ada standard or to any name defined in
21753 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21754 this option is treated as turning OFF detection of all unknown pragmas.
21755
21756 @item GNAT
21757 Turn OFF detection of all GNAT-specific pragmas
21758
21759 @item ALL
21760 Clear the list of the pragmas to be detected and
21761 turn the rule OFF.
21762 @end table
21763 @end itemize
21764
21765 @noindent
21766 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21767 the syntax of an Ada identifier and therefore can not be considered
21768 as a pragma name, a diagnostic message is generated and the corresponding
21769 parameter is ignored.
21770
21771 When more then one parameter is given in the same rule option, the parameters
21772 must be separated by a comma.
21773
21774 If more then one option for this rule is specified for the @command{gnatcheck}
21775 call, a new option overrides the previous one(s).
21776
21777 The @option{+R} option with no parameters turns the rule ON with the set of
21778 pragmas to be detected defined by the previous rule options.
21779 (By default this set is empty, so if the only option specified for the rule is
21780 @option{+RForbidden_Pragmas} (with
21781 no parameter), then the rule is enabled, but it does not detect anything).
21782 The @option{-R} option with no parameter turns the rule OFF, but it does not
21783 affect the set of pragmas to be detected.
21784
21785
21786
21787
21788 @node Function_Style_Procedures
21789 @subsection @code{Function_Style_Procedures}
21790 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21791
21792 @noindent
21793 Flag each procedure that can be rewritten as a function. A procedure can be
21794 converted into a function if it has exactly one parameter of mode @code{out}
21795 and no parameters of mode @code{in out}. Procedure declarations,
21796 formal procedure declarations, and generic procedure declarations are always
21797 checked. Procedure
21798 bodies and body stubs are flagged only if they do not have corresponding
21799 separate declarations. Procedure renamings and procedure instantiations are
21800 not flagged.
21801
21802 If a procedure can be rewritten as a function, but its @code{out} parameter is
21803 of a limited type, it is not flagged.
21804
21805 Protected procedures are not flagged. Null procedures also are not flagged.
21806
21807 This rule has no parameters.
21808
21809
21810 @node Generics_In_Subprograms
21811 @subsection @code{Generics_In_Subprograms}
21812 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21813
21814 @noindent
21815 Flag each declaration of a generic unit in a subprogram. Generic
21816 declarations in the bodies of generic subprograms are also flagged.
21817 A generic unit nested in another generic unit is not flagged.
21818 If a generic unit is
21819 declared in a local package that is declared in a subprogram body, the
21820 generic unit is flagged.
21821
21822 This rule has no parameters.
21823
21824
21825 @node GOTO_Statements
21826 @subsection @code{GOTO_Statements}
21827 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21828
21829 @noindent
21830 Flag each occurrence of a @code{goto} statement.
21831
21832 This rule has no parameters.
21833
21834
21835 @node Implicit_IN_Mode_Parameters
21836 @subsection @code{Implicit_IN_Mode_Parameters}
21837 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21838
21839 @noindent
21840 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21841 Note that @code{access} parameters, although they technically behave
21842 like @code{in} parameters, are not flagged.
21843
21844 This rule has no parameters.
21845
21846
21847 @node Implicit_SMALL_For_Fixed_Point_Types
21848 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21849 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21850
21851 @noindent
21852 Flag each fixed point type declaration that lacks an explicit
21853 representation  clause to define its @code{'Small} value.
21854 Since @code{'Small} can be  defined only for ordinary fixed point types,
21855 decimal fixed point type declarations are not checked.
21856
21857 This rule has no parameters.
21858
21859
21860 @node Improperly_Located_Instantiations
21861 @subsection @code{Improperly_Located_Instantiations}
21862 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21863
21864 @noindent
21865 Flag all generic instantiations in library-level package specs
21866 (including library generic packages) and in all subprogram bodies.
21867
21868 Instantiations in task and entry bodies are not flagged. Instantiations in the
21869 bodies of protected subprograms are flagged.
21870
21871 This rule has no parameters.
21872
21873
21874
21875 @node Improper_Returns
21876 @subsection @code{Improper_Returns}
21877 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21878
21879 @noindent
21880 Flag each explicit @code{return} statement in procedures, and
21881 multiple @code{return} statements in functions.
21882 Diagnostic messages are generated for all @code{return} statements
21883 in a procedure (thus each procedure must be written so that it
21884 returns implicitly at the end of its statement part),
21885 and for all @code{return} statements in a function after the first one.
21886 This rule supports the stylistic convention that each subprogram
21887 should have no more than one point of normal return.
21888
21889 This rule has no parameters.
21890
21891
21892 @node Library_Level_Subprograms
21893 @subsection @code{Library_Level_Subprograms}
21894 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21895
21896 @noindent
21897 Flag all library-level subprograms (including generic subprogram instantiations).
21898
21899 This rule has no parameters.
21900
21901
21902 @node Local_Packages
21903 @subsection @code{Local_Packages}
21904 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21905
21906 @noindent
21907 Flag all local packages declared in package and generic package
21908 specs.
21909 Local packages in bodies are not flagged.
21910
21911 This rule has no parameters.
21912
21913 @ignore
21914 @node Improperly_Called_Protected_Entries
21915 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21916 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21917
21918 @noindent
21919 Flag each protected entry that can be called from more than one task.
21920
21921 This rule has no parameters.
21922 @end ignore
21923
21924 @node Metrics
21925 @subsection @code{Metrics}
21926 @cindex @code{Metrics} rule (for @command{gnatcheck})
21927
21928 @noindent
21929 There is a set of checks based on computing a metric value and comparing the
21930 result with the specified upper (or lower, depending on a specific metric)
21931 value specified for a given metric. A construct is flagged if a given metric
21932 is applicable (can be computed) for it and the computed value is greater
21933 then (lover then) the specified upper (lower) bound.
21934
21935 The name of any metric-based rule consists of the prefix @code{Metrics_}
21936 followed by the name of the corresponding metric (see the table below).
21937 For @option{+R} option, each metric-based rule has a numeric parameter
21938 specifying the bound (integer or real, depending on a metric), @option{-R}
21939 option for metric rules does not have a parameter.
21940
21941 The following table shows the metric names for that the corresponding
21942 metrics-based checks are supported by gnatcheck, including the
21943 constraint that must be satisfied by the bound that is specified for the check
21944 and what bound - upper (U) or lower (L) - should be specified.
21945
21946 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21947 @ifnothtml
21948 @headitem Check Name @tab Description @tab Bounds Value
21949 @end ifnothtml
21950 @ifhtml
21951 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21952 @end ifhtml
21953 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21954 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21955 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21956 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21957 @end multitable
21958
21959 @noindent
21960 The meaning and the computed values for all these metrics are exactly
21961 the same as for the corresponding metrics in @command{gnatmetric}.
21962
21963 @emph{Example:} the rule
21964 @smallexample
21965 +RMetrics_Cyclomatic_Complexity : 7
21966 @end smallexample
21967 @noindent
21968 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21969
21970 To turn OFF the check for cyclomatic complexity metric, use the following option:
21971 @smallexample
21972 -RMetrics_Cyclomatic_Complexity
21973 @end smallexample
21974
21975
21976 @node Misnamed_Controlling_Parameters
21977 @subsection @code{Misnamed_Controlling_Parameters}
21978 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21979
21980 @noindent
21981 Flags a declaration of a dispatching operation, if the first parameter is
21982 not a controlling one and its name is not @code{This} (the check for
21983 parameter name is not case-sensitive). Declarations of dispatching functions
21984 with controlling result and no controlling parameter are never flagged.
21985
21986 A subprogram body declaration, subprogram renaming declaration or subprogram
21987 body stub is flagged only if it is not a completion of a prior subprogram
21988 declaration.
21989
21990 This rule has no parameters.
21991
21992
21993
21994 @node Misnamed_Identifiers
21995 @subsection @code{Misnamed_Identifiers}
21996 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21997
21998 @noindent
21999 Flag the declaration of each identifier that does not have a suffix
22000 corresponding to the kind of entity being declared.
22001 The following declarations are checked:
22002
22003 @itemize @bullet
22004 @item
22005 type declarations
22006
22007 @item
22008 subtype declarations
22009
22010 @item
22011 constant declarations (but not number declarations)
22012
22013 @item
22014 package renaming declarations (but not generic package renaming
22015 declarations)
22016 @end itemize
22017
22018 @noindent
22019 This rule may have parameters. When used without parameters, the rule enforces
22020 the following checks:
22021
22022 @itemize @bullet
22023 @item
22024 type-defining names end with @code{_T}, unless the type is an access type,
22025 in which case the suffix must be @code{_A}
22026 @item
22027 constant names end with @code{_C}
22028 @item
22029 names defining package renamings end with @code{_R}
22030 @end itemize
22031
22032 @noindent
22033 Defining identifiers from incomplete type declarations are never flagged.
22034
22035 For a private type declaration (including private extensions), the defining
22036 identifier from the private type declaration is checked against the type
22037 suffix (even if the corresponding full declaration is an access type
22038 declaration), and the defining identifier from the corresponding full type
22039 declaration is not checked.
22040
22041 @noindent
22042 For a deferred constant, the defining name in the corresponding full constant
22043 declaration is not checked.
22044
22045 Defining names of formal types are not checked.
22046
22047 The rule may have the following parameters:
22048
22049 @itemize @bullet
22050 @item
22051 For the @option{+R} option:
22052 @table @code
22053 @item Default
22054 Sets the default listed above for all the names to be checked.
22055
22056 @item Type_Suffix=@emph{string}
22057 Specifies the suffix for a type name.
22058
22059 @item Access_Suffix=@emph{string}
22060 Specifies the suffix for an access type name. If
22061 this parameter is set, it overrides for access
22062 types the suffix set by the @code{Type_Suffix} parameter.
22063 For access types, @emph{string} may have the following format:
22064 @emph{suffix1(suffix2)}. That means that an access type name
22065 should have the @emph{suffix1} suffix except for the case when
22066 the designated type is also an access type, in this case the
22067 type name should have the @emph{suffix1 & suffix2} suffix.
22068
22069 @item Class_Access_Suffix=@emph{string}
22070 Specifies the suffix for the name of an access type that points to some class-wide
22071 type. If this parameter is set, it overrides for such access
22072 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22073 parameter.
22074
22075 @item Class_Subtype_Suffix=@emph{string}
22076 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22077
22078 @item Constant_Suffix=@emph{string}
22079 Specifies the suffix for a constant name.
22080
22081 @item Renaming_Suffix=@emph{string}
22082 Specifies the suffix for a package renaming name.
22083 @end table
22084
22085 @item
22086 For the @option{-R} option:
22087 @table @code
22088 @item All_Suffixes
22089 Remove all the suffixes specified for the
22090 identifier suffix checks, whether by default or
22091 as specified by other rule parameters. All the
22092 checks for this rule are disabled as a result.
22093
22094 @item Type_Suffix
22095 Removes the suffix specified for types. This
22096 disables checks for types but does not disable
22097 any other checks for this rule (including the
22098 check for access type names if @code{Access_Suffix} is
22099 set).
22100
22101 @item Access_Suffix
22102 Removes the suffix specified for access types.
22103 This disables checks for access type names but
22104 does not disable any other checks for this rule.
22105 If @code{Type_Suffix} is set, access type names are
22106 checked as ordinary type names.
22107
22108 @item Class_Access_Suffix
22109 Removes the suffix specified for access types pointing to class-wide
22110 type. This disables specific checks for names of access types pointing to
22111 class-wide types but does not disable any other checks for this rule.
22112 If @code{Type_Suffix} is set, access type names are
22113 checked as ordinary type names. If @code{Access_Suffix} is set, these
22114 access types are checked as any other access type name.
22115
22116 @item Class_Subtype_Suffix=@emph{string}
22117 Removes the suffix specified for subtype names.
22118 This disables checks for subtype names but
22119 does not disable any other checks for this rule.
22120
22121 @item Constant_Suffix
22122 Removes the suffix specified for constants. This
22123 disables checks for constant names but does not
22124 disable any other checks for this rule.
22125
22126 @item Renaming_Suffix
22127 Removes the suffix specified for package
22128 renamings. This disables checks for package
22129 renamings but does not disable any other checks
22130 for this rule.
22131 @end table
22132 @end itemize
22133
22134 @noindent
22135 If more than one parameter is used, parameters must be separated by commas.
22136
22137 If more than one  option is specified for the @command{gnatcheck} invocation,
22138 a new option overrides the previous one(s).
22139
22140 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22141 checks for all the
22142 name suffixes specified by previous options used for this rule.
22143
22144 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22145 all the checks but keeps
22146 all the suffixes specified by previous options used for this rule.
22147
22148 The @emph{string} value must be a valid suffix for an Ada identifier (after
22149 trimming all the leading and trailing space characters, if any).
22150 Parameters are not case sensitive, except the @emph{string} part.
22151
22152 If any error is detected in a rule parameter, the parameter is ignored.
22153 In such a case the options that are set for the rule are not
22154 specified.
22155
22156
22157
22158 @node Multiple_Entries_In_Protected_Definitions
22159 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22160 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22161
22162 @noindent
22163 Flag each protected definition (i.e., each protected object/type declaration)
22164 that defines more than one entry.
22165 Diagnostic messages are generated for all the entry declarations
22166 except the first one. An entry family is counted as one entry. Entries from
22167 the private part of the protected definition are also checked.
22168
22169 This rule has no parameters.
22170
22171 @node Name_Clashes
22172 @subsection @code{Name_Clashes}
22173 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22174
22175 @noindent
22176 Check that certain names are not used as defining identifiers. To activate
22177 this rule, you need to supply a reference to the dictionary file(s) as a rule
22178 parameter(s) (more then one dictionary file can be specified). If no
22179 dictionary file is set, this rule will not cause anything to be flagged.
22180 Only defining occurrences, not references, are checked.
22181 The check is not case-sensitive.
22182
22183 This rule is enabled by default, but without setting any corresponding
22184 dictionary file(s); thus the default effect is to do no checks.
22185
22186 A dictionary file is a plain text file. The maximum line length for this file
22187 is 1024 characters.  If the line is longer then this limit, extra characters
22188 are ignored.
22189
22190 Each line can be either an empty line, a comment line, or a line containing
22191 a list of identifiers separated by space or HT characters.
22192 A comment is an Ada-style comment (from @code{--} to end-of-line).
22193 Identifiers must follow the Ada syntax for identifiers.
22194 A line containing one or more identifiers may end with a comment.
22195
22196 @node Non_Qualified_Aggregates
22197 @subsection @code{Non_Qualified_Aggregates}
22198 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22199
22200 @noindent
22201 Flag each non-qualified aggregate.
22202 A non-qualified aggregate is an
22203 aggregate that is not the expression of a qualified expression. A
22204 string literal is not considered an aggregate, but an array
22205 aggregate of a string type is considered as a normal aggregate.
22206 Aggregates of anonymous array types are not flagged.
22207
22208 This rule has no parameters.
22209
22210
22211 @node Non_Short_Circuit_Operators
22212 @subsection @code{Non_Short_Circuit_Operators}
22213 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22214
22215 @noindent
22216 Flag all calls to predefined @code{and} and @code{or} operators for
22217 any boolean type. Calls to
22218 user-defined @code{and} and @code{or} and to operators defined by renaming
22219 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22220 operators for modular types or boolean array types are not flagged.
22221
22222 This rule has no parameters.
22223
22224
22225
22226 @node Non_SPARK_Attributes
22227 @subsection @code{Non_SPARK_Attributes}
22228 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22229
22230 @noindent
22231 The SPARK language defines the following subset of Ada 95 attribute
22232 designators as those that can be used in SPARK programs. The use of
22233 any other attribute is flagged.
22234
22235 @itemize @bullet
22236 @item @code{'Adjacent}
22237 @item @code{'Aft}
22238 @item @code{'Base}
22239 @item @code{'Ceiling}
22240 @item @code{'Component_Size}
22241 @item @code{'Compose}
22242 @item @code{'Copy_Sign}
22243 @item @code{'Delta}
22244 @item @code{'Denorm}
22245 @item @code{'Digits}
22246 @item @code{'Exponent}
22247 @item @code{'First}
22248 @item @code{'Floor}
22249 @item @code{'Fore}
22250 @item @code{'Fraction}
22251 @item @code{'Last}
22252 @item @code{'Leading_Part}
22253 @item @code{'Length}
22254 @item @code{'Machine}
22255 @item @code{'Machine_Emax}
22256 @item @code{'Machine_Emin}
22257 @item @code{'Machine_Mantissa}
22258 @item @code{'Machine_Overflows}
22259 @item @code{'Machine_Radix}
22260 @item @code{'Machine_Rounds}
22261 @item @code{'Max}
22262 @item @code{'Min}
22263 @item @code{'Model}
22264 @item @code{'Model_Emin}
22265 @item @code{'Model_Epsilon}
22266 @item @code{'Model_Mantissa}
22267 @item @code{'Model_Small}
22268 @item @code{'Modulus}
22269 @item @code{'Pos}
22270 @item @code{'Pred}
22271 @item @code{'Range}
22272 @item @code{'Remainder}
22273 @item @code{'Rounding}
22274 @item @code{'Safe_First}
22275 @item @code{'Safe_Last}
22276 @item @code{'Scaling}
22277 @item @code{'Signed_Zeros}
22278 @item @code{'Size}
22279 @item @code{'Small}
22280 @item @code{'Succ}
22281 @item @code{'Truncation}
22282 @item @code{'Unbiased_Rounding}
22283 @item @code{'Val}
22284 @item @code{'Valid}
22285 @end itemize
22286
22287 @noindent
22288 This rule has no parameters.
22289
22290
22291 @node Non_Tagged_Derived_Types
22292 @subsection @code{Non_Tagged_Derived_Types}
22293 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22294
22295 @noindent
22296 Flag all derived type declarations that do not have a record extension part.
22297
22298 This rule has no parameters.
22299
22300
22301
22302 @node Non_Visible_Exceptions
22303 @subsection @code{Non_Visible_Exceptions}
22304 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22305
22306 @noindent
22307 Flag constructs leading to the possibility of propagating an exception
22308 out of the scope in which the exception is declared.
22309 Two cases are detected:
22310
22311 @itemize @bullet
22312 @item
22313 An exception declaration in a subprogram body, task body or block
22314 statement is flagged if the body or statement does not contain a handler for
22315 that exception or a handler with an @code{others} choice.
22316
22317 @item
22318 A @code{raise} statement in an exception handler of a subprogram body,
22319 task body or block statement is flagged if it (re)raises a locally
22320 declared exception.  This may occur under the following circumstances:
22321 @itemize @minus
22322 @item
22323 it explicitly raises a locally declared exception, or
22324 @item
22325 it does not specify an exception name (i.e., it is simply @code{raise;})
22326 and the enclosing handler contains a locally declared exception in its
22327 exception choices.
22328 @end itemize
22329 @end itemize
22330
22331 @noindent
22332 Renamings of local exceptions are not flagged.
22333
22334 This rule has no parameters.
22335
22336
22337 @node Numeric_Literals
22338 @subsection @code{Numeric_Literals}
22339 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22340
22341 @noindent
22342 Flag each use of a numeric literal in an index expression, and in any
22343 circumstance except for the following:
22344
22345 @itemize @bullet
22346 @item
22347 a literal occurring in the initialization expression for a constant
22348 declaration or a named number declaration, or
22349
22350 @item
22351 an integer literal that is less than or equal to a value
22352 specified by the @option{N} rule parameter.
22353 @end itemize
22354
22355 @noindent
22356 This rule may have the following parameters for the @option{+R} option:
22357
22358 @table @asis
22359 @item @emph{N}
22360 @emph{N} is an integer literal used as the maximal value that is not flagged
22361 (i.e., integer literals not exceeding this value are allowed)
22362
22363 @item @code{ALL}
22364 All integer literals are flagged
22365 @end table
22366
22367 @noindent
22368 If no parameters are set, the maximum unflagged value is 1.
22369
22370 The last specified check limit (or the fact that there is no limit at
22371 all) is used when multiple @option{+R} options appear.
22372
22373 The @option{-R} option for this rule has no parameters.
22374 It disables the rule but retains the last specified maximum unflagged value.
22375 If the @option{+R} option subsequently appears, this value is used as the
22376 threshold for the check.
22377
22378
22379 @node OTHERS_In_Aggregates
22380 @subsection @code{OTHERS_In_Aggregates}
22381 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22382
22383 @noindent
22384 Flag each use of an @code{others} choice in extension aggregates.
22385 In record and array aggregates, an @code{others} choice is flagged unless
22386 it is used to refer to all components, or to all but one component.
22387
22388 If, in case of a named array aggregate, there are two associations, one
22389 with an @code{others} choice and another with a discrete range, the
22390 @code{others} choice is flagged even if the discrete range specifies
22391 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22392
22393 This rule has no parameters.
22394
22395 @node OTHERS_In_CASE_Statements
22396 @subsection @code{OTHERS_In_CASE_Statements}
22397 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22398
22399 @noindent
22400 Flag any use of an @code{others} choice in a @code{case} statement.
22401
22402 This rule has no parameters.
22403
22404 @node OTHERS_In_Exception_Handlers
22405 @subsection @code{OTHERS_In_Exception_Handlers}
22406 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22407
22408 @noindent
22409 Flag any use of an @code{others} choice in an exception handler.
22410
22411 This rule has no parameters.
22412
22413
22414 @node Outer_Loop_Exits
22415 @subsection @code{Outer_Loop_Exits}
22416 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22417
22418 @noindent
22419 Flag each @code{exit} statement containing a loop name that is not the name
22420 of the immediately enclosing @code{loop} statement.
22421
22422 This rule has no parameters.
22423
22424
22425 @node Overloaded_Operators
22426 @subsection @code{Overloaded_Operators}
22427 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22428
22429 @noindent
22430 Flag each function declaration that overloads an operator symbol.
22431 A function body is checked only if the body does not have a
22432 separate spec. Formal functions are also checked. For a
22433 renaming declaration, only renaming-as-declaration is checked
22434
22435 This rule has no parameters.
22436
22437
22438 @node Overly_Nested_Control_Structures
22439 @subsection @code{Overly_Nested_Control_Structures}
22440 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22441
22442 @noindent
22443 Flag each control structure whose nesting level exceeds the value provided
22444 in the rule parameter.
22445
22446 The control structures checked are the following:
22447
22448 @itemize @bullet
22449 @item    @code{if} statement
22450 @item    @code{case} statement
22451 @item    @code{loop} statement
22452 @item    Selective accept statement
22453 @item    Timed entry call statement
22454 @item    Conditional entry call
22455 @item    Asynchronous select statement
22456 @end itemize
22457
22458 @noindent
22459 The rule has the following parameter for the @option{+R} option:
22460
22461 @table @emph
22462 @item N
22463 Positive integer specifying the maximal control structure nesting
22464 level that is not flagged
22465 @end table
22466
22467 @noindent
22468 If the parameter for the @option{+R} option is not specified or
22469 if it is not a positive integer, @option{+R} option is ignored.
22470
22471 If more then one  option is specified for the gnatcheck call, the later option and
22472 new parameter override the previous one(s).
22473
22474
22475 @node Parameters_Out_Of_Order
22476 @subsection @code{Parameters_Out_Of_Order}
22477 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22478
22479 @noindent
22480 Flag each subprogram and entry declaration whose formal parameters are not
22481 ordered according to the following scheme:
22482
22483 @itemize @bullet
22484
22485 @item @code{in} and @code{access} parameters first,
22486 then @code{in out} parameters,
22487 and then @code{out} parameters;
22488
22489 @item for @code{in} mode, parameters with default initialization expressions
22490 occur last
22491 @end itemize
22492
22493 @noindent
22494 Only the first violation of the described order is flagged.
22495
22496 The following constructs are checked:
22497
22498 @itemize @bullet
22499 @item   subprogram declarations (including null procedures);
22500 @item   generic subprogram declarations;
22501 @item   formal subprogram declarations;
22502 @item   entry declarations;
22503 @item   subprogram bodies and subprogram body stubs that do not
22504 have separate specifications
22505 @end itemize
22506
22507 @noindent
22508 Subprogram renamings are not checked.
22509
22510 This rule has no parameters.
22511
22512
22513 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22514 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22515 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22516
22517 @noindent
22518 Flag each generic actual parameter corresponding to a generic formal
22519 parameter with a default initialization, if positional notation is used.
22520
22521 This rule has no parameters.
22522
22523 @node Positional_Actuals_For_Defaulted_Parameters
22524 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22525 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22526
22527 @noindent
22528 Flag each actual parameter to a subprogram or entry call where the
22529 corresponding formal parameter has a default expression, if positional
22530 notation is used.
22531
22532 This rule has no parameters.
22533
22534 @node Positional_Components
22535 @subsection @code{Positional_Components}
22536 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22537
22538 @noindent
22539 Flag each array, record and extension aggregate that includes positional
22540 notation.
22541
22542 This rule has no parameters.
22543
22544
22545 @node Positional_Generic_Parameters
22546 @subsection @code{Positional_Generic_Parameters}
22547 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22548
22549 @noindent
22550 Flag each positional actual generic parameter except for the case when
22551 the generic unit being iinstantiated has exactly one generic formal
22552 parameter.
22553
22554 This rule has no parameters.
22555
22556
22557 @node Positional_Parameters
22558 @subsection @code{Positional_Parameters}
22559 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22560
22561 @noindent
22562 Flag each positional parameter notation in a subprogram or entry call,
22563 except for the following:
22564
22565 @itemize @bullet
22566 @item
22567 Parameters of calls to of prefix or infix operators are not flagged
22568 @item
22569 If the called subprogram or entry has only one formal parameter,
22570 the parameter of the call is not flagged;
22571 @item
22572 If a subprogram call uses the @emph{Object.Operation} notation, then
22573 @itemize @minus
22574 @item
22575 the first parameter (that is, @emph{Object}) is not flagged;
22576 @item
22577 if the called subprogram has only two parameters, the second parameter
22578 of the call is not flagged;
22579 @end itemize
22580 @end itemize
22581
22582 @noindent
22583 This rule has no parameters.
22584
22585
22586
22587
22588 @node Predefined_Numeric_Types
22589 @subsection @code{Predefined_Numeric_Types}
22590 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22591
22592 @noindent
22593 Flag each explicit use of the name of any numeric type or subtype defined
22594 in package @code{Standard}.
22595
22596 The rationale for this rule is to detect when the
22597 program may depend on platform-specific characteristics of the implementation
22598 of the predefined numeric types. Note that this rule is over-pessimistic;
22599 for example, a program that uses @code{String} indexing
22600 likely needs a variable of type @code{Integer}.
22601 Another example is the flagging of predefined numeric types with explicit
22602 constraints:
22603
22604 @smallexample @c ada
22605     subtype My_Integer is Integer range Left .. Right;
22606     Vy_Var : My_Integer;
22607 @end smallexample
22608
22609 @noindent
22610 This rule detects only numeric types and subtypes defined in
22611 @code{Standard}. The use of numeric types and subtypes defined in other
22612 predefined packages (such as @code{System.Any_Priority} or
22613 @code{Ada.Text_IO.Count}) is not flagged
22614
22615 This rule has no parameters.
22616
22617
22618
22619 @node Raising_External_Exceptions
22620 @subsection @code{Raising_External_Exceptions}
22621 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22622
22623 @noindent
22624 Flag any @code{raise} statement, in a program unit declared in a library
22625 package or in a generic library package, for an exception that is
22626 neither a predefined exception nor an exception that is also declared (or
22627 renamed) in the visible part of the package.
22628
22629 This rule has no parameters.
22630
22631
22632
22633 @node Raising_Predefined_Exceptions
22634 @subsection @code{Raising_Predefined_Exceptions}
22635 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22636
22637 @noindent
22638 Flag each @code{raise} statement that raises a predefined exception
22639 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22640 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22641
22642 This rule has no parameters.
22643
22644 @node Separate_Numeric_Error_Handlers
22645 @subsection @code{Separate_Numeric_Error_Handlers}
22646 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22647
22648 @noindent
22649 Flags each exception handler that contains a choice for
22650 the predefined @code{Constraint_Error} exception, but does not contain
22651 the choice for the predefined @code{Numeric_Error} exception, or
22652 that contains the choice for @code{Numeric_Error}, but does not contain the
22653 choice for @code{Constraint_Error}.
22654
22655 This rule has no parameters.
22656
22657 @ignore
22658 @node Recursion
22659 @subsection @code{Recursion} (under construction, GLOBAL)
22660 @cindex @code{Recursion} rule (for @command{gnatcheck})
22661
22662 @noindent
22663 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22664 calls, of recursive subprograms are detected.
22665
22666 This rule has no parameters.
22667 @end ignore
22668
22669 @ignore
22670 @node Side_Effect_Functions
22671 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22672 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22673
22674 @noindent
22675 Flag functions with side effects.
22676
22677 We define a side effect as changing any data object that is not local for the
22678 body of this function.
22679
22680 At the moment, we do NOT consider a side effect any input-output operations
22681 (changing a state or a content of any file).
22682
22683 We do not consider protected functions for this rule (???)
22684
22685 There are the following sources of side effect:
22686
22687 @enumerate
22688 @item Explicit (or direct) side-effect:
22689
22690 @itemize @bullet
22691 @item
22692 direct assignment to a non-local variable;
22693
22694 @item
22695 direct call to an entity that is known to change some data object that is
22696      not local for the body of this function (Note, that if F1 calls F2 and F2
22697      does have a side effect, this does not automatically mean that F1 also
22698      have a side effect, because it may be the case that F2 is declared in
22699      F1's body and it changes some data object that is global for F2, but
22700      local for F1);
22701 @end itemize
22702
22703 @item Indirect side-effect:
22704 @itemize @bullet
22705 @item
22706 Subprogram calls implicitly issued by:
22707 @itemize @bullet
22708 @item
22709 computing initialization expressions from type declarations as a part
22710          of object elaboration or allocator evaluation;
22711 @item
22712 computing implicit parameters of subprogram or entry calls or generic
22713          instantiations;
22714 @end itemize
22715
22716 @item
22717 activation of a task that change some non-local data object (directly or
22718      indirectly);
22719
22720 @item
22721 elaboration code of a package that is a result of a package instantiation;
22722
22723 @item
22724 controlled objects;
22725 @end itemize
22726
22727 @item Situations when we can suspect a side-effect, but the full static check
22728 is either impossible or too hard:
22729 @itemize @bullet
22730 @item
22731 assignment to access variables or to the objects pointed by access
22732      variables;
22733
22734 @item
22735 call to a subprogram pointed by access-to-subprogram value
22736
22737 @item
22738 dispatching calls;
22739 @end itemize
22740 @end enumerate
22741
22742 @noindent
22743 This rule has no parameters.
22744 @end ignore
22745
22746 @node Slices
22747 @subsection @code{Slices}
22748 @cindex @code{Slices} rule (for @command{gnatcheck})
22749
22750 @noindent
22751 Flag all uses of array slicing
22752
22753 This rule has no parameters.
22754
22755
22756 @node Too_Many_Parents
22757 @subsection @code{Too_Many_Parents}
22758 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22759
22760 @noindent
22761 Flags any type declaration, single task declaration or single protected
22762 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22763 of the rule.
22764 A parent here is either a (sub)type denoted by the subtype mark from the
22765 parent_subtype_indication (in case of a derived type declaration), or
22766 any of the progenitors from the interface list, if any.
22767
22768 This rule has the following (mandatory) parameters for the @option{+R} option:
22769
22770 @table @emph
22771 @item N
22772 Positive integer specifying the maximal allowed number of parents.
22773 @end table
22774
22775
22776 @node Unassigned_OUT_Parameters
22777 @subsection @code{Unassigned_OUT_Parameters}
22778 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22779
22780 @noindent
22781 Flags procedures' @code{out} parameters that are not assigned, and
22782 identifies the contexts in which the assignments are missing.
22783
22784 An @code{out} parameter is flagged in the statements in the procedure
22785 body's handled sequence of statements (before the procedure body's
22786 @code{exception} part, if any) if this sequence of statements contains
22787 no assignments to the parameter.
22788
22789 An @code{out} parameter is flagged in an exception handler in the exception
22790 part of the procedure body's handled sequence of statements if the handler
22791 contains no assignment to the parameter.
22792
22793 Bodies of generic procedures are also considered.
22794
22795 The following are treated as assignments to an @code{out} parameter:
22796
22797 @itemize @bullet
22798 @item
22799 an assignment statement, with the parameter or some component as the target;
22800
22801 @item
22802 passing the parameter (or one of its components) as an @code{out} or
22803 @code{in out} parameter.
22804 @end itemize
22805
22806 @noindent
22807 This rule does not have any parameters.
22808
22809
22810
22811 @node Uncommented_BEGIN_In_Package_Bodies
22812 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22813 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22814
22815 @noindent
22816 Flags each package body with declarations and a statement part that does not
22817 include a trailing comment on the line containing the @code{begin} keyword;
22818 this trailing comment needs to specify the package name and nothing else.
22819 The @code{begin} is not flagged if the package body does not
22820 contain any declarations.
22821
22822 If the @code{begin} keyword is placed on the
22823 same line as the last declaration or the first statement, it is flagged
22824 independently of whether the line contains a trailing comment. The
22825 diagnostic message is attached to the line containing the first statement.
22826
22827 This rule has no parameters.
22828
22829 @node Unconditional_Exits
22830 @subsection @code{Unconditional_Exits}
22831 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22832
22833 @noindent
22834 Flag unconditional @code{exit} statements.
22835
22836 This rule has no parameters.
22837
22838 @node Unconstrained_Array_Returns
22839 @subsection @code{Unconstrained_Array_Returns}
22840 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22841
22842 @noindent
22843 Flag each function returning an unconstrained array. Function declarations,
22844 function bodies (and body stubs) having no separate specifications,
22845 and generic function instantiations are checked.
22846 Function calls and function renamings are
22847 not checked.
22848
22849 Generic function declarations, and function declarations in generic
22850 packages are not checked, instead this rule checks the results of
22851 generic instantiations (that is, expanded specification and expanded
22852 body corresponding to an instantiation).
22853
22854 This rule has no parameters.
22855
22856 @node Universal_Ranges
22857 @subsection @code{Universal_Ranges}
22858 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22859
22860 @noindent
22861 Flag discrete ranges that are a part of an index constraint, constrained
22862 array definition, or @code{for}-loop parameter specification, and whose bounds
22863 are both of type @i{universal_integer}. Ranges that have at least one
22864 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22865 or an expression of non-universal type) are not flagged.
22866
22867 This rule has no parameters.
22868
22869
22870 @node Unnamed_Blocks_And_Loops
22871 @subsection @code{Unnamed_Blocks_And_Loops}
22872 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22873
22874 @noindent
22875 Flag each unnamed block statement and loop statement.
22876
22877 The rule has no parameters.
22878
22879
22880
22881 @ignore
22882 @node Unused_Subprograms
22883 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22884 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22885
22886 @noindent
22887 Flag all unused subprograms.
22888
22889 This rule has no parameters.
22890 @end ignore
22891
22892
22893
22894
22895 @node USE_PACKAGE_Clauses
22896 @subsection @code{USE_PACKAGE_Clauses}
22897 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22898
22899 @noindent
22900 Flag all @code{use} clauses for packages; @code{use type} clauses are
22901 not flagged.
22902
22903 This rule has no parameters.
22904
22905
22906 @node Visible_Components
22907 @subsection @code{Visible_Components}
22908 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22909
22910 @noindent
22911 Flags all the type declarations located in the visible part of a library
22912 package or a library generic package that can declare a visible component. A
22913 type is considered as declaring a visible component if it contains a record
22914 definition by its own or as a part of a record extension. Type declaration is
22915 flagged even if it contains a record definition that defines no components.
22916
22917 Declarations located in private parts of local (generic) packages are not
22918 flagged. Declarations in private packages are not flagged.
22919
22920 This rule has no parameters.
22921
22922
22923 @node Volatile_Objects_Without_Address_Clauses
22924 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22925 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22926
22927 @noindent
22928 Flag each volatile object that does not have an address clause.
22929
22930 The following check is made: if the pragma @code{Volatile} is applied to a
22931 data object or to its type, then an address clause must
22932 be supplied for this object.
22933
22934 This rule does not check the components of data objects,
22935 array components that are volatile as a result of the pragma
22936 @code{Volatile_Components}, or objects that are volatile because
22937 they are atomic as a result of pragmas @code{Atomic} or
22938 @code{Atomic_Components}.
22939
22940 Only variable declarations, and not constant declarations, are checked.
22941
22942 This rule has no parameters.
22943
22944 @node Example of gnatcheck Usage
22945 @section Example of @command{gnatcheck} Usage
22946
22947 @noindent
22948 Here is a simple example. Suppose that in the current directory we have a
22949 project file named @file{gnatcheck_example.gpr} with the following content:
22950
22951 @smallexample @c projectfile
22952 project Gnatcheck_Example is
22953
22954    for Source_Dirs use ("src");
22955    for Object_Dir use "obj";
22956    for Main use ("main.adb");
22957
22958    package Check is
22959       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
22960    end Check;
22961
22962 end Gnatcheck_Example;
22963 @end smallexample
22964
22965 @noindent
22966 And the file named @file{coding_standard} is also located in the current
22967 directory and has the following content:
22968
22969 @smallexample
22970 -----------------------------------------------------
22971 -- This is a sample gnatcheck coding standard file --
22972 -----------------------------------------------------
22973
22974 --  First, turning on rules, that are directly implemented in gnatcheck
22975 +RAbstract_Type_Declarations
22976 +RAnonymous_Arrays
22977 +RLocal_Packages
22978 +RFloat_Equality_Checks
22979 +REXIT_Statements_With_No_Loop_Name
22980
22981 --  Then, activating compiler checks of interest:
22982 +RStyle_Checks:e
22983 --  This style check checks if a unit name is present on END keyword that
22984 --  is the end of the unit declaration
22985 @end smallexample
22986
22987 @noindent
22988 And the subdirectory @file{src} contains the following Ada sources:
22989
22990 @file{pack.ads}:
22991
22992 @smallexample @c ada
22993 package Pack is
22994    type T is abstract tagged private;
22995    procedure P (X : T) is abstract;
22996
22997    package Inner is
22998       type My_Float is digits 8;
22999       function Is_Equal (L, R : My_Float) return Boolean;
23000    end Inner;
23001 private
23002    type T is abstract tagged null record;
23003 end;
23004 @end smallexample
23005
23006 @noindent
23007 @file{pack.adb}:
23008
23009 @smallexample @c ada
23010 package body Pack is
23011    package body Inner is
23012       function Is_Equal (L, R : My_Float) return Boolean is
23013       begin
23014          return L = R;
23015       end;
23016    end Inner;
23017 end Pack;
23018 @end smallexample
23019
23020 @noindent
23021 and @file{main.adb}
23022
23023 @smallexample @c ada
23024 with Pack; use Pack;
23025 procedure Main is
23026
23027    pragma Annotate
23028      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
23029    Float_Array : array (1 .. 10) of Inner.My_Float;
23030    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
23031
23032    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
23033
23034    use Inner;
23035
23036    B : Boolean := False;
23037
23038 begin
23039    for J in Float_Array'Range loop
23040       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
23041          B := True;
23042          exit;
23043       end if;
23044    end loop;
23045 end Main;
23046 @end smallexample
23047
23048 @noindent
23049 And suppose we call @command{gnatcheck} from the current directory using
23050 the @command{gnat} driver:
23051
23052 @smallexample
23053    gnat check -Pgnatcheck_example.gpr
23054 @end smallexample
23055
23056 @noindent
23057 As a result, @command{gnatcheck} is called to check all the files from the
23058 project @file{gnatcheck_example.gpr} using the coding standard defined by
23059 the file @file{coding_standard}. As the result, the @command{gnatcheck}
23060 report file named @file{gnatcheck.out} will be created in the current
23061 directory, and it will have the following content:
23062
23063 @smallexample
23064 RULE CHECKING REPORT
23065
23066 1. OVERVIEW
23067
23068 Date and time of execution: 2009.10.28 14:17
23069 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
23070 Command line:
23071
23072 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
23073
23074 Coding standard (applied rules):
23075    Abstract_Type_Declarations
23076    Anonymous_Arrays
23077    EXIT_Statements_With_No_Loop_Name
23078    Float_Equality_Checks
23079    Local_Packages
23080
23081    Compiler style checks: -gnatye
23082
23083 Number of coding standard violations: 6
23084 Number of exempted coding standard violations: 1
23085
23086 2. DETECTED RULE VIOLATIONS
23087
23088 2.1. NON-EXEMPTED VIOLATIONS
23089
23090 Source files with non-exempted violations
23091    pack.ads
23092    pack.adb
23093    main.adb
23094
23095 List of violations grouped by files, and ordered by increasing source location:
23096
23097 pack.ads:2:4: declaration of abstract type
23098 pack.ads:5:4: declaration of local package
23099 pack.ads:10:30: declaration of abstract type
23100 pack.ads:11:1: (style) "end Pack" required
23101 pack.adb:5:19: use of equality operation for float values
23102 pack.adb:6:7: (style) "end Is_Equal" required
23103 main.adb:9:26: anonymous array type
23104 main.adb:19:10: exit statement with no loop name
23105
23106 2.2. EXEMPTED VIOLATIONS
23107
23108 Source files with exempted violations
23109    main.adb
23110
23111 List of violations grouped by files, and ordered by increasing source location:
23112
23113 main.adb:6:18: anonymous array type
23114    (this one is fine)
23115
23116 2.3. SOURCE FILES WITH NO VIOLATION
23117
23118    No files without violations
23119
23120 END OF REPORT
23121 @end smallexample
23122
23123
23124 @c *********************************
23125 @node Creating Sample Bodies Using gnatstub
23126 @chapter Creating Sample Bodies Using @command{gnatstub}
23127 @findex gnatstub
23128
23129 @noindent
23130 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
23131 for library unit declarations.
23132
23133 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
23134 driver (see @ref{The GNAT Driver and Project Files}).
23135
23136 To create a body stub, @command{gnatstub} has to compile the library
23137 unit declaration. Therefore, bodies can be created only for legal
23138 library units. Moreover, if a library unit depends semantically upon
23139 units located outside the current directory, you have to provide
23140 the source search path when calling @command{gnatstub}, see the description
23141 of @command{gnatstub} switches below.
23142
23143 By default, all the program unit body stubs generated by @code{gnatstub}
23144 raise the predefined @code{Program_Error} exception, which will catch
23145 accidental calls of generated stubs. This behavior can be changed with
23146 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
23147
23148 @menu
23149 * Running gnatstub::
23150 * Switches for gnatstub::
23151 @end menu
23152
23153 @node Running gnatstub
23154 @section Running @command{gnatstub}
23155
23156 @noindent
23157 @command{gnatstub} has the command-line interface of the form
23158
23159 @smallexample
23160 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
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 switches
23189 is an optional sequence of switches as described in the next section
23190 @end table
23191
23192 @node Switches for gnatstub
23193 @section Switches for @command{gnatstub}
23194
23195 @table @option
23196 @c !sort!
23197
23198 @item ^-f^/FULL^
23199 @cindex @option{^-f^/FULL^} (@command{gnatstub})
23200 If the destination directory already contains a file with the name of the
23201 body file
23202 for the argument spec file, replace it with the generated body stub.
23203
23204 @item ^-hs^/HEADER=SPEC^
23205 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
23206 Put the comment header (i.e., all the comments preceding the
23207 compilation unit) from the source of the library unit declaration
23208 into the body stub.
23209
23210 @item ^-hg^/HEADER=GENERAL^
23211 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
23212 Put a sample comment header into the body stub.
23213
23214 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
23215 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
23216 Use the content of the file as the comment header for a generated body stub.
23217
23218 @ifclear vms
23219 @item -IDIR
23220 @cindex @option{-IDIR} (@command{gnatstub})
23221 @itemx -I-
23222 @cindex @option{-I-} (@command{gnatstub})
23223 @end ifclear
23224 @ifset vms
23225 @item /NOCURRENT_DIRECTORY
23226 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23227 @end ifset
23228 ^These switches have ^This switch has^ the same meaning as in calls to
23229 @command{gcc}.
23230 ^They define ^It defines ^ the source search path in the call to
23231 @command{gcc} issued
23232 by @command{gnatstub} to compile an argument source file.
23233
23234 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23235 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23236 This switch has the same meaning as in calls to @command{gcc}.
23237 It defines the additional configuration file to be passed to the call to
23238 @command{gcc} issued
23239 by @command{gnatstub} to compile an argument source file.
23240
23241 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23242 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23243 (@var{n} is a non-negative integer). Set the maximum line length in the
23244 body stub to @var{n}; the default is 79. The maximum value that can be
23245 specified is 32767. Note that in the special case of configuration
23246 pragma files, the maximum is always 32767 regardless of whether or
23247 not this switch appears.
23248
23249 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23250 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23251 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23252 the generated body sample to @var{n}.
23253 The default indentation is 3.
23254
23255 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23256 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23257 Order local bodies alphabetically. (By default local bodies are ordered
23258 in the same way as the corresponding local specs in the argument spec file.)
23259
23260 @item ^-i^/INDENTATION=^@var{n}
23261 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23262 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23263
23264 @item ^-k^/TREE_FILE=SAVE^
23265 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23266 Do not remove the tree file (i.e., the snapshot of the compiler internal
23267 structures used by @command{gnatstub}) after creating the body stub.
23268
23269 @item ^-l^/LINE_LENGTH=^@var{n}
23270 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23271 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23272
23273 @item ^--no-exception^/NO_EXCEPTION^
23274 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23275 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23276 This is not always possible for function stubs.
23277
23278 @item ^--no-local-header^/NO_LOCAL_HEADER^
23279 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23280 Do not place local comment header with unit name before body stub for a
23281 unit.
23282
23283 @item ^-o ^/BODY=^@var{body-name}
23284 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23285 Body file name.  This should be set if the argument file name does not
23286 follow
23287 the GNAT file naming
23288 conventions. If this switch is omitted the default name for the body will be
23289 obtained
23290 from the argument file name according to the GNAT file naming conventions.
23291
23292 @item ^-q^/QUIET^
23293 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23294 Quiet mode: do not generate a confirmation when a body is
23295 successfully created, and do not generate a message when a body is not
23296 required for an
23297 argument unit.
23298
23299 @item ^-r^/TREE_FILE=REUSE^
23300 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23301 Reuse the tree file (if it exists) instead of creating it.  Instead of
23302 creating the tree file for the library unit declaration, @command{gnatstub}
23303 tries to find it in the current directory and use it for creating
23304 a body. If the tree file is not found, no body is created. This option
23305 also implies @option{^-k^/SAVE^}, whether or not
23306 the latter is set explicitly.
23307
23308 @item ^-t^/TREE_FILE=OVERWRITE^
23309 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23310 Overwrite the existing tree file.  If the current directory already
23311 contains the file which, according to the GNAT file naming rules should
23312 be considered as a tree file for the argument source file,
23313 @command{gnatstub}
23314 will refuse to create the tree file needed to create a sample body
23315 unless this option is set.
23316
23317 @item ^-v^/VERBOSE^
23318 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23319 Verbose mode: generate version information.
23320
23321 @end table
23322
23323 @c *********************************
23324 @node Generating Ada Bindings for C and C++ headers
23325 @chapter Generating Ada Bindings for C and C++ headers
23326 @findex binding
23327
23328 @noindent
23329 GNAT now comes with a binding generator for C and C++ headers which is
23330 intended to do 95% of the tedious work of generating Ada specs from C
23331 or C++ header files.
23332
23333 Note that this capability is not intended to generate 100% correct Ada specs,
23334 and will is some cases require manual adjustments, although it can often
23335 be used out of the box in practice.
23336
23337 Some of the known limitations include:
23338
23339 @itemize @bullet
23340 @item only very simple character constant macros are translated into Ada
23341 constants. Function macros (macros with arguments) are partially translated
23342 as comments, to be completed manually if needed.
23343 @item some extensions (e.g. vector types) are not supported
23344 @item pointers to pointers or complex structures are mapped to System.Address
23345 @end itemize
23346
23347 The code generated is using the Ada 2005 syntax, which makes it
23348 easier to interface with other languages than previous versions of Ada.
23349
23350 @menu
23351 * Running the binding generator::
23352 * Generating bindings for C++ headers::
23353 * Switches::
23354 @end menu
23355
23356 @node Running the binding generator
23357 @section Running the binding generator
23358
23359 @noindent
23360 The binding generator is part of the @command{gcc} compiler and can be
23361 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23362 spec files for the header files specified on the command line, and all
23363 header files needed by these files transitivitely. For example:
23364
23365 @smallexample
23366 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23367 $ gcc -c -gnat05 *.ads
23368 @end smallexample
23369
23370 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23371 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23372 correspond to the files @file{/usr/include/time.h},
23373 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23374 mode these Ada specs.
23375
23376 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23377 and will attempt to generate corresponding Ada comments.
23378
23379 If you want to generate a single Ada file and not the transitive closure, you
23380 can use instead the @option{-fdump-ada-spec-slim} switch.
23381
23382 Note that we recommend when possible to use the @command{g++} driver to
23383 generate bindings, even for most C headers, since this will in general
23384 generate better Ada specs. For generating bindings for C++ headers, it is
23385 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23386 is equivalent in this case. If @command{g++} cannot work on your C headers
23387 because of incompatibilities between C and C++, then you can fallback to
23388 @command{gcc} instead.
23389
23390 For an example of better bindings generated from the C++ front-end,
23391 the name of the parameters (when available) are actually ignored by the C
23392 front-end. Consider the following C header:
23393
23394 @smallexample
23395 extern void foo (int variable);
23396 @end smallexample
23397
23398 with the C front-end, @code{variable} is ignored, and the above is handled as:
23399
23400 @smallexample
23401 extern void foo (int);
23402 @end smallexample
23403
23404 generating a generic:
23405
23406 @smallexample
23407 procedure foo (param1 : int);
23408 @end smallexample
23409
23410 with the C++ front-end, the name is available, and we generate:
23411
23412 @smallexample
23413 procedure foo (variable : int);
23414 @end smallexample
23415
23416 In some cases, the generated bindings will be more complete or more meaningful
23417 when defining some macros, which you can do via the @option{-D} switch. This
23418 is for example the case with @file{Xlib.h} under GNU/Linux:
23419
23420 @smallexample
23421 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23422 @end smallexample
23423
23424 The above will generate more complete bindings than a straight call without
23425 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23426
23427 In other cases, it is not possible to parse a header file in a stand alone
23428 manner, because other include files need to be included first. In this
23429 case, the solution is to create a small header file including the needed
23430 @code{#include} and possible @code{#define} directives. For example, to
23431 generate Ada bindings for @file{readline/readline.h}, you need to first
23432 include @file{stdio.h}, so you can create a file with the following two
23433 lines in e.g. @file{readline1.h}:
23434
23435 @smallexample
23436 #include <stdio.h>
23437 #include <readline/readline.h>
23438 @end smallexample
23439
23440 and then generate Ada bindings from this file:
23441
23442 @smallexample
23443 $ g++ -c -fdump-ada-spec readline1.h
23444 @end smallexample
23445
23446 @node Generating bindings for C++ headers
23447 @section Generating bindings for C++ headers
23448
23449 @noindent
23450 Generating bindings for C++ headers is done using the same options, always
23451 with the @command{g++} compiler.
23452
23453 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23454 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23455 multiple inheritance of abstract classes will be mapped to Ada interfaces
23456 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23457 information on interfacing to C++).
23458
23459 For example, given the following C++ header file:
23460
23461 @smallexample
23462 @group
23463 @cartouche
23464 class Carnivore @{
23465 public:
23466    virtual int Number_Of_Teeth () = 0;
23467 @};
23468
23469 class Domestic @{
23470 public:
23471    virtual void Set_Owner (char* Name) = 0;
23472 @};
23473
23474 class Animal @{
23475 public:
23476   int Age_Count;
23477   virtual void Set_Age (int New_Age);
23478 @};
23479
23480 class Dog : Animal, Carnivore, Domestic @{
23481  public:
23482   int  Tooth_Count;
23483   char *Owner;
23484
23485   virtual int  Number_Of_Teeth ();
23486   virtual void Set_Owner (char* Name);
23487
23488   Dog();
23489 @};
23490 @end cartouche
23491 @end group
23492 @end smallexample
23493
23494 The corresponding Ada code is generated:
23495
23496 @smallexample @c ada
23497 @group
23498 @cartouche
23499   package Class_Carnivore is
23500     type Carnivore is limited interface;
23501     pragma Import (CPP, Carnivore);
23502
23503     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23504   end;
23505   use Class_Carnivore;
23506
23507   package Class_Domestic is
23508     type Domestic is limited interface;
23509     pragma Import (CPP, Domestic);
23510
23511     procedure Set_Owner
23512       (this : access Domestic;
23513        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23514   end;
23515   use Class_Domestic;
23516
23517   package Class_Animal is
23518     type Animal is tagged limited record
23519       Age_Count : aliased int;
23520     end record;
23521     pragma Import (CPP, Animal);
23522
23523     procedure Set_Age (this : access Animal; New_Age : int);
23524     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23525   end;
23526   use Class_Animal;
23527
23528   package Class_Dog is
23529     type Dog is new Animal and Carnivore and Domestic with record
23530       Tooth_Count : aliased int;
23531       Owner : Interfaces.C.Strings.chars_ptr;
23532     end record;
23533     pragma Import (CPP, Dog);
23534
23535     function Number_Of_Teeth (this : access Dog) return int;
23536     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23537
23538     procedure Set_Owner
23539       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23540     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23541
23542     function New_Dog return Dog;
23543     pragma CPP_Constructor (New_Dog);
23544     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23545   end;
23546   use Class_Dog;
23547 @end cartouche
23548 @end group
23549 @end smallexample
23550
23551 @node Switches
23552 @section Switches
23553
23554 @table @option
23555 @item -fdump-ada-spec
23556 @cindex @option{-fdump-ada-spec} (@command{gcc})
23557 Generate Ada spec files for the given header files transitively (including
23558 all header files that these headers depend upon).
23559
23560 @item -fdump-ada-spec-slim
23561 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23562 Generate Ada spec files for the header files specified on the command line
23563 only.
23564
23565 @item -C
23566 @cindex @option{-C} (@command{gcc})
23567 Extract comments from headers and generate Ada comments in the Ada spec files.
23568 @end table
23569
23570 @node Other Utility Programs
23571 @chapter Other Utility Programs
23572
23573 @noindent
23574 This chapter discusses some other utility programs available in the Ada
23575 environment.
23576
23577 @menu
23578 * Using Other Utility Programs with GNAT::
23579 * The External Symbol Naming Scheme of GNAT::
23580 * Converting Ada Files to html with gnathtml::
23581 * Installing gnathtml::
23582 @ifset vms
23583 * LSE::
23584 * Profiling::
23585 @end ifset
23586 @end menu
23587
23588 @node Using Other Utility Programs with GNAT
23589 @section Using Other Utility Programs with GNAT
23590
23591 @noindent
23592 The object files generated by GNAT are in standard system format and in
23593 particular the debugging information uses this format. This means
23594 programs generated by GNAT can be used with existing utilities that
23595 depend on these formats.
23596
23597 @ifclear vms
23598 In general, any utility program that works with C will also often work with
23599 Ada programs generated by GNAT. This includes software utilities such as
23600 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23601 as Purify.
23602 @end ifclear
23603
23604 @node The External Symbol Naming Scheme of GNAT
23605 @section The External Symbol Naming Scheme of GNAT
23606
23607 @noindent
23608 In order to interpret the output from GNAT, when using tools that are
23609 originally intended for use with other languages, it is useful to
23610 understand the conventions used to generate link names from the Ada
23611 entity names.
23612
23613 All link names are in all lowercase letters. With the exception of library
23614 procedure names, the mechanism used is simply to use the full expanded
23615 Ada name with dots replaced by double underscores. For example, suppose
23616 we have the following package spec:
23617
23618 @smallexample @c ada
23619 @group
23620 @cartouche
23621 package QRS is
23622    MN : Integer;
23623 end QRS;
23624 @end cartouche
23625 @end group
23626 @end smallexample
23627
23628 @noindent
23629 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23630 the corresponding link name is @code{qrs__mn}.
23631 @findex Export
23632 Of course if a @code{pragma Export} is used this may be overridden:
23633
23634 @smallexample @c ada
23635 @group
23636 @cartouche
23637 package Exports is
23638    Var1 : Integer;
23639    pragma Export (Var1, C, External_Name => "var1_name");
23640    Var2 : Integer;
23641    pragma Export (Var2, C, Link_Name => "var2_link_name");
23642 end Exports;
23643 @end cartouche
23644 @end group
23645 @end smallexample
23646
23647 @noindent
23648 In this case, the link name for @var{Var1} is whatever link name the
23649 C compiler would assign for the C function @var{var1_name}. This typically
23650 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23651 system conventions, but other possibilities exist. The link name for
23652 @var{Var2} is @var{var2_link_name}, and this is not operating system
23653 dependent.
23654
23655 @findex _main
23656 One exception occurs for library level procedures. A potential ambiguity
23657 arises between the required name @code{_main} for the C main program,
23658 and the name we would otherwise assign to an Ada library level procedure
23659 called @code{Main} (which might well not be the main program).
23660
23661 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23662 names. So if we have a library level procedure such as
23663
23664 @smallexample @c ada
23665 @group
23666 @cartouche
23667 procedure Hello (S : String);
23668 @end cartouche
23669 @end group
23670 @end smallexample
23671
23672 @noindent
23673 the external name of this procedure will be @var{_ada_hello}.
23674
23675
23676 @node Converting Ada Files to html with gnathtml
23677 @section Converting Ada Files to HTML with @code{gnathtml}
23678
23679 @noindent
23680 This @code{Perl} script allows Ada source files to be browsed using
23681 standard Web browsers. For installation procedure, see the section
23682 @xref{Installing gnathtml}.
23683
23684 Ada reserved keywords are highlighted in a bold font and Ada comments in
23685 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23686 switch to suppress the generation of cross-referencing information, user
23687 defined variables and types will appear in a different color; you will
23688 be able to click on any identifier and go to its declaration.
23689
23690 The command line is as follow:
23691 @smallexample
23692 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23693 @end smallexample
23694
23695 @noindent
23696 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23697 an html file for every ada file, and a global file called @file{index.htm}.
23698 This file is an index of every identifier defined in the files.
23699
23700 The available ^switches^options^ are the following ones:
23701
23702 @table @option
23703 @item -83
23704 @cindex @option{-83} (@code{gnathtml})
23705 Only the Ada 83 subset of keywords will be highlighted.
23706
23707 @item -cc @var{color}
23708 @cindex @option{-cc} (@code{gnathtml})
23709 This option allows you to change the color used for comments. The default
23710 value is green. The color argument can be any name accepted by html.
23711
23712 @item -d
23713 @cindex @option{-d} (@code{gnathtml})
23714 If the Ada files depend on some other files (for instance through
23715 @code{with} clauses, the latter files will also be converted to html.
23716 Only the files in the user project will be converted to html, not the files
23717 in the run-time library itself.
23718
23719 @item -D
23720 @cindex @option{-D} (@code{gnathtml})
23721 This command is the same as @option{-d} above, but @command{gnathtml} will
23722 also look for files in the run-time library, and generate html files for them.
23723
23724 @item -ext @var{extension}
23725 @cindex @option{-ext} (@code{gnathtml})
23726 This option allows you to change the extension of the generated HTML files.
23727 If you do not specify an extension, it will default to @file{htm}.
23728
23729 @item -f
23730 @cindex @option{-f} (@code{gnathtml})
23731 By default, gnathtml will generate html links only for global entities
23732 ('with'ed units, global variables and types,@dots{}).  If you specify
23733 @option{-f} on the command line, then links will be generated for local
23734 entities too.
23735
23736 @item -l @var{number}
23737 @cindex @option{-l} (@code{gnathtml})
23738 If this ^switch^option^ is provided and @var{number} is not 0, then
23739 @code{gnathtml} will number the html files every @var{number} line.
23740
23741 @item -I @var{dir}
23742 @cindex @option{-I} (@code{gnathtml})
23743 Specify a directory to search for library files (@file{.ALI} files) and
23744 source files. You can provide several -I switches on the command line,
23745 and the directories will be parsed in the order of the command line.
23746
23747 @item -o @var{dir}
23748 @cindex @option{-o} (@code{gnathtml})
23749 Specify the output directory for html files. By default, gnathtml will
23750 saved the generated html files in a subdirectory named @file{html/}.
23751
23752 @item -p @var{file}
23753 @cindex @option{-p} (@code{gnathtml})
23754 If you are using Emacs and the most recent Emacs Ada mode, which provides
23755 a full Integrated Development Environment for compiling, checking,
23756 running and debugging applications, you may use @file{.gpr} files
23757 to give the directories where Emacs can find sources and object files.
23758
23759 Using this ^switch^option^, you can tell gnathtml to use these files.
23760 This allows you to get an html version of your application, even if it
23761 is spread over multiple directories.
23762
23763 @item -sc @var{color}
23764 @cindex @option{-sc} (@code{gnathtml})
23765 This ^switch^option^ allows you to change the color used for symbol
23766 definitions.
23767 The default value is red. The color argument can be any name accepted by html.
23768
23769 @item -t @var{file}
23770 @cindex @option{-t} (@code{gnathtml})
23771 This ^switch^option^ provides the name of a file. This file contains a list of
23772 file names to be converted, and the effect is exactly as though they had
23773 appeared explicitly on the command line. This
23774 is the recommended way to work around the command line length limit on some
23775 systems.
23776
23777 @end table
23778
23779 @node Installing gnathtml
23780 @section Installing @code{gnathtml}
23781
23782 @noindent
23783 @code{Perl} needs to be installed on your machine to run this script.
23784 @code{Perl} is freely available for almost every architecture and
23785 Operating System via the Internet.
23786
23787 On Unix systems, you  may want to modify  the  first line of  the script
23788 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23789 is. The syntax of this line is:
23790 @smallexample
23791 #!full_path_name_to_perl
23792 @end smallexample
23793
23794 @noindent
23795 Alternatively, you may run the script using the following command line:
23796
23797 @smallexample
23798 $ perl gnathtml.pl @ovar{switches} @var{files}
23799 @end smallexample
23800
23801 @ifset vms
23802 @node LSE
23803 @section LSE
23804 @findex LSE
23805
23806 @noindent
23807 The GNAT distribution provides an Ada 95 template for the HP Language
23808 Sensitive Editor (LSE), a component of DECset. In order to
23809 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23810
23811 @node Profiling
23812 @section Profiling
23813 @findex PCA
23814
23815 @noindent
23816 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23817 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23818 the collection phase with the /DEBUG qualifier.
23819
23820 @smallexample
23821 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23822 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23823 $ RUN/DEBUG <PROGRAM_NAME>
23824 @end smallexample
23825 @noindent
23826 @end ifset
23827
23828 @ifclear vms
23829 @c ******************************
23830 @node Code Coverage and Profiling
23831 @chapter Code Coverage and Profiling
23832 @cindex Code Coverage
23833 @cindex Profiling
23834
23835 @noindent
23836 This chapter describes how to use @code{gcov} - coverage testing tool - and
23837 @code{gprof} - profiler tool - on your Ada programs.
23838
23839 @menu
23840 * Code Coverage of Ada Programs using gcov::
23841 * Profiling an Ada Program using gprof::
23842 @end menu
23843
23844 @node Code Coverage of Ada Programs using gcov
23845 @section Code Coverage of Ada Programs using gcov
23846 @cindex gcov
23847 @cindex -fprofile-arcs
23848 @cindex -ftest-coverage
23849 @cindex -coverage
23850 @cindex Code Coverage
23851
23852 @noindent
23853 @code{gcov} is a test coverage program: it analyzes the execution of a given
23854 program on selected tests, to help you determine the portions of the program
23855 that are still untested.
23856
23857 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23858 User's Guide. You can refer to this documentation for a more complete
23859 description.
23860
23861 This chapter provides a quick startup guide, and
23862 details some Gnat-specific features.
23863
23864 @menu
23865 * Quick startup guide::
23866 * Gnat specifics::
23867 @end menu
23868
23869 @node Quick startup guide
23870 @subsection Quick startup guide
23871
23872 In order to perform coverage analysis of a program using @code{gcov}, 3
23873 steps are needed:
23874
23875 @itemize @bullet
23876 @item
23877 Code instrumentation during the compilation process
23878 @item
23879 Execution of the instrumented program
23880 @item
23881 Execution of the @code{gcov} tool to generate the result.
23882 @end itemize
23883
23884 The code instrumentation needed by gcov is created at the object level:
23885 The source code is not modified in any way, because the instrumentation code is
23886 inserted by gcc during the compilation process. To compile your code with code
23887 coverage activated, you need to recompile your whole project using the
23888 switches
23889 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23890 @code{-fprofile-arcs}.
23891
23892 @smallexample
23893 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23894    -largs -fprofile-arcs
23895 @end smallexample
23896
23897 This compilation process will create @file{.gcno} files together with
23898 the usual object files.
23899
23900 Once the program is compiled with coverage instrumentation, you can
23901 run it as many times as needed - on portions of a test suite for
23902 example. The first execution will produce @file{.gcda} files at the
23903 same location as the @file{.gcno} files.  The following executions
23904 will update those files, so that a cumulative result of the covered
23905 portions of the program is generated.
23906
23907 Finally, you need to call the @code{gcov} tool. The different options of
23908 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23909
23910 This will create annotated source files with a @file{.gcov} extension:
23911 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23912
23913 @node Gnat specifics
23914 @subsection Gnat specifics
23915
23916 Because Ada semantics, portions of the source code may be shared among
23917 several object files. This is the case for example when generics are
23918 involved, when inlining is active  or when declarations generate  initialisation
23919 calls. In order to take
23920 into account this shared code, you need to call @code{gcov} on all
23921 source files of the tested program at once.
23922
23923 The list of source files might exceed the system's maximum command line
23924 length. In order to bypass this limitation, a new mechanism has been
23925 implemented in @code{gcov}: you can now list all your project's files into a
23926 text file, and provide this file to gcov as a parameter,  preceded by a @@
23927 (e.g. @samp{gcov @@mysrclist.txt}).
23928
23929 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23930 not supported as there can be unresolved symbols during the final link.
23931
23932 @node Profiling an Ada Program using gprof
23933 @section Profiling an Ada Program using gprof
23934 @cindex gprof
23935 @cindex -pg
23936 @cindex Profiling
23937
23938 @noindent
23939 This section is not meant to be an exhaustive documentation of @code{gprof}.
23940 Full documentation for it can be found in the GNU Profiler User's Guide
23941 documentation that is part of this GNAT distribution.
23942
23943 Profiling a program helps determine the parts of a program that are executed
23944 most often, and are therefore the most time-consuming.
23945
23946 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23947 better handle Ada programs and multitasking.
23948 It is currently supported on the following platforms
23949 @itemize @bullet
23950 @item
23951 linux x86/x86_64
23952 @item
23953 solaris sparc/sparc64/x86
23954 @item
23955 windows x86
23956 @end itemize
23957
23958 @noindent
23959 In order to profile a program using @code{gprof}, 3 steps are needed:
23960
23961 @itemize @bullet
23962 @item
23963 Code instrumentation, requiring a full recompilation of the project with the
23964 proper switches.
23965 @item
23966 Execution of the program under the analysis conditions, i.e. with the desired
23967 input.
23968 @item
23969 Analysis of the results using the @code{gprof} tool.
23970 @end itemize
23971
23972 @noindent
23973 The following sections detail the different steps, and indicate how
23974 to interpret the results:
23975 @menu
23976 * Compilation for profiling::
23977 * Program execution::
23978 * Running gprof::
23979 * Interpretation of profiling results::
23980 @end menu
23981
23982 @node Compilation for profiling
23983 @subsection Compilation for profiling
23984 @cindex -pg
23985 @cindex Profiling
23986
23987 In order to profile a program the first step is to tell the compiler
23988 to generate the necessary profiling information. The compiler switch to be used
23989 is @code{-pg}, which must be added to other compilation switches. This
23990 switch needs to be specified both during compilation and link stages, and can
23991 be specified once when using gnatmake:
23992
23993 @smallexample
23994 gnatmake -f -pg -P my_project
23995 @end smallexample
23996
23997 @noindent
23998 Note that only the objects that were compiled with the @samp{-pg} switch will be
23999 profiled; if you need to profile your whole project, use the
24000 @samp{-f} gnatmake switch to force full recompilation.
24001
24002 @node Program execution
24003 @subsection Program execution
24004
24005 @noindent
24006 Once the program has been compiled for profiling, you can run it as usual.
24007
24008 The only constraint imposed by profiling is that the program must terminate
24009 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
24010 properly analyzed.
24011
24012 Once the program completes execution, a data file called @file{gmon.out} is
24013 generated in the directory where the program was launched from. If this file
24014 already exists, it will be overwritten.
24015
24016 @node Running gprof
24017 @subsection Running gprof
24018
24019 @noindent
24020 The @code{gprof} tool is called as follow:
24021
24022 @smallexample
24023 gprof my_prog gmon.out
24024 @end smallexample
24025
24026 @noindent
24027 or simpler:
24028
24029 @smallexample
24030 gprof my_prog
24031 @end smallexample
24032
24033 @noindent
24034 The complete form of the gprof command line is the following:
24035
24036 @smallexample
24037 gprof [^switches^options^] [executable [data-file]]
24038 @end smallexample
24039
24040 @noindent
24041 @code{gprof} supports numerous ^switch^options^. The order of these
24042 ^switch^options^ does not matter. The full list of options can be found in
24043 the GNU Profiler User's Guide documentation that comes with this documentation.
24044
24045 The following is the subset of those switches that is most relevant:
24046
24047 @table @option
24048
24049 @item --demangle[=@var{style}]
24050 @itemx --no-demangle
24051 @cindex @option{--demangle} (@code{gprof})
24052 These options control whether symbol names should be demangled when
24053 printing output.  The default is to demangle C++ symbols.  The
24054 @code{--no-demangle} option may be used to turn off demangling. Different
24055 compilers have different mangling styles.  The optional demangling style
24056 argument can be used to choose an appropriate demangling style for your
24057 compiler, in particular Ada symbols generated by GNAT can be demangled using
24058 @code{--demangle=gnat}.
24059
24060 @item -e @var{function_name}
24061 @cindex @option{-e} (@code{gprof})
24062 The @samp{-e @var{function}} option tells @code{gprof} not to print
24063 information about the function @var{function_name} (and its
24064 children@dots{}) in the call graph.  The function will still be listed
24065 as a child of any functions that call it, but its index number will be
24066 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
24067 given; only one @var{function_name} may be indicated with each @samp{-e}
24068 option.
24069
24070 @item -E @var{function_name}
24071 @cindex @option{-E} (@code{gprof})
24072 The @code{-E @var{function}} option works like the @code{-e} option, but
24073 execution time spent in the function (and children who were not called from
24074 anywhere else), will not be used to compute the percentages-of-time for
24075 the call graph.  More than one @samp{-E} option may be given; only one
24076 @var{function_name} may be indicated with each @samp{-E} option.
24077
24078 @item -f @var{function_name}
24079 @cindex @option{-f} (@code{gprof})
24080 The @samp{-f @var{function}} option causes @code{gprof} to limit the
24081 call graph to the function @var{function_name} and its children (and
24082 their children@dots{}).  More than one @samp{-f} option may be given;
24083 only one @var{function_name} may be indicated with each @samp{-f}
24084 option.
24085
24086 @item -F @var{function_name}
24087 @cindex @option{-F} (@code{gprof})
24088 The @samp{-F @var{function}} option works like the @code{-f} option, but
24089 only time spent in the function and its children (and their
24090 children@dots{}) will be used to determine total-time and
24091 percentages-of-time for the call graph.  More than one @samp{-F} option
24092 may be given; only one @var{function_name} may be indicated with each
24093 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
24094
24095 @end table
24096
24097 @node Interpretation of profiling results
24098 @subsection Interpretation of profiling results
24099
24100 @noindent
24101
24102 The results of the profiling analysis are represented by two arrays: the
24103 'flat profile' and the 'call graph'. Full documentation of those outputs
24104 can be found in the GNU Profiler User's Guide.
24105
24106 The flat profile shows the time spent in each function of the program, and how
24107 many time it has been called. This allows you to locate easily the most
24108 time-consuming functions.
24109
24110 The call graph shows, for each subprogram, the subprograms that call it,
24111 and the subprograms that it calls. It also provides an estimate of the time
24112 spent in each of those callers/called subprograms.
24113 @end ifclear
24114
24115 @c ******************************
24116 @node Running and Debugging Ada Programs
24117 @chapter Running and Debugging Ada Programs
24118 @cindex Debugging
24119
24120 @noindent
24121 This chapter discusses how to debug Ada programs.
24122 @ifset vms
24123 It applies to GNAT on the Alpha OpenVMS platform;
24124 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
24125 since HP has implemented Ada support in the OpenVMS debugger on I64.
24126 @end ifset
24127
24128 An incorrect Ada program may be handled in three ways by the GNAT compiler:
24129
24130 @enumerate
24131 @item
24132 The illegality may be a violation of the static semantics of Ada. In
24133 that case GNAT diagnoses the constructs in the program that are illegal.
24134 It is then a straightforward matter for the user to modify those parts of
24135 the program.
24136
24137 @item
24138 The illegality may be a violation of the dynamic semantics of Ada. In
24139 that case the program compiles and executes, but may generate incorrect
24140 results, or may terminate abnormally with some exception.
24141
24142 @item
24143 When presented with a program that contains convoluted errors, GNAT
24144 itself may terminate abnormally without providing full diagnostics on
24145 the incorrect user program.
24146 @end enumerate
24147
24148 @menu
24149 * The GNAT Debugger GDB::
24150 * Running GDB::
24151 * Introduction to GDB Commands::
24152 * Using Ada Expressions::
24153 * Calling User-Defined Subprograms::
24154 * Using the Next Command in a Function::
24155 * Ada Exceptions::
24156 * Ada Tasks::
24157 * Debugging Generic Units::
24158 * GNAT Abnormal Termination or Failure to Terminate::
24159 * Naming Conventions for GNAT Source Files::
24160 * Getting Internal Debugging Information::
24161 * Stack Traceback::
24162 @end menu
24163
24164 @cindex Debugger
24165 @findex gdb
24166
24167 @node The GNAT Debugger GDB
24168 @section The GNAT Debugger GDB
24169
24170 @noindent
24171 @code{GDB} is a general purpose, platform-independent debugger that
24172 can be used to debug mixed-language programs compiled with @command{gcc},
24173 and in particular is capable of debugging Ada programs compiled with
24174 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
24175 complex Ada data structures.
24176
24177 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
24178 @ifset vms
24179 located in the GNU:[DOCS] directory,
24180 @end ifset
24181 for full details on the usage of @code{GDB}, including a section on
24182 its usage on programs. This manual should be consulted for full
24183 details. The section that follows is a brief introduction to the
24184 philosophy and use of @code{GDB}.
24185
24186 When GNAT programs are compiled, the compiler optionally writes debugging
24187 information into the generated object file, including information on
24188 line numbers, and on declared types and variables. This information is
24189 separate from the generated code. It makes the object files considerably
24190 larger, but it does not add to the size of the actual executable that
24191 will be loaded into memory, and has no impact on run-time performance. The
24192 generation of debug information is triggered by the use of the
24193 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
24194 used to carry out the compilations. It is important to emphasize that
24195 the use of these options does not change the generated code.
24196
24197 The debugging information is written in standard system formats that
24198 are used by many tools, including debuggers and profilers. The format
24199 of the information is typically designed to describe C types and
24200 semantics, but GNAT implements a translation scheme which allows full
24201 details about Ada types and variables to be encoded into these
24202 standard C formats. Details of this encoding scheme may be found in
24203 the file exp_dbug.ads in the GNAT source distribution. However, the
24204 details of this encoding are, in general, of no interest to a user,
24205 since @code{GDB} automatically performs the necessary decoding.
24206
24207 When a program is bound and linked, the debugging information is
24208 collected from the object files, and stored in the executable image of
24209 the program. Again, this process significantly increases the size of
24210 the generated executable file, but it does not increase the size of
24211 the executable program itself. Furthermore, if this program is run in
24212 the normal manner, it runs exactly as if the debug information were
24213 not present, and takes no more actual memory.
24214
24215 However, if the program is run under control of @code{GDB}, the
24216 debugger is activated.  The image of the program is loaded, at which
24217 point it is ready to run.  If a run command is given, then the program
24218 will run exactly as it would have if @code{GDB} were not present. This
24219 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
24220 entirely non-intrusive until a breakpoint is encountered.  If no
24221 breakpoint is ever hit, the program will run exactly as it would if no
24222 debugger were present. When a breakpoint is hit, @code{GDB} accesses
24223 the debugging information and can respond to user commands to inspect
24224 variables, and more generally to report on the state of execution.
24225
24226 @c **************
24227 @node Running GDB
24228 @section Running GDB
24229
24230 @noindent
24231 This section describes how to initiate the debugger.
24232 @c The above sentence is really just filler, but it was otherwise
24233 @c clumsy to get the first paragraph nonindented given the conditional
24234 @c nature of the description
24235
24236 @ifclear vms
24237 The debugger can be launched from a @code{GPS} menu or
24238 directly from the command line. The description below covers the latter use.
24239 All the commands shown can be used in the @code{GPS} debug console window,
24240 but there are usually more GUI-based ways to achieve the same effect.
24241 @end ifclear
24242
24243 The command to run @code{GDB} is
24244
24245 @smallexample
24246 $ ^gdb program^GDB PROGRAM^
24247 @end smallexample
24248
24249 @noindent
24250 where @code{^program^PROGRAM^} is the name of the executable file. This
24251 activates the debugger and results in a prompt for debugger commands.
24252 The simplest command is simply @code{run}, which causes the program to run
24253 exactly as if the debugger were not present. The following section
24254 describes some of the additional commands that can be given to @code{GDB}.
24255
24256 @c *******************************
24257 @node Introduction to GDB Commands
24258 @section Introduction to GDB Commands
24259
24260 @noindent
24261 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24262 Debugging with GDB, gdb, Debugging with GDB},
24263 @ifset vms
24264 located in the GNU:[DOCS] directory,
24265 @end ifset
24266 for extensive documentation on the use
24267 of these commands, together with examples of their use. Furthermore,
24268 the command @command{help} invoked from within GDB activates a simple help
24269 facility which summarizes the available commands and their options.
24270 In this section we summarize a few of the most commonly
24271 used commands to give an idea of what @code{GDB} is about. You should create
24272 a simple program with debugging information and experiment with the use of
24273 these @code{GDB} commands on the program as you read through the
24274 following section.
24275
24276 @table @code
24277 @item set args @var{arguments}
24278 The @var{arguments} list above is a list of arguments to be passed to
24279 the program on a subsequent run command, just as though the arguments
24280 had been entered on a normal invocation of the program. The @code{set args}
24281 command is not needed if the program does not require arguments.
24282
24283 @item run
24284 The @code{run} command causes execution of the program to start from
24285 the beginning. If the program is already running, that is to say if
24286 you are currently positioned at a breakpoint, then a prompt will ask
24287 for confirmation that you want to abandon the current execution and
24288 restart.
24289
24290 @item breakpoint @var{location}
24291 The breakpoint command sets a breakpoint, that is to say a point at which
24292 execution will halt and @code{GDB} will await further
24293 commands. @var{location} is
24294 either a line number within a file, given in the format @code{file:linenumber},
24295 or it is the name of a subprogram. If you request that a breakpoint be set on
24296 a subprogram that is overloaded, a prompt will ask you to specify on which of
24297 those subprograms you want to breakpoint. You can also
24298 specify that all of them should be breakpointed. If the program is run
24299 and execution encounters the breakpoint, then the program
24300 stops and @code{GDB} signals that the breakpoint was encountered by
24301 printing the line of code before which the program is halted.
24302
24303 @item breakpoint exception @var{name}
24304 A special form of the breakpoint command which breakpoints whenever
24305 exception @var{name} is raised.
24306 If @var{name} is omitted,
24307 then a breakpoint will occur when any exception is raised.
24308
24309 @item print @var{expression}
24310 This will print the value of the given expression. Most simple
24311 Ada expression formats are properly handled by @code{GDB}, so the expression
24312 can contain function calls, variables, operators, and attribute references.
24313
24314 @item continue
24315 Continues execution following a breakpoint, until the next breakpoint or the
24316 termination of the program.
24317
24318 @item step
24319 Executes a single line after a breakpoint. If the next statement
24320 is a subprogram call, execution continues into (the first statement of)
24321 the called subprogram.
24322
24323 @item next
24324 Executes a single line. If this line is a subprogram call, executes and
24325 returns from the call.
24326
24327 @item list
24328 Lists a few lines around the current source location. In practice, it
24329 is usually more convenient to have a separate edit window open with the
24330 relevant source file displayed. Successive applications of this command
24331 print subsequent lines. The command can be given an argument which is a
24332 line number, in which case it displays a few lines around the specified one.
24333
24334 @item backtrace
24335 Displays a backtrace of the call chain. This command is typically
24336 used after a breakpoint has occurred, to examine the sequence of calls that
24337 leads to the current breakpoint. The display includes one line for each
24338 activation record (frame) corresponding to an active subprogram.
24339
24340 @item up
24341 At a breakpoint, @code{GDB} can display the values of variables local
24342 to the current frame. The command @code{up} can be used to
24343 examine the contents of other active frames, by moving the focus up
24344 the stack, that is to say from callee to caller, one frame at a time.
24345
24346 @item down
24347 Moves the focus of @code{GDB} down from the frame currently being
24348 examined to the frame of its callee (the reverse of the previous command),
24349
24350 @item frame @var{n}
24351 Inspect the frame with the given number. The value 0 denotes the frame
24352 of the current breakpoint, that is to say the top of the call stack.
24353
24354 @end table
24355
24356 @noindent
24357 The above list is a very short introduction to the commands that
24358 @code{GDB} provides. Important additional capabilities, including conditional
24359 breakpoints, the ability to execute command sequences on a breakpoint,
24360 the ability to debug at the machine instruction level and many other
24361 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24362 Debugging with GDB}.  Note that most commands can be abbreviated
24363 (for example, c for continue, bt for backtrace).
24364
24365 @node Using Ada Expressions
24366 @section Using Ada Expressions
24367 @cindex Ada expressions
24368
24369 @noindent
24370 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24371 extensions. The philosophy behind the design of this subset is
24372
24373 @itemize @bullet
24374 @item
24375 That @code{GDB} should provide basic literals and access to operations for
24376 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24377 leaving more sophisticated computations to subprograms written into the
24378 program (which therefore may be called from @code{GDB}).
24379
24380 @item
24381 That type safety and strict adherence to Ada language restrictions
24382 are not particularly important to the @code{GDB} user.
24383
24384 @item
24385 That brevity is important to the @code{GDB} user.
24386 @end itemize
24387
24388 @noindent
24389 Thus, for brevity, the debugger acts as if there were
24390 implicit @code{with} and @code{use} clauses in effect for all user-written
24391 packages, thus making it unnecessary to fully qualify most names with
24392 their packages, regardless of context. Where this causes ambiguity,
24393 @code{GDB} asks the user's intent.
24394
24395 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24396 GDB, gdb, Debugging with GDB}.
24397
24398 @node Calling User-Defined Subprograms
24399 @section Calling User-Defined Subprograms
24400
24401 @noindent
24402 An important capability of @code{GDB} is the ability to call user-defined
24403 subprograms while debugging. This is achieved simply by entering
24404 a subprogram call statement in the form:
24405
24406 @smallexample
24407 call subprogram-name (parameters)
24408 @end smallexample
24409
24410 @noindent
24411 The keyword @code{call} can be omitted in the normal case where the
24412 @code{subprogram-name} does not coincide with any of the predefined
24413 @code{GDB} commands.
24414
24415 The effect is to invoke the given subprogram, passing it the
24416 list of parameters that is supplied. The parameters can be expressions and
24417 can include variables from the program being debugged. The
24418 subprogram must be defined
24419 at the library level within your program, and @code{GDB} will call the
24420 subprogram within the environment of your program execution (which
24421 means that the subprogram is free to access or even modify variables
24422 within your program).
24423
24424 The most important use of this facility is in allowing the inclusion of
24425 debugging routines that are tailored to particular data structures
24426 in your program. Such debugging routines can be written to provide a suitably
24427 high-level description of an abstract type, rather than a low-level dump
24428 of its physical layout. After all, the standard
24429 @code{GDB print} command only knows the physical layout of your
24430 types, not their abstract meaning. Debugging routines can provide information
24431 at the desired semantic level and are thus enormously useful.
24432
24433 For example, when debugging GNAT itself, it is crucial to have access to
24434 the contents of the tree nodes used to represent the program internally.
24435 But tree nodes are represented simply by an integer value (which in turn
24436 is an index into a table of nodes).
24437 Using the @code{print} command on a tree node would simply print this integer
24438 value, which is not very useful. But the PN routine (defined in file
24439 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24440 a useful high level representation of the tree node, which includes the
24441 syntactic category of the node, its position in the source, the integers
24442 that denote descendant nodes and parent node, as well as varied
24443 semantic information. To study this example in more detail, you might want to
24444 look at the body of the PN procedure in the stated file.
24445
24446 @node Using the Next Command in a Function
24447 @section Using the Next Command in a Function
24448
24449 @noindent
24450 When you use the @code{next} command in a function, the current source
24451 location will advance to the next statement as usual. A special case
24452 arises in the case of a @code{return} statement.
24453
24454 Part of the code for a return statement is the ``epilog'' of the function.
24455 This is the code that returns to the caller. There is only one copy of
24456 this epilog code, and it is typically associated with the last return
24457 statement in the function if there is more than one return. In some
24458 implementations, this epilog is associated with the first statement
24459 of the function.
24460
24461 The result is that if you use the @code{next} command from a return
24462 statement that is not the last return statement of the function you
24463 may see a strange apparent jump to the last return statement or to
24464 the start of the function. You should simply ignore this odd jump.
24465 The value returned is always that from the first return statement
24466 that was stepped through.
24467
24468 @node Ada Exceptions
24469 @section Breaking on Ada Exceptions
24470 @cindex Exceptions
24471
24472 @noindent
24473 You can set breakpoints that trip when your program raises
24474 selected exceptions.
24475
24476 @table @code
24477 @item break exception
24478 Set a breakpoint that trips whenever (any task in the) program raises
24479 any exception.
24480
24481 @item break exception @var{name}
24482 Set a breakpoint that trips whenever (any task in the) program raises
24483 the exception @var{name}.
24484
24485 @item break exception unhandled
24486 Set a breakpoint that trips whenever (any task in the) program raises an
24487 exception for which there is no handler.
24488
24489 @item info exceptions
24490 @itemx info exceptions @var{regexp}
24491 The @code{info exceptions} command permits the user to examine all defined
24492 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24493 argument, prints out only those exceptions whose name matches @var{regexp}.
24494 @end table
24495
24496 @node Ada Tasks
24497 @section Ada Tasks
24498 @cindex Tasks
24499
24500 @noindent
24501 @code{GDB} allows the following task-related commands:
24502
24503 @table @code
24504 @item info tasks
24505 This command shows a list of current Ada tasks, as in the following example:
24506
24507 @smallexample
24508 @iftex
24509 @leftskip=0cm
24510 @end iftex
24511 (gdb) info tasks
24512   ID       TID P-ID   Thread Pri State                 Name
24513    1   8088000   0   807e000  15 Child Activation Wait main_task
24514    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24515    3   809a800   1   80a4800  15 Child Activation Wait a
24516 *  4   80ae800   3   80b8000  15 Running               c
24517 @end smallexample
24518
24519 @noindent
24520 In this listing, the asterisk before the first task indicates it to be the
24521 currently running task. The first column lists the task ID that is used
24522 to refer to tasks in the following commands.
24523
24524 @item break @var{linespec} task @var{taskid}
24525 @itemx break @var{linespec} task @var{taskid} if @dots{}
24526 @cindex Breakpoints and tasks
24527 These commands are like the @code{break @dots{} thread @dots{}}.
24528 @var{linespec} specifies source lines.
24529
24530 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24531 to specify that you only want @code{GDB} to stop the program when a
24532 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24533 numeric task identifiers assigned by @code{GDB}, shown in the first
24534 column of the @samp{info tasks} display.
24535
24536 If you do not specify @samp{task @var{taskid}} when you set a
24537 breakpoint, the breakpoint applies to @emph{all} tasks of your
24538 program.
24539
24540 You can use the @code{task} qualifier on conditional breakpoints as
24541 well; in this case, place @samp{task @var{taskid}} before the
24542 breakpoint condition (before the @code{if}).
24543
24544 @item task @var{taskno}
24545 @cindex Task switching
24546
24547 This command allows to switch to the task referred by @var{taskno}. In
24548 particular, This allows to browse the backtrace of the specified
24549 task. It is advised to switch back to the original task before
24550 continuing execution otherwise the scheduling of the program may be
24551 perturbed.
24552 @end table
24553
24554 @noindent
24555 For more detailed information on the tasking support,
24556 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24557
24558 @node Debugging Generic Units
24559 @section Debugging Generic Units
24560 @cindex Debugging Generic Units
24561 @cindex Generics
24562
24563 @noindent
24564 GNAT always uses code expansion for generic instantiation. This means that
24565 each time an instantiation occurs, a complete copy of the original code is
24566 made, with appropriate substitutions of formals by actuals.
24567
24568 It is not possible to refer to the original generic entities in
24569 @code{GDB}, but it is always possible to debug a particular instance of
24570 a generic, by using the appropriate expanded names. For example, if we have
24571
24572 @smallexample @c ada
24573 @group
24574 @cartouche
24575 procedure g is
24576
24577    generic package k is
24578       procedure kp (v1 : in out integer);
24579    end k;
24580
24581    package body k is
24582       procedure kp (v1 : in out integer) is
24583       begin
24584          v1 := v1 + 1;
24585       end kp;
24586    end k;
24587
24588    package k1 is new k;
24589    package k2 is new k;
24590
24591    var : integer := 1;
24592
24593 begin
24594    k1.kp (var);
24595    k2.kp (var);
24596    k1.kp (var);
24597    k2.kp (var);
24598 end;
24599 @end cartouche
24600 @end group
24601 @end smallexample
24602
24603 @noindent
24604 Then to break on a call to procedure kp in the k2 instance, simply
24605 use the command:
24606
24607 @smallexample
24608 (gdb) break g.k2.kp
24609 @end smallexample
24610
24611 @noindent
24612 When the breakpoint occurs, you can step through the code of the
24613 instance in the normal manner and examine the values of local variables, as for
24614 other units.
24615
24616 @node GNAT Abnormal Termination or Failure to Terminate
24617 @section GNAT Abnormal Termination or Failure to Terminate
24618 @cindex GNAT Abnormal Termination or Failure to Terminate
24619
24620 @noindent
24621 When presented with programs that contain serious errors in syntax
24622 or semantics,
24623 GNAT may on rare occasions  experience problems in operation, such
24624 as aborting with a
24625 segmentation fault or illegal memory access, raising an internal
24626 exception, terminating abnormally, or failing to terminate at all.
24627 In such cases, you can activate
24628 various features of GNAT that can help you pinpoint the construct in your
24629 program that is the likely source of the problem.
24630
24631 The following strategies are presented in increasing order of
24632 difficulty, corresponding to your experience in using GNAT and your
24633 familiarity with compiler internals.
24634
24635 @enumerate
24636 @item
24637 Run @command{gcc} with the @option{-gnatf}. This first
24638 switch causes all errors on a given line to be reported. In its absence,
24639 only the first error on a line is displayed.
24640
24641 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24642 are encountered, rather than after compilation is terminated. If GNAT
24643 terminates prematurely or goes into an infinite loop, the last error
24644 message displayed may help to pinpoint the culprit.
24645
24646 @item
24647 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24648 mode, @command{gcc} produces ongoing information about the progress of the
24649 compilation and provides the name of each procedure as code is
24650 generated. This switch allows you to find which Ada procedure was being
24651 compiled when it encountered a code generation problem.
24652
24653 @item
24654 @cindex @option{-gnatdc} switch
24655 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24656 switch that does for the front-end what @option{^-v^VERBOSE^} does
24657 for the back end. The system prints the name of each unit,
24658 either a compilation unit or nested unit, as it is being analyzed.
24659 @item
24660 Finally, you can start
24661 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24662 front-end of GNAT, and can be run independently (normally it is just
24663 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24664 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24665 @code{where} command is the first line of attack; the variable
24666 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24667 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24668 which the execution stopped, and @code{input_file name} indicates the name of
24669 the source file.
24670 @end enumerate
24671
24672 @node Naming Conventions for GNAT Source Files
24673 @section Naming Conventions for GNAT Source Files
24674
24675 @noindent
24676 In order to examine the workings of the GNAT system, the following
24677 brief description of its organization may be helpful:
24678
24679 @itemize @bullet
24680 @item
24681 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24682
24683 @item
24684 All files prefixed with @file{^par^PAR^} are components of the parser. The
24685 numbers correspond to chapters of the Ada Reference Manual. For example,
24686 parsing of select statements can be found in @file{par-ch9.adb}.
24687
24688 @item
24689 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24690 numbers correspond to chapters of the Ada standard. For example, all
24691 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24692 addition, some features of the language require sufficient special processing
24693 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24694 dynamic dispatching, etc.
24695
24696 @item
24697 All files prefixed with @file{^exp^EXP^} perform normalization and
24698 expansion of the intermediate representation (abstract syntax tree, or AST).
24699 these files use the same numbering scheme as the parser and semantics files.
24700 For example, the construction of record initialization procedures is done in
24701 @file{exp_ch3.adb}.
24702
24703 @item
24704 The files prefixed with @file{^bind^BIND^} implement the binder, which
24705 verifies the consistency of the compilation, determines an order of
24706 elaboration, and generates the bind file.
24707
24708 @item
24709 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24710 data structures used by the front-end.
24711
24712 @item
24713 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24714 the abstract syntax tree as produced by the parser.
24715
24716 @item
24717 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24718 all entities, computed during semantic analysis.
24719
24720 @item
24721 Library management issues are dealt with in files with prefix
24722 @file{^lib^LIB^}.
24723
24724 @item
24725 @findex Ada
24726 @cindex Annex A
24727 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24728 defined in Annex A.
24729
24730 @item
24731 @findex Interfaces
24732 @cindex Annex B
24733 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24734 defined in Annex B.
24735
24736 @item
24737 @findex System
24738 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24739 both language-defined children and GNAT run-time routines.
24740
24741 @item
24742 @findex GNAT
24743 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24744 general-purpose packages, fully documented in their specs. All
24745 the other @file{.c} files are modifications of common @command{gcc} files.
24746 @end itemize
24747
24748 @node Getting Internal Debugging Information
24749 @section Getting Internal Debugging Information
24750
24751 @noindent
24752 Most compilers have internal debugging switches and modes. GNAT
24753 does also, except GNAT internal debugging switches and modes are not
24754 secret. A summary and full description of all the compiler and binder
24755 debug flags are in the file @file{debug.adb}. You must obtain the
24756 sources of the compiler to see the full detailed effects of these flags.
24757
24758 The switches that print the source of the program (reconstructed from
24759 the internal tree) are of general interest for user programs, as are the
24760 options to print
24761 the full internal tree, and the entity table (the symbol table
24762 information). The reconstructed source provides a readable version of the
24763 program after the front-end has completed analysis and  expansion,
24764 and is useful when studying the performance of specific constructs.
24765 For example, constraint checks are indicated, complex aggregates
24766 are replaced with loops and assignments, and tasking primitives
24767 are replaced with run-time calls.
24768
24769 @node Stack Traceback
24770 @section Stack Traceback
24771 @cindex traceback
24772 @cindex stack traceback
24773 @cindex stack unwinding
24774
24775 @noindent
24776 Traceback is a mechanism to display the sequence of subprogram calls that
24777 leads to a specified execution point in a program. Often (but not always)
24778 the execution point is an instruction at which an exception has been raised.
24779 This mechanism is also known as @i{stack unwinding} because it obtains
24780 its information by scanning the run-time stack and recovering the activation
24781 records of all active subprograms. Stack unwinding is one of the most
24782 important tools for program debugging.
24783
24784 The first entry stored in traceback corresponds to the deepest calling level,
24785 that is to say the subprogram currently executing the instruction
24786 from which we want to obtain the traceback.
24787
24788 Note that there is no runtime performance penalty when stack traceback
24789 is enabled, and no exception is raised during program execution.
24790
24791 @menu
24792 * Non-Symbolic Traceback::
24793 * Symbolic Traceback::
24794 @end menu
24795
24796 @node Non-Symbolic Traceback
24797 @subsection Non-Symbolic Traceback
24798 @cindex traceback, non-symbolic
24799
24800 @noindent
24801 Note: this feature is not supported on all platforms. See
24802 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24803 platforms.
24804
24805 @menu
24806 * Tracebacks From an Unhandled Exception::
24807 * Tracebacks From Exception Occurrences (non-symbolic)::
24808 * Tracebacks From Anywhere in a Program (non-symbolic)::
24809 @end menu
24810
24811 @node Tracebacks From an Unhandled Exception
24812 @subsubsection Tracebacks From an Unhandled Exception
24813
24814 @noindent
24815 A runtime non-symbolic traceback is a list of addresses of call instructions.
24816 To enable this feature you must use the @option{-E}
24817 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24818 of exception information. You can retrieve this information using the
24819 @code{addr2line} tool.
24820
24821 Here is a simple example:
24822
24823 @smallexample @c ada
24824 @cartouche
24825 procedure STB is
24826
24827    procedure P1 is
24828    begin
24829       raise Constraint_Error;
24830    end P1;
24831
24832    procedure P2 is
24833    begin
24834       P1;
24835    end P2;
24836
24837 begin
24838    P2;
24839 end STB;
24840 @end cartouche
24841 @end smallexample
24842
24843 @smallexample
24844 $ gnatmake stb -bargs -E
24845 $ stb
24846
24847 Execution terminated by unhandled exception
24848 Exception name: CONSTRAINT_ERROR
24849 Message: stb.adb:5
24850 Call stack traceback locations:
24851 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24852 @end smallexample
24853
24854 @noindent
24855 As we see the traceback lists a sequence of addresses for the unhandled
24856 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24857 guess that this exception come from procedure P1. To translate these
24858 addresses into the source lines where the calls appear, the
24859 @code{addr2line} tool, described below, is invaluable. The use of this tool
24860 requires the program to be compiled with debug information.
24861
24862 @smallexample
24863 $ gnatmake -g stb -bargs -E
24864 $ stb
24865
24866 Execution terminated by unhandled exception
24867 Exception name: CONSTRAINT_ERROR
24868 Message: stb.adb:5
24869 Call stack traceback locations:
24870 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24871
24872 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24873    0x4011f1 0x77e892a4
24874
24875 00401373 at d:/stb/stb.adb:5
24876 0040138B at d:/stb/stb.adb:10
24877 0040139C at d:/stb/stb.adb:14
24878 00401335 at d:/stb/b~stb.adb:104
24879 004011C4 at /build/@dots{}/crt1.c:200
24880 004011F1 at /build/@dots{}/crt1.c:222
24881 77E892A4 in ?? at ??:0
24882 @end smallexample
24883
24884 @noindent
24885 The @code{addr2line} tool has several other useful options:
24886
24887 @table @code
24888 @item --functions
24889 to get the function name corresponding to any location
24890
24891 @item --demangle=gnat
24892 to use the gnat decoding mode for the function names. Note that
24893 for binutils version 2.9.x the option is simply @option{--demangle}.
24894 @end table
24895
24896 @smallexample
24897 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24898    0x40139c 0x401335 0x4011c4 0x4011f1
24899
24900 00401373 in stb.p1 at d:/stb/stb.adb:5
24901 0040138B in stb.p2 at d:/stb/stb.adb:10
24902 0040139C in stb at d:/stb/stb.adb:14
24903 00401335 in main at d:/stb/b~stb.adb:104
24904 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24905 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24906 @end smallexample
24907
24908 @noindent
24909 From this traceback we can see that the exception was raised in
24910 @file{stb.adb} at line 5, which was reached from a procedure call in
24911 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24912 which contains the call to the main program.
24913 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24914 and the output will vary from platform to platform.
24915
24916 It is also possible to use @code{GDB} with these traceback addresses to debug
24917 the program. For example, we can break at a given code location, as reported
24918 in the stack traceback:
24919
24920 @smallexample
24921 $ gdb -nw stb
24922 @ifclear vms
24923 @noindent
24924 Furthermore, this feature is not implemented inside Windows DLL. Only
24925 the non-symbolic traceback is reported in this case.
24926 @end ifclear
24927
24928 (gdb) break *0x401373
24929 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24930 @end smallexample
24931
24932 @noindent
24933 It is important to note that the stack traceback addresses
24934 do not change when debug information is included. This is particularly useful
24935 because it makes it possible to release software without debug information (to
24936 minimize object size), get a field report that includes a stack traceback
24937 whenever an internal bug occurs, and then be able to retrieve the sequence
24938 of calls with the same program compiled with debug information.
24939
24940 @node Tracebacks From Exception Occurrences (non-symbolic)
24941 @subsubsection Tracebacks From Exception Occurrences
24942
24943 @noindent
24944 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24945 The stack traceback is attached to the exception information string, and can
24946 be retrieved in an exception handler within the Ada program, by means of the
24947 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24948
24949 @smallexample @c ada
24950 with Ada.Text_IO;
24951 with Ada.Exceptions;
24952
24953 procedure STB is
24954
24955    use Ada;
24956    use Ada.Exceptions;
24957
24958    procedure P1 is
24959       K : Positive := 1;
24960    begin
24961       K := K - 1;
24962    exception
24963       when E : others =>
24964          Text_IO.Put_Line (Exception_Information (E));
24965    end P1;
24966
24967    procedure P2 is
24968    begin
24969       P1;
24970    end P2;
24971
24972 begin
24973    P2;
24974 end STB;
24975 @end smallexample
24976
24977 @noindent
24978 This program will output:
24979
24980 @smallexample
24981 $ stb
24982
24983 Exception name: CONSTRAINT_ERROR
24984 Message: stb.adb:12
24985 Call stack traceback locations:
24986 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24987 @end smallexample
24988
24989 @node Tracebacks From Anywhere in a Program (non-symbolic)
24990 @subsubsection Tracebacks From Anywhere in a Program
24991
24992 @noindent
24993 It is also possible to retrieve a stack traceback from anywhere in a
24994 program. For this you need to
24995 use the @code{GNAT.Traceback} API. This package includes a procedure called
24996 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24997 display procedures described below. It is not necessary to use the
24998 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24999 is invoked explicitly.
25000
25001 @noindent
25002 In the following example we compute a traceback at a specific location in
25003 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
25004 convert addresses to strings:
25005
25006 @smallexample @c ada
25007 with Ada.Text_IO;
25008 with GNAT.Traceback;
25009 with GNAT.Debug_Utilities;
25010
25011 procedure STB is
25012
25013    use Ada;
25014    use GNAT;
25015    use GNAT.Traceback;
25016
25017    procedure P1 is
25018       TB  : Tracebacks_Array (1 .. 10);
25019       --  We are asking for a maximum of 10 stack frames.
25020       Len : Natural;
25021       --  Len will receive the actual number of stack frames returned.
25022    begin
25023       Call_Chain (TB, Len);
25024
25025       Text_IO.Put ("In STB.P1 : ");
25026
25027       for K in 1 .. Len loop
25028          Text_IO.Put (Debug_Utilities.Image (TB (K)));
25029          Text_IO.Put (' ');
25030       end loop;
25031
25032       Text_IO.New_Line;
25033    end P1;
25034
25035    procedure P2 is
25036    begin
25037       P1;
25038    end P2;
25039
25040 begin
25041    P2;
25042 end STB;
25043 @end smallexample
25044
25045 @smallexample
25046 $ gnatmake -g stb
25047 $ stb
25048
25049 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
25050 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
25051 @end smallexample
25052
25053 @noindent
25054 You can then get further information by invoking the @code{addr2line}
25055 tool as described earlier (note that the hexadecimal addresses
25056 need to be specified in C format, with a leading ``0x'').
25057
25058 @node Symbolic Traceback
25059 @subsection Symbolic Traceback
25060 @cindex traceback, symbolic
25061
25062 @noindent
25063 A symbolic traceback is a stack traceback in which procedure names are
25064 associated with each code location.
25065
25066 @noindent
25067 Note that this feature is not supported on all platforms. See
25068 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
25069 list of currently supported platforms.
25070
25071 @noindent
25072 Note that the symbolic traceback requires that the program be compiled
25073 with debug information. If it is not compiled with debug information
25074 only the non-symbolic information will be valid.
25075
25076 @menu
25077 * Tracebacks From Exception Occurrences (symbolic)::
25078 * Tracebacks From Anywhere in a Program (symbolic)::
25079 @end menu
25080
25081 @node Tracebacks From Exception Occurrences (symbolic)
25082 @subsubsection Tracebacks From Exception Occurrences
25083
25084 @smallexample @c ada
25085 with Ada.Text_IO;
25086 with GNAT.Traceback.Symbolic;
25087
25088 procedure STB is
25089
25090    procedure P1 is
25091    begin
25092       raise Constraint_Error;
25093    end P1;
25094
25095    procedure P2 is
25096    begin
25097       P1;
25098    end P2;
25099
25100    procedure P3 is
25101    begin
25102       P2;
25103    end P3;
25104
25105 begin
25106    P3;
25107 exception
25108    when E : others =>
25109       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
25110 end STB;
25111 @end smallexample
25112
25113 @smallexample
25114 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
25115 $ stb
25116
25117 0040149F in stb.p1 at stb.adb:8
25118 004014B7 in stb.p2 at stb.adb:13
25119 004014CF in stb.p3 at stb.adb:18
25120 004015DD in ada.stb at stb.adb:22
25121 00401461 in main at b~stb.adb:168
25122 004011C4 in __mingw_CRTStartup at crt1.c:200
25123 004011F1 in mainCRTStartup at crt1.c:222
25124 77E892A4 in ?? at ??:0
25125 @end smallexample
25126
25127 @noindent
25128 In the above example the ``.\'' syntax in the @command{gnatmake} command
25129 is currently required by @command{addr2line} for files that are in
25130 the current working directory.
25131 Moreover, the exact sequence of linker options may vary from platform
25132 to platform.
25133 The above @option{-largs} section is for Windows platforms. By contrast,
25134 under Unix there is no need for the @option{-largs} section.
25135 Differences across platforms are due to details of linker implementation.
25136
25137 @node Tracebacks From Anywhere in a Program (symbolic)
25138 @subsubsection Tracebacks From Anywhere in a Program
25139
25140 @noindent
25141 It is possible to get a symbolic stack traceback
25142 from anywhere in a program, just as for non-symbolic tracebacks.
25143 The first step is to obtain a non-symbolic
25144 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
25145 information. Here is an example:
25146
25147 @smallexample @c ada
25148 with Ada.Text_IO;
25149 with GNAT.Traceback;
25150 with GNAT.Traceback.Symbolic;
25151
25152 procedure STB is
25153
25154    use Ada;
25155    use GNAT.Traceback;
25156    use GNAT.Traceback.Symbolic;
25157
25158    procedure P1 is
25159       TB  : Tracebacks_Array (1 .. 10);
25160       --  We are asking for a maximum of 10 stack frames.
25161       Len : Natural;
25162       --  Len will receive the actual number of stack frames returned.
25163    begin
25164       Call_Chain (TB, Len);
25165       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
25166    end P1;
25167
25168    procedure P2 is
25169    begin
25170       P1;
25171    end P2;
25172
25173 begin
25174    P2;
25175 end STB;
25176 @end smallexample
25177
25178 @c ******************************
25179 @ifset vms
25180 @node Compatibility with HP Ada
25181 @chapter Compatibility with HP Ada
25182 @cindex Compatibility
25183
25184 @noindent
25185 @cindex DEC Ada
25186 @cindex HP Ada
25187 @cindex Compatibility between GNAT and HP Ada
25188 This chapter compares HP Ada (formerly known as ``DEC Ada'')
25189 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
25190 GNAT is highly compatible
25191 with HP Ada, and it should generally be straightforward to port code
25192 from the HP Ada environment to GNAT. However, there are a few language
25193 and implementation differences of which the user must be aware. These
25194 differences are discussed in this chapter. In
25195 addition, the operating environment and command structure for the
25196 compiler are different, and these differences are also discussed.
25197
25198 For further details on these and other compatibility issues,
25199 see Appendix E of the HP publication
25200 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
25201
25202 Except where otherwise indicated, the description of GNAT for OpenVMS
25203 applies to both the Alpha and I64 platforms.
25204
25205 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
25206 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25207
25208 The discussion in this chapter addresses specifically the implementation
25209 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
25210 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
25211 GNAT always follows the Alpha implementation.
25212
25213 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
25214 attributes are recognized, although only a subset of them can sensibly
25215 be implemented.  The description of pragmas in
25216 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
25217 indicates whether or not they are applicable to non-VMS systems.
25218
25219 @menu
25220 * Ada Language Compatibility::
25221 * Differences in the Definition of Package System::
25222 * Language-Related Features::
25223 * The Package STANDARD::
25224 * The Package SYSTEM::
25225 * Tasking and Task-Related Features::
25226 * Pragmas and Pragma-Related Features::
25227 * Library of Predefined Units::
25228 * Bindings::
25229 * Main Program Definition::
25230 * Implementation-Defined Attributes::
25231 * Compiler and Run-Time Interfacing::
25232 * Program Compilation and Library Management::
25233 * Input-Output::
25234 * Implementation Limits::
25235 * Tools and Utilities::
25236 @end menu
25237
25238 @node Ada Language Compatibility
25239 @section Ada Language Compatibility
25240
25241 @noindent
25242 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25243 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25244 with Ada 83, and therefore Ada 83 programs will compile
25245 and run under GNAT with
25246 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25247 provides details on specific incompatibilities.
25248
25249 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25250 as well as the pragma @code{ADA_83}, to force the compiler to
25251 operate in Ada 83 mode. This mode does not guarantee complete
25252 conformance to Ada 83, but in practice is sufficient to
25253 eliminate most sources of incompatibilities.
25254 In particular, it eliminates the recognition of the
25255 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25256 in Ada 83 programs is legal, and handles the cases of packages
25257 with optional bodies, and generics that instantiate unconstrained
25258 types without the use of @code{(<>)}.
25259
25260 @node Differences in the Definition of Package System
25261 @section Differences in the Definition of Package @code{System}
25262
25263 @noindent
25264 An Ada compiler is allowed to add
25265 implementation-dependent declarations to package @code{System}.
25266 In normal mode,
25267 GNAT does not take advantage of this permission, and the version of
25268 @code{System} provided by GNAT exactly matches that defined in the Ada
25269 Reference Manual.
25270
25271 However, HP Ada adds an extensive set of declarations to package
25272 @code{System},
25273 as fully documented in the HP Ada manuals. To minimize changes required
25274 for programs that make use of these extensions, GNAT provides the pragma
25275 @code{Extend_System} for extending the definition of package System. By using:
25276 @cindex pragma @code{Extend_System}
25277 @cindex @code{Extend_System} pragma
25278
25279 @smallexample @c ada
25280 @group
25281 @cartouche
25282 pragma Extend_System (Aux_DEC);
25283 @end cartouche
25284 @end group
25285 @end smallexample
25286
25287 @noindent
25288 the set of definitions in @code{System} is extended to include those in
25289 package @code{System.Aux_DEC}.
25290 @cindex @code{System.Aux_DEC} package
25291 @cindex @code{Aux_DEC} package (child of @code{System})
25292 These definitions are incorporated directly into package @code{System},
25293 as though they had been declared there. For a
25294 list of the declarations added, see the spec of this package,
25295 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25296 @cindex @file{s-auxdec.ads} file
25297 The pragma @code{Extend_System} is a configuration pragma, which means that
25298 it can be placed in the file @file{gnat.adc}, so that it will automatically
25299 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25300 for further details.
25301
25302 An alternative approach that avoids the use of the non-standard
25303 @code{Extend_System} pragma is to add a context clause to the unit that
25304 references these facilities:
25305
25306 @smallexample @c ada
25307 @cartouche
25308 with System.Aux_DEC;
25309 use  System.Aux_DEC;
25310 @end cartouche
25311 @end smallexample
25312
25313 @noindent
25314 The effect is not quite semantically identical to incorporating
25315 the declarations directly into package @code{System},
25316 but most programs will not notice a difference
25317 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25318 to reference the entities directly in package @code{System}.
25319 For units containing such references,
25320 the prefixes must either be removed, or the pragma @code{Extend_System}
25321 must be used.
25322
25323 @node Language-Related Features
25324 @section Language-Related Features
25325
25326 @noindent
25327 The following sections highlight differences in types,
25328 representations of types, operations, alignment, and
25329 related topics.
25330
25331 @menu
25332 * Integer Types and Representations::
25333 * Floating-Point Types and Representations::
25334 * Pragmas Float_Representation and Long_Float::
25335 * Fixed-Point Types and Representations::
25336 * Record and Array Component Alignment::
25337 * Address Clauses::
25338 * Other Representation Clauses::
25339 @end menu
25340
25341 @node Integer Types and Representations
25342 @subsection Integer Types and Representations
25343
25344 @noindent
25345 The set of predefined integer types is identical in HP Ada and GNAT.
25346 Furthermore the representation of these integer types is also identical,
25347 including the capability of size clauses forcing biased representation.
25348
25349 In addition,
25350 HP Ada for OpenVMS Alpha systems has defined the
25351 following additional integer types in package @code{System}:
25352
25353 @itemize @bullet
25354
25355 @item
25356 @code{INTEGER_8}
25357
25358 @item
25359 @code{INTEGER_16}
25360
25361 @item
25362 @code{INTEGER_32}
25363
25364 @item
25365 @code{INTEGER_64}
25366
25367 @item
25368 @code{LARGEST_INTEGER}
25369 @end itemize
25370
25371 @noindent
25372 In GNAT, the first four of these types may be obtained from the
25373 standard Ada package @code{Interfaces}.
25374 Alternatively, by use of the pragma @code{Extend_System}, identical
25375 declarations can be referenced directly in package @code{System}.
25376 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25377
25378 @node Floating-Point Types and Representations
25379 @subsection Floating-Point Types and Representations
25380 @cindex Floating-Point types
25381
25382 @noindent
25383 The set of predefined floating-point types is identical in HP Ada and GNAT.
25384 Furthermore the representation of these floating-point
25385 types is also identical. One important difference is that the default
25386 representation for HP Ada is @code{VAX_Float}, but the default representation
25387 for GNAT is IEEE.
25388
25389 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25390 pragma @code{Float_Representation} as described in the HP Ada
25391 documentation.
25392 For example, the declarations:
25393
25394 @smallexample @c ada
25395 @cartouche
25396 type F_Float is digits 6;
25397 pragma Float_Representation (VAX_Float, F_Float);
25398 @end cartouche
25399 @end smallexample
25400
25401 @noindent
25402 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25403 format.
25404 This set of declarations actually appears in @code{System.Aux_DEC},
25405 which contains
25406 the full set of additional floating-point declarations provided in
25407 the HP Ada version of package @code{System}.
25408 This and similar declarations may be accessed in a user program
25409 by using pragma @code{Extend_System}. The use of this
25410 pragma, and the related pragma @code{Long_Float} is described in further
25411 detail in the following section.
25412
25413 @node Pragmas Float_Representation and Long_Float
25414 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25415
25416 @noindent
25417 HP Ada provides the pragma @code{Float_Representation}, which
25418 acts as a program library switch to allow control over
25419 the internal representation chosen for the predefined
25420 floating-point types declared in the package @code{Standard}.
25421 The format of this pragma is as follows:
25422
25423 @smallexample @c ada
25424 @cartouche
25425 pragma Float_Representation(VAX_Float | IEEE_Float);
25426 @end cartouche
25427 @end smallexample
25428
25429 @noindent
25430 This pragma controls the representation of floating-point
25431 types as follows:
25432
25433 @itemize @bullet
25434 @item
25435 @code{VAX_Float} specifies that floating-point
25436 types are represented by default with the VAX system hardware types
25437 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25438 Note that the @code{H-floating}
25439 type was available only on VAX systems, and is not available
25440 in either HP Ada or GNAT.
25441
25442 @item
25443 @code{IEEE_Float} specifies that floating-point
25444 types are represented by default with the IEEE single and
25445 double floating-point types.
25446 @end itemize
25447
25448 @noindent
25449 GNAT provides an identical implementation of the pragma
25450 @code{Float_Representation}, except that it functions as a
25451 configuration pragma. Note that the
25452 notion of configuration pragma corresponds closely to the
25453 HP Ada notion of a program library switch.
25454
25455 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25456 which is different
25457 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25458 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25459 advisable to change the format of numbers passed to standard library
25460 routines, and if necessary explicit type conversions may be needed.
25461
25462 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25463 efficient, and (given that it conforms to an international standard)
25464 potentially more portable.
25465 The situation in which @code{VAX_Float} may be useful is in interfacing
25466 to existing code and data that expect the use of @code{VAX_Float}.
25467 In such a situation use the predefined @code{VAX_Float}
25468 types in package @code{System}, as extended by
25469 @code{Extend_System}. For example, use @code{System.F_Float}
25470 to specify the 32-bit @code{F-Float} format.
25471
25472 @noindent
25473 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25474 to allow control over the internal representation chosen
25475 for the predefined type @code{Long_Float} and for floating-point
25476 type declarations with digits specified in the range 7 .. 15.
25477 The format of this pragma is as follows:
25478
25479 @smallexample @c ada
25480 @cartouche
25481 pragma Long_Float (D_FLOAT | G_FLOAT);
25482 @end cartouche
25483 @end smallexample
25484
25485 @node Fixed-Point Types and Representations
25486 @subsection Fixed-Point Types and Representations
25487
25488 @noindent
25489 On HP Ada for OpenVMS Alpha systems, rounding is
25490 away from zero for both positive and negative numbers.
25491 Therefore, @code{+0.5} rounds to @code{1},
25492 and @code{-0.5} rounds to @code{-1}.
25493
25494 On GNAT the results of operations
25495 on fixed-point types are in accordance with the Ada
25496 rules. In particular, results of operations on decimal
25497 fixed-point types are truncated.
25498
25499 @node Record and Array Component Alignment
25500 @subsection Record and Array Component Alignment
25501
25502 @noindent
25503 On HP Ada for OpenVMS Alpha, all non-composite components
25504 are aligned on natural boundaries. For example, 1-byte
25505 components are aligned on byte boundaries, 2-byte
25506 components on 2-byte boundaries, 4-byte components on 4-byte
25507 byte boundaries, and so on. The OpenVMS Alpha hardware
25508 runs more efficiently with naturally aligned data.
25509
25510 On GNAT, alignment rules are compatible
25511 with HP Ada for OpenVMS Alpha.
25512
25513 @node Address Clauses
25514 @subsection Address Clauses
25515
25516 @noindent
25517 In HP Ada and GNAT, address clauses are supported for
25518 objects and imported subprograms.
25519 The predefined type @code{System.Address} is a private type
25520 in both compilers on Alpha OpenVMS, with the same representation
25521 (it is simply a machine pointer). Addition, subtraction, and comparison
25522 operations are available in the standard Ada package
25523 @code{System.Storage_Elements}, or in package @code{System}
25524 if it is extended to include @code{System.Aux_DEC} using a
25525 pragma @code{Extend_System} as previously described.
25526
25527 Note that code that @code{with}'s both this extended package @code{System}
25528 and the package @code{System.Storage_Elements} should not @code{use}
25529 both packages, or ambiguities will result. In general it is better
25530 not to mix these two sets of facilities. The Ada package was
25531 designed specifically to provide the kind of features that HP Ada
25532 adds directly to package @code{System}.
25533
25534 The type @code{System.Address} is a 64-bit integer type in GNAT for
25535 I64 OpenVMS.  For more information,
25536 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25537
25538 GNAT is compatible with HP Ada in its handling of address
25539 clauses, except for some limitations in
25540 the form of address clauses for composite objects with
25541 initialization. Such address clauses are easily replaced
25542 by the use of an explicitly-defined constant as described
25543 in the Ada Reference Manual (13.1(22)). For example, the sequence
25544 of declarations:
25545
25546 @smallexample @c ada
25547 @cartouche
25548 X, Y : Integer := Init_Func;
25549 Q : String (X .. Y) := "abc";
25550 @dots{}
25551 for Q'Address use Compute_Address;
25552 @end cartouche
25553 @end smallexample
25554
25555 @noindent
25556 will be rejected by GNAT, since the address cannot be computed at the time
25557 that @code{Q} is declared. To achieve the intended effect, write instead:
25558
25559 @smallexample @c ada
25560 @group
25561 @cartouche
25562 X, Y : Integer := Init_Func;
25563 Q_Address : constant Address := Compute_Address;
25564 Q : String (X .. Y) := "abc";
25565 @dots{}
25566 for Q'Address use Q_Address;
25567 @end cartouche
25568 @end group
25569 @end smallexample
25570
25571 @noindent
25572 which will be accepted by GNAT (and other Ada compilers), and is also
25573 compatible with Ada 83. A fuller description of the restrictions
25574 on address specifications is found in @ref{Top, GNAT Reference Manual,
25575 About This Guide, gnat_rm, GNAT Reference Manual}.
25576
25577 @node Other Representation Clauses
25578 @subsection Other Representation Clauses
25579
25580 @noindent
25581 GNAT implements in a compatible manner all the representation
25582 clauses supported by HP Ada. In addition, GNAT
25583 implements the representation clause forms that were introduced in Ada 95,
25584 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25585
25586 @node The Package STANDARD
25587 @section The Package @code{STANDARD}
25588
25589 @noindent
25590 The package @code{STANDARD}, as implemented by HP Ada, is fully
25591 described in the @cite{Ada Reference Manual} and in the
25592 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25593 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25594
25595 In addition, HP Ada supports the Latin-1 character set in
25596 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25597 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25598 the type @code{WIDE_CHARACTER}.
25599
25600 The floating-point types supported by GNAT are those
25601 supported by HP Ada, but the defaults are different, and are controlled by
25602 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25603
25604 @node The Package SYSTEM
25605 @section The Package @code{SYSTEM}
25606
25607 @noindent
25608 HP Ada provides a specific version of the package
25609 @code{SYSTEM} for each platform on which the language is implemented.
25610 For the complete spec of the package @code{SYSTEM}, see
25611 Appendix F of the @cite{HP Ada Language Reference Manual}.
25612
25613 On HP Ada, the package @code{SYSTEM} includes the following conversion
25614 functions:
25615 @itemize @bullet
25616 @item @code{TO_ADDRESS(INTEGER)}
25617
25618 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25619
25620 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25621
25622 @item @code{TO_INTEGER(ADDRESS)}
25623
25624 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25625
25626 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25627 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25628 @end itemize
25629
25630 @noindent
25631 By default, GNAT supplies a version of @code{SYSTEM} that matches
25632 the definition given in the @cite{Ada Reference Manual}.
25633 This
25634 is a subset of the HP system definitions, which is as
25635 close as possible to the original definitions. The only difference
25636 is that the definition of @code{SYSTEM_NAME} is different:
25637
25638 @smallexample @c ada
25639 @cartouche
25640 type Name is (SYSTEM_NAME_GNAT);
25641 System_Name : constant Name := SYSTEM_NAME_GNAT;
25642 @end cartouche
25643 @end smallexample
25644
25645 @noindent
25646 Also, GNAT adds the Ada declarations for
25647 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25648
25649 However, the use of the following pragma causes GNAT
25650 to extend the definition of package @code{SYSTEM} so that it
25651 encompasses the full set of HP-specific extensions,
25652 including the functions listed above:
25653
25654 @smallexample @c ada
25655 @cartouche
25656 pragma Extend_System (Aux_DEC);
25657 @end cartouche
25658 @end smallexample
25659
25660 @noindent
25661 The pragma @code{Extend_System} is a configuration pragma that
25662 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25663 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25664
25665 HP Ada does not allow the recompilation of the package
25666 @code{SYSTEM}. Instead HP Ada provides several pragmas
25667 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25668 to modify values in the package @code{SYSTEM}.
25669 On OpenVMS Alpha systems, the pragma
25670 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25671 its single argument.
25672
25673 GNAT does permit the recompilation of package @code{SYSTEM} using
25674 the special switch @option{-gnatg}, and this switch can be used if
25675 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25676 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25677 or @code{MEMORY_SIZE} by any other means.
25678
25679 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25680 enumeration literal @code{SYSTEM_NAME_GNAT}.
25681
25682 The definitions provided by the use of
25683
25684 @smallexample @c ada
25685 pragma Extend_System (AUX_Dec);
25686 @end smallexample
25687
25688 @noindent
25689 are virtually identical to those provided by the HP Ada 83 package
25690 @code{SYSTEM}. One important difference is that the name of the
25691 @code{TO_ADDRESS}
25692 function for type @code{UNSIGNED_LONGWORD} is changed to
25693 @code{TO_ADDRESS_LONG}.
25694 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25695 discussion of why this change was necessary.
25696
25697 @noindent
25698 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25699 is in fact
25700 an extension to Ada 83 not strictly compatible with the reference manual.
25701 GNAT, in order to be exactly compatible with the standard,
25702 does not provide this capability. In HP Ada 83, the
25703 point of this definition is to deal with a call like:
25704
25705 @smallexample @c ada
25706 TO_ADDRESS (16#12777#);
25707 @end smallexample
25708
25709 @noindent
25710 Normally, according to Ada 83 semantics, one would expect this to be
25711 ambiguous, since it matches both the @code{INTEGER} and
25712 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25713 However, in HP Ada 83, there is no ambiguity, since the
25714 definition using @i{universal_integer} takes precedence.
25715
25716 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25717 it is
25718 not possible to be 100% compatible. Since there are many programs using
25719 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25720 GNAT was
25721 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25722 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25723
25724 @smallexample @c ada
25725 function To_Address (X : Integer) return Address;
25726 pragma Pure_Function (To_Address);
25727
25728 function To_Address_Long (X : Unsigned_Longword) return Address;
25729 pragma Pure_Function (To_Address_Long);
25730 @end smallexample
25731
25732 @noindent
25733 This means that programs using @code{TO_ADDRESS} for
25734 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25735
25736 @node Tasking and Task-Related Features
25737 @section Tasking and Task-Related Features
25738
25739 @noindent
25740 This section compares the treatment of tasking in GNAT
25741 and in HP Ada for OpenVMS Alpha.
25742 The GNAT description applies to both Alpha and I64 OpenVMS.
25743 For detailed information on tasking in
25744 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25745 relevant run-time reference manual.
25746
25747 @menu
25748 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25749 * Assigning Task IDs::
25750 * Task IDs and Delays::
25751 * Task-Related Pragmas::
25752 * Scheduling and Task Priority::
25753 * The Task Stack::
25754 * External Interrupts::
25755 @end menu
25756
25757 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25758 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25759
25760 @noindent
25761 On OpenVMS Alpha systems, each Ada task (except a passive
25762 task) is implemented as a single stream of execution
25763 that is created and managed by the kernel. On these
25764 systems, HP Ada tasking support is based on DECthreads,
25765 an implementation of the POSIX standard for threads.
25766
25767 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25768 code that calls DECthreads routines can be used together.
25769 The interaction between Ada tasks and DECthreads routines
25770 can have some benefits. For example when on OpenVMS Alpha,
25771 HP Ada can call C code that is already threaded.
25772
25773 GNAT uses the facilities of DECthreads,
25774 and Ada tasks are mapped to threads.
25775
25776 @node Assigning Task IDs
25777 @subsection Assigning Task IDs
25778
25779 @noindent
25780 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25781 the environment task that executes the main program. On
25782 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25783 that have been created but are not yet activated.
25784
25785 On OpenVMS Alpha systems, task IDs are assigned at
25786 activation. On GNAT systems, task IDs are also assigned at
25787 task creation but do not have the same form or values as
25788 task ID values in HP Ada. There is no null task, and the
25789 environment task does not have a specific task ID value.
25790
25791 @node Task IDs and Delays
25792 @subsection Task IDs and Delays
25793
25794 @noindent
25795 On OpenVMS Alpha systems, tasking delays are implemented
25796 using Timer System Services. The Task ID is used for the
25797 identification of the timer request (the @code{REQIDT} parameter).
25798 If Timers are used in the application take care not to use
25799 @code{0} for the identification, because cancelling such a timer
25800 will cancel all timers and may lead to unpredictable results.
25801
25802 @node Task-Related Pragmas
25803 @subsection Task-Related Pragmas
25804
25805 @noindent
25806 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25807 specification of the size of the guard area for a task
25808 stack. (The guard area forms an area of memory that has no
25809 read or write access and thus helps in the detection of
25810 stack overflow.) On OpenVMS Alpha systems, if the pragma
25811 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25812 area is created. In the absence of a pragma @code{TASK_STORAGE},
25813 a default guard area is created.
25814
25815 GNAT supplies the following task-related pragmas:
25816
25817 @itemize @bullet
25818 @item  @code{TASK_INFO}
25819
25820 This pragma appears within a task definition and
25821 applies to the task in which it appears. The argument
25822 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25823
25824 @item  @code{TASK_STORAGE}
25825
25826 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25827 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25828 @code{SUPPRESS}, and @code{VOLATILE}.
25829 @end itemize
25830 @node Scheduling and Task Priority
25831 @subsection Scheduling and Task Priority
25832
25833 @noindent
25834 HP Ada implements the Ada language requirement that
25835 when two tasks are eligible for execution and they have
25836 different priorities, the lower priority task does not
25837 execute while the higher priority task is waiting. The HP
25838 Ada Run-Time Library keeps a task running until either the
25839 task is suspended or a higher priority task becomes ready.
25840
25841 On OpenVMS Alpha systems, the default strategy is round-
25842 robin with preemption. Tasks of equal priority take turns
25843 at the processor. A task is run for a certain period of
25844 time and then placed at the tail of the ready queue for
25845 its priority level.
25846
25847 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25848 which can be used to enable or disable round-robin
25849 scheduling of tasks with the same priority.
25850 See the relevant HP Ada run-time reference manual for
25851 information on using the pragmas to control HP Ada task
25852 scheduling.
25853
25854 GNAT follows the scheduling rules of Annex D (Real-Time
25855 Annex) of the @cite{Ada Reference Manual}. In general, this
25856 scheduling strategy is fully compatible with HP Ada
25857 although it provides some additional constraints (as
25858 fully documented in Annex D).
25859 GNAT implements time slicing control in a manner compatible with
25860 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25861 are identical to the HP Ada 83 pragma of the same name.
25862 Note that it is not possible to mix GNAT tasking and
25863 HP Ada 83 tasking in the same program, since the two run-time
25864 libraries are not compatible.
25865
25866 @node The Task Stack
25867 @subsection The Task Stack
25868
25869 @noindent
25870 In HP Ada, a task stack is allocated each time a
25871 non-passive task is activated. As soon as the task is
25872 terminated, the storage for the task stack is deallocated.
25873 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25874 a default stack size is used. Also, regardless of the size
25875 specified, some additional space is allocated for task
25876 management purposes. On OpenVMS Alpha systems, at least
25877 one page is allocated.
25878
25879 GNAT handles task stacks in a similar manner. In accordance with
25880 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25881 an alternative method for controlling the task stack size.
25882 The specification of the attribute @code{T'STORAGE_SIZE} is also
25883 supported in a manner compatible with HP Ada.
25884
25885 @node External Interrupts
25886 @subsection External Interrupts
25887
25888 @noindent
25889 On HP Ada, external interrupts can be associated with task entries.
25890 GNAT is compatible with HP Ada in its handling of external interrupts.
25891
25892 @node Pragmas and Pragma-Related Features
25893 @section Pragmas and Pragma-Related Features
25894
25895 @noindent
25896 Both HP Ada and GNAT supply all language-defined pragmas
25897 as specified by the Ada 83 standard. GNAT also supplies all
25898 language-defined pragmas introduced by Ada 95 and Ada 2005.
25899 In addition, GNAT implements the implementation-defined pragmas
25900 from HP Ada 83.
25901
25902 @itemize @bullet
25903 @item  @code{AST_ENTRY}
25904
25905 @item  @code{COMMON_OBJECT}
25906
25907 @item  @code{COMPONENT_ALIGNMENT}
25908
25909 @item  @code{EXPORT_EXCEPTION}
25910
25911 @item  @code{EXPORT_FUNCTION}
25912
25913 @item  @code{EXPORT_OBJECT}
25914
25915 @item  @code{EXPORT_PROCEDURE}
25916
25917 @item  @code{EXPORT_VALUED_PROCEDURE}
25918
25919 @item  @code{FLOAT_REPRESENTATION}
25920
25921 @item  @code{IDENT}
25922
25923 @item  @code{IMPORT_EXCEPTION}
25924
25925 @item  @code{IMPORT_FUNCTION}
25926
25927 @item  @code{IMPORT_OBJECT}
25928
25929 @item  @code{IMPORT_PROCEDURE}
25930
25931 @item  @code{IMPORT_VALUED_PROCEDURE}
25932
25933 @item  @code{INLINE_GENERIC}
25934
25935 @item  @code{INTERFACE_NAME}
25936
25937 @item  @code{LONG_FLOAT}
25938
25939 @item  @code{MAIN_STORAGE}
25940
25941 @item  @code{PASSIVE}
25942
25943 @item  @code{PSECT_OBJECT}
25944
25945 @item  @code{SHARE_GENERIC}
25946
25947 @item  @code{SUPPRESS_ALL}
25948
25949 @item  @code{TASK_STORAGE}
25950
25951 @item  @code{TIME_SLICE}
25952
25953 @item  @code{TITLE}
25954 @end itemize
25955
25956 @noindent
25957 These pragmas are all fully implemented, with the exception of @code{TITLE},
25958 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25959 recognized, but which have no
25960 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25961 use of Ada protected objects. In GNAT, all generics are inlined.
25962
25963 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25964 a separate subprogram specification which must appear before the
25965 subprogram body.
25966
25967 GNAT also supplies a number of implementation-defined pragmas as follows:
25968 @itemize @bullet
25969 @item  @code{ABORT_DEFER}
25970
25971 @item  @code{ADA_83}
25972
25973 @item  @code{ADA_95}
25974
25975 @item  @code{ADA_05}
25976
25977 @item  @code{ANNOTATE}
25978
25979 @item  @code{ASSERT}
25980
25981 @item  @code{C_PASS_BY_COPY}
25982
25983 @item  @code{CPP_CLASS}
25984
25985 @item  @code{CPP_CONSTRUCTOR}
25986
25987 @item  @code{CPP_DESTRUCTOR}
25988
25989 @item  @code{DEBUG}
25990
25991 @item  @code{EXTEND_SYSTEM}
25992
25993 @item  @code{LINKER_ALIAS}
25994
25995 @item  @code{LINKER_SECTION}
25996
25997 @item  @code{MACHINE_ATTRIBUTE}
25998
25999 @item  @code{NO_RETURN}
26000
26001 @item  @code{PURE_FUNCTION}
26002
26003 @item  @code{SOURCE_FILE_NAME}
26004
26005 @item  @code{SOURCE_REFERENCE}
26006
26007 @item  @code{TASK_INFO}
26008
26009 @item  @code{UNCHECKED_UNION}
26010
26011 @item  @code{UNIMPLEMENTED_UNIT}
26012
26013 @item  @code{UNIVERSAL_DATA}
26014
26015 @item  @code{UNSUPPRESS}
26016
26017 @item  @code{WARNINGS}
26018
26019 @item  @code{WEAK_EXTERNAL}
26020 @end itemize
26021
26022 @noindent
26023 For full details on these GNAT implementation-defined pragmas,
26024 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
26025 Manual}.
26026
26027 @menu
26028 * Restrictions on the Pragma INLINE::
26029 * Restrictions on the Pragma INTERFACE::
26030 * Restrictions on the Pragma SYSTEM_NAME::
26031 @end menu
26032
26033 @node Restrictions on the Pragma INLINE
26034 @subsection Restrictions on Pragma @code{INLINE}
26035
26036 @noindent
26037 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
26038 @itemize @bullet
26039 @item  Parameters cannot have a task type.
26040
26041 @item  Function results cannot be task types, unconstrained
26042 array types, or unconstrained types with discriminants.
26043
26044 @item  Bodies cannot declare the following:
26045 @itemize @bullet
26046 @item  Subprogram body or stub (imported subprogram is allowed)
26047
26048 @item  Tasks
26049
26050 @item  Generic declarations
26051
26052 @item  Instantiations
26053
26054 @item  Exceptions
26055
26056 @item  Access types (types derived from access types allowed)
26057
26058 @item  Array or record types
26059
26060 @item  Dependent tasks
26061
26062 @item  Direct recursive calls of subprogram or containing
26063 subprogram, directly or via a renaming
26064
26065 @end itemize
26066 @end itemize
26067
26068 @noindent
26069 In GNAT, the only restriction on pragma @code{INLINE} is that the
26070 body must occur before the call if both are in the same
26071 unit, and the size must be appropriately small. There are
26072 no other specific restrictions which cause subprograms to
26073 be incapable of being inlined.
26074
26075 @node  Restrictions on the Pragma INTERFACE
26076 @subsection  Restrictions on Pragma @code{INTERFACE}
26077
26078 @noindent
26079 The following restrictions on pragma @code{INTERFACE}
26080 are enforced by both HP Ada and GNAT:
26081 @itemize @bullet
26082 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
26083 Default is the default on OpenVMS Alpha systems.
26084
26085 @item  Parameter passing: Language specifies default
26086 mechanisms but can be overridden with an @code{EXPORT} pragma.
26087
26088 @itemize @bullet
26089 @item  Ada: Use internal Ada rules.
26090
26091 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
26092 record or task type. Result cannot be a string, an
26093 array, or a record.
26094
26095 @item  Fortran: Parameters cannot have a task type. Result cannot
26096 be a string, an array, or a record.
26097 @end itemize
26098 @end itemize
26099
26100 @noindent
26101 GNAT is entirely upwards compatible with HP Ada, and in addition allows
26102 record parameters for all languages.
26103
26104 @node  Restrictions on the Pragma SYSTEM_NAME
26105 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
26106
26107 @noindent
26108 For HP Ada for OpenVMS Alpha, the enumeration literal
26109 for the type @code{NAME} is @code{OPENVMS_AXP}.
26110 In GNAT, the enumeration
26111 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
26112
26113 @node  Library of Predefined Units
26114 @section  Library of Predefined Units
26115
26116 @noindent
26117 A library of predefined units is provided as part of the
26118 HP Ada and GNAT implementations. HP Ada does not provide
26119 the package @code{MACHINE_CODE} but instead recommends importing
26120 assembler code.
26121
26122 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
26123 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
26124 version.
26125 The HP Ada Predefined Library units are modified to remove post-Ada 83
26126 incompatibilities and to make them interoperable with GNAT
26127 (@pxref{Changes to DECLIB}, for details).
26128 The units are located in the @file{DECLIB} directory.
26129
26130 The GNAT RTL is contained in
26131 the @file{ADALIB} directory, and
26132 the default search path is set up to find @code{DECLIB} units in preference
26133 to @code{ADALIB} units with the same name (@code{TEXT_IO},
26134 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
26135
26136 @menu
26137 * Changes to DECLIB::
26138 @end menu
26139
26140 @node Changes to DECLIB
26141 @subsection Changes to @code{DECLIB}
26142
26143 @noindent
26144 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
26145 compatibility are minor and include the following:
26146
26147 @itemize @bullet
26148 @item  Adjusting the location of pragmas and record representation
26149 clauses to obey Ada 95 (and thus Ada 2005) rules
26150
26151 @item  Adding the proper notation to generic formal parameters
26152 that take unconstrained types in instantiation
26153
26154 @item  Adding pragma @code{ELABORATE_BODY} to package specs
26155 that have package bodies not otherwise allowed
26156
26157 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
26158 ``@code{PROTECTD}''.
26159 Currently these are found only in the @code{STARLET} package spec.
26160
26161 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
26162 where the address size is constrained to 32 bits.
26163 @end itemize
26164
26165 @noindent
26166 None of the above changes is visible to users.
26167
26168 @node Bindings
26169 @section Bindings
26170
26171 @noindent
26172 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
26173 @itemize @bullet
26174
26175 @item  Command Language Interpreter (CLI interface)
26176
26177 @item  DECtalk Run-Time Library (DTK interface)
26178
26179 @item  Librarian utility routines (LBR interface)
26180
26181 @item  General Purpose Run-Time Library (LIB interface)
26182
26183 @item  Math Run-Time Library (MTH interface)
26184
26185 @item  National Character Set Run-Time Library (NCS interface)
26186
26187 @item  Compiled Code Support Run-Time Library (OTS interface)
26188
26189 @item  Parallel Processing Run-Time Library (PPL interface)
26190
26191 @item  Screen Management Run-Time Library (SMG interface)
26192
26193 @item  Sort Run-Time Library (SOR interface)
26194
26195 @item  String Run-Time Library (STR interface)
26196
26197 @item STARLET System Library
26198 @findex Starlet
26199
26200 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
26201
26202 @item  X Windows Toolkit (XT interface)
26203
26204 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
26205 @end itemize
26206
26207 @noindent
26208 GNAT provides implementations of these HP bindings in the @code{DECLIB}
26209 directory, on both the Alpha and I64 OpenVMS platforms.
26210
26211 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
26212 in the
26213 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
26214 A pragma @code{Linker_Options} has been added to packages @code{Xm},
26215 @code{Xt}, and @code{X_Lib}
26216 causing the default X/Motif sharable image libraries to be linked in. This
26217 is done via options files named @file{xm.opt}, @file{xt.opt}, and
26218 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
26219
26220 It may be necessary to edit these options files to update or correct the
26221 library names if, for example, the newer X/Motif bindings from
26222 @file{ADA$EXAMPLES}
26223 had been (previous to installing GNAT) copied and renamed to supersede the
26224 default @file{ADA$PREDEFINED} versions.
26225
26226 @menu
26227 * Shared Libraries and Options Files::
26228 * Interfaces to C::
26229 @end menu
26230
26231 @node Shared Libraries and Options Files
26232 @subsection Shared Libraries and Options Files
26233
26234 @noindent
26235 When using the HP Ada
26236 predefined X and Motif bindings, the linking with their sharable images is
26237 done automatically by @command{GNAT LINK}.
26238 When using other X and Motif bindings, you need
26239 to add the corresponding sharable images to the command line for
26240 @code{GNAT LINK}. When linking with shared libraries, or with
26241 @file{.OPT} files, you must
26242 also add them to the command line for @command{GNAT LINK}.
26243
26244 A shared library to be used with GNAT is built in the same way as other
26245 libraries under VMS. The VMS Link command can be used in standard fashion.
26246
26247 @node Interfaces to C
26248 @subsection Interfaces to C
26249
26250 @noindent
26251 HP Ada
26252 provides the following Ada types and operations:
26253
26254 @itemize @bullet
26255 @item C types package (@code{C_TYPES})
26256
26257 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26258
26259 @item Other_types (@code{SHORT_INT})
26260 @end itemize
26261
26262 @noindent
26263 Interfacing to C with GNAT, you can use the above approach
26264 described for HP Ada or the facilities of Annex B of
26265 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26266 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26267 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26268
26269 The @option{-gnatF} qualifier forces default and explicit
26270 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26271 to be uppercased for compatibility with the default behavior
26272 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26273
26274 @node Main Program Definition
26275 @section Main Program Definition
26276
26277 @noindent
26278 The following section discusses differences in the
26279 definition of main programs on HP Ada and GNAT.
26280 On HP Ada, main programs are defined to meet the
26281 following conditions:
26282 @itemize @bullet
26283 @item  Procedure with no formal parameters (returns @code{0} upon
26284 normal completion)
26285
26286 @item  Procedure with no formal parameters (returns @code{42} when
26287 an unhandled exception is raised)
26288
26289 @item  Function with no formal parameters whose returned value
26290 is of a discrete type
26291
26292 @item  Procedure with one @code{out} formal of a discrete type for
26293 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26294
26295 @end itemize
26296
26297 @noindent
26298 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26299 a main function or main procedure returns a discrete
26300 value whose size is less than 64 bits (32 on VAX systems),
26301 the value is zero- or sign-extended as appropriate.
26302 On GNAT, main programs are defined as follows:
26303 @itemize @bullet
26304 @item  Must be a non-generic, parameterless subprogram that
26305 is either a procedure or function returning an Ada
26306 @code{STANDARD.INTEGER} (the predefined type)
26307
26308 @item  Cannot be a generic subprogram or an instantiation of a
26309 generic subprogram
26310 @end itemize
26311
26312 @node Implementation-Defined Attributes
26313 @section Implementation-Defined Attributes
26314
26315 @noindent
26316 GNAT provides all HP Ada implementation-defined
26317 attributes.
26318
26319 @node Compiler and Run-Time Interfacing
26320 @section Compiler and Run-Time Interfacing
26321
26322 @noindent
26323 HP Ada provides the following qualifiers to pass options to the linker
26324 (ACS LINK):
26325 @itemize @bullet
26326 @item  @option{/WAIT} and @option{/SUBMIT}
26327
26328 @item  @option{/COMMAND}
26329
26330 @item  @option{/@r{[}NO@r{]}MAP}
26331
26332 @item  @option{/OUTPUT=@var{file-spec}}
26333
26334 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26335 @end itemize
26336
26337 @noindent
26338 To pass options to the linker, GNAT provides the following
26339 switches:
26340
26341 @itemize @bullet
26342 @item   @option{/EXECUTABLE=@var{exec-name}}
26343
26344 @item   @option{/VERBOSE}
26345
26346 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26347 @end itemize
26348
26349 @noindent
26350 For more information on these switches, see
26351 @ref{Switches for gnatlink}.
26352 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26353 to control optimization. HP Ada also supplies the
26354 following pragmas:
26355 @itemize @bullet
26356 @item  @code{OPTIMIZE}
26357
26358 @item  @code{INLINE}
26359
26360 @item  @code{INLINE_GENERIC}
26361
26362 @item  @code{SUPPRESS_ALL}
26363
26364 @item  @code{PASSIVE}
26365 @end itemize
26366
26367 @noindent
26368 In GNAT, optimization is controlled strictly by command
26369 line parameters, as described in the corresponding section of this guide.
26370 The HP pragmas for control of optimization are
26371 recognized but ignored.
26372
26373 Note that in GNAT, the default is optimization off, whereas in HP Ada
26374 the default is that optimization is turned on.
26375
26376 @node Program Compilation and Library Management
26377 @section Program Compilation and Library Management
26378
26379 @noindent
26380 HP Ada and GNAT provide a comparable set of commands to
26381 build programs. HP Ada also provides a program library,
26382 which is a concept that does not exist on GNAT. Instead,
26383 GNAT provides directories of sources that are compiled as
26384 needed.
26385
26386 The following table summarizes
26387 the HP Ada commands and provides
26388 equivalent GNAT commands. In this table, some GNAT
26389 equivalents reflect the fact that GNAT does not use the
26390 concept of a program library. Instead, it uses a model
26391 in which collections of source and object files are used
26392 in a manner consistent with other languages like C and
26393 Fortran. Therefore, standard system file commands are used
26394 to manipulate these elements. Those GNAT commands are marked with
26395 an asterisk.
26396 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26397
26398 @need 1500
26399 @multitable @columnfractions .35 .65
26400
26401 @item @emph{HP Ada Command}
26402 @tab @emph{GNAT Equivalent / Description}
26403
26404 @item @command{ADA}
26405 @tab @command{GNAT COMPILE}@*
26406 Invokes the compiler to compile one or more Ada source files.
26407
26408 @item @command{ACS ATTACH}@*
26409 @tab [No equivalent]@*
26410 Switches control of terminal from current process running the program
26411 library manager.
26412
26413 @item @command{ACS CHECK}
26414 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26415 Forms the execution closure of one
26416 or more compiled units and checks completeness and currency.
26417
26418 @item @command{ACS COMPILE}
26419 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26420 Forms the execution closure of one or
26421 more specified units, checks completeness and currency,
26422 identifies units that have revised source files, compiles same,
26423 and recompiles units that are or will become obsolete.
26424 Also completes incomplete generic instantiations.
26425
26426 @item @command{ACS COPY FOREIGN}
26427 @tab Copy (*)@*
26428 Copies a foreign object file into the program library as a
26429 library unit body.
26430
26431 @item @command{ACS COPY UNIT}
26432 @tab Copy (*)@*
26433 Copies a compiled unit from one program library to another.
26434
26435 @item @command{ACS CREATE LIBRARY}
26436 @tab Create /directory (*)@*
26437 Creates a program library.
26438
26439 @item @command{ACS CREATE SUBLIBRARY}
26440 @tab Create /directory (*)@*
26441 Creates a program sublibrary.
26442
26443 @item @command{ACS DELETE LIBRARY}
26444 @tab @*
26445 Deletes a program library and its contents.
26446
26447 @item @command{ACS DELETE SUBLIBRARY}
26448 @tab @*
26449 Deletes a program sublibrary and its contents.
26450
26451 @item @command{ACS DELETE UNIT}
26452 @tab Delete file (*)@*
26453 On OpenVMS systems, deletes one or more compiled units from
26454 the current program library.
26455
26456 @item @command{ACS DIRECTORY}
26457 @tab Directory (*)@*
26458 On OpenVMS systems, lists units contained in the current
26459 program library.
26460
26461 @item @command{ACS ENTER FOREIGN}
26462 @tab Copy (*)@*
26463 Allows the import of a foreign body as an Ada library
26464 spec and enters a reference to a pointer.
26465
26466 @item @command{ACS ENTER UNIT}
26467 @tab Copy (*)@*
26468 Enters a reference (pointer) from the current program library to
26469 a unit compiled into another program library.
26470
26471 @item @command{ACS EXIT}
26472 @tab [No equivalent]@*
26473 Exits from the program library manager.
26474
26475 @item @command{ACS EXPORT}
26476 @tab Copy (*)@*
26477 Creates an object file that contains system-specific object code
26478 for one or more units. With GNAT, object files can simply be copied
26479 into the desired directory.
26480
26481 @item @command{ACS EXTRACT SOURCE}
26482 @tab Copy (*)@*
26483 Allows access to the copied source file for each Ada compilation unit
26484
26485 @item @command{ACS HELP}
26486 @tab @command{HELP GNAT}@*
26487 Provides online help.
26488
26489 @item @command{ACS LINK}
26490 @tab @command{GNAT LINK}@*
26491 Links an object file containing Ada units into an executable file.
26492
26493 @item @command{ACS LOAD}
26494 @tab Copy (*)@*
26495 Loads (partially compiles) Ada units into the program library.
26496 Allows loading a program from a collection of files into a library
26497 without knowing the relationship among units.
26498
26499 @item @command{ACS MERGE}
26500 @tab Copy (*)@*
26501 Merges into the current program library, one or more units from
26502 another library where they were modified.
26503
26504 @item @command{ACS RECOMPILE}
26505 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26506 Recompiles from   external or copied source files any obsolete
26507 unit in the closure. Also, completes any incomplete generic
26508 instantiations.
26509
26510 @item @command{ACS REENTER}
26511 @tab @command{GNAT MAKE}@*
26512 Reenters current references to units compiled after last entered
26513 with the @command{ACS ENTER UNIT} command.
26514
26515 @item @command{ACS SET LIBRARY}
26516 @tab Set default (*)@*
26517 Defines a program library to be the compilation context as well
26518 as the target library for compiler output and commands in general.
26519
26520 @item @command{ACS SET PRAGMA}
26521 @tab Edit @file{gnat.adc} (*)@*
26522 Redefines specified  values of the library characteristics
26523 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26524 and @code{Float_Representation}.
26525
26526 @item @command{ACS SET SOURCE}
26527 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26528 Defines the source file search list for the @command{ACS COMPILE} command.
26529
26530 @item @command{ACS SHOW LIBRARY}
26531 @tab Directory (*)@*
26532 Lists information about one or more program libraries.
26533
26534 @item @command{ACS SHOW PROGRAM}
26535 @tab [No equivalent]@*
26536 Lists information about the execution closure of one or
26537 more units in the program library.
26538
26539 @item @command{ACS SHOW SOURCE}
26540 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26541 Shows the source file search used when compiling units.
26542
26543 @item @command{ACS SHOW VERSION}
26544 @tab Compile with @option{VERBOSE} option
26545 Displays the version number of the compiler and program library
26546 manager used.
26547
26548 @item @command{ACS SPAWN}
26549 @tab [No equivalent]@*
26550 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26551 command).
26552
26553 @item @command{ACS VERIFY}
26554 @tab [No equivalent]@*
26555 Performs a series of consistency checks on a program library to
26556 determine whether the library structure and library files are in
26557 valid form.
26558 @end multitable
26559
26560 @noindent
26561
26562 @node Input-Output
26563 @section Input-Output
26564
26565 @noindent
26566 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26567 Management Services (RMS) to perform operations on
26568 external files.
26569
26570 @noindent
26571 HP Ada and GNAT predefine an identical set of input-
26572 output packages. To make the use of the
26573 generic @code{TEXT_IO} operations more convenient, HP Ada
26574 provides predefined library packages that instantiate the
26575 integer and floating-point operations for the predefined
26576 integer and floating-point types as shown in the following table.
26577
26578 @multitable @columnfractions .45 .55
26579 @item @emph{Package Name} @tab Instantiation
26580
26581 @item @code{INTEGER_TEXT_IO}
26582 @tab @code{INTEGER_IO(INTEGER)}
26583
26584 @item @code{SHORT_INTEGER_TEXT_IO}
26585 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26586
26587 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26588 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26589
26590 @item @code{FLOAT_TEXT_IO}
26591 @tab @code{FLOAT_IO(FLOAT)}
26592
26593 @item @code{LONG_FLOAT_TEXT_IO}
26594 @tab @code{FLOAT_IO(LONG_FLOAT)}
26595 @end multitable
26596
26597 @noindent
26598 The HP Ada predefined packages and their operations
26599 are implemented using OpenVMS Alpha files and input-output
26600 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26601 Familiarity with the following is recommended:
26602 @itemize @bullet
26603 @item  RMS file organizations and access methods
26604
26605 @item  OpenVMS file specifications and directories
26606
26607 @item  OpenVMS File Definition Language (FDL)
26608 @end itemize
26609
26610 @noindent
26611 GNAT provides I/O facilities that are completely
26612 compatible with HP Ada. The distribution includes the
26613 standard HP Ada versions of all I/O packages, operating
26614 in a manner compatible with HP Ada. In particular, the
26615 following packages are by default the HP Ada (Ada 83)
26616 versions of these packages rather than the renamings
26617 suggested in Annex J of the Ada Reference Manual:
26618 @itemize @bullet
26619 @item  @code{TEXT_IO}
26620
26621 @item  @code{SEQUENTIAL_IO}
26622
26623 @item  @code{DIRECT_IO}
26624 @end itemize
26625
26626 @noindent
26627 The use of the standard child package syntax (for
26628 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26629 packages.
26630 GNAT provides HP-compatible predefined instantiations
26631 of the @code{TEXT_IO} packages, and also
26632 provides the standard predefined instantiations required
26633 by the @cite{Ada Reference Manual}.
26634
26635 For further information on how GNAT interfaces to the file
26636 system or how I/O is implemented in programs written in
26637 mixed languages, see @ref{Implementation of the Standard I/O,,,
26638 gnat_rm, GNAT Reference Manual}.
26639 This chapter covers the following:
26640 @itemize @bullet
26641 @item  Standard I/O packages
26642
26643 @item  @code{FORM} strings
26644
26645 @item  @code{ADA.DIRECT_IO}
26646
26647 @item  @code{ADA.SEQUENTIAL_IO}
26648
26649 @item  @code{ADA.TEXT_IO}
26650
26651 @item  Stream pointer positioning
26652
26653 @item  Reading and writing non-regular files
26654
26655 @item  @code{GET_IMMEDIATE}
26656
26657 @item  Treating @code{TEXT_IO} files as streams
26658
26659 @item  Shared files
26660
26661 @item  Open modes
26662 @end itemize
26663
26664 @node Implementation Limits
26665 @section Implementation Limits
26666
26667 @noindent
26668 The following table lists implementation limits for HP Ada
26669 and GNAT systems.
26670 @multitable @columnfractions .60 .20 .20
26671 @sp 1
26672 @item  @emph{Compilation Parameter}
26673 @tab   @emph{HP Ada}
26674 @tab   @emph{GNAT}
26675 @sp 1
26676
26677 @item  In a subprogram or entry  declaration, maximum number of
26678 formal parameters that are of an unconstrained record type
26679 @tab   32
26680 @tab   No set limit
26681 @sp 1
26682
26683 @item  Maximum identifier length (number of characters)
26684 @tab   255
26685 @tab   32766
26686 @sp 1
26687
26688 @item  Maximum number of characters in a source line
26689 @tab   255
26690 @tab   32766
26691 @sp 1
26692
26693 @item  Maximum collection size   (number of bytes)
26694 @tab   2**31-1
26695 @tab   2**31-1
26696 @sp 1
26697
26698 @item  Maximum number of discriminants for a record type
26699 @tab   245
26700 @tab   No set limit
26701 @sp 1
26702
26703 @item  Maximum number of formal parameters in an entry or
26704 subprogram declaration
26705 @tab   246
26706 @tab    No set limit
26707 @sp 1
26708
26709 @item  Maximum number of dimensions in an array type
26710 @tab   255
26711 @tab   No set limit
26712 @sp 1
26713
26714 @item  Maximum number of library  units and subunits in a compilation.
26715 @tab   4095
26716 @tab   No set limit
26717 @sp 1
26718
26719 @item  Maximum number of library units and subunits in an execution.
26720 @tab   16383
26721 @tab   No set limit
26722 @sp 1
26723
26724 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26725 or @code{PSECT_OBJECT}
26726 @tab   32757
26727 @tab   No set limit
26728 @sp 1
26729
26730 @item  Maximum number of enumeration literals in an enumeration type
26731 definition
26732 @tab   65535
26733 @tab   No set limit
26734 @sp 1
26735
26736 @item  Maximum number of lines in a source file
26737 @tab   65534
26738 @tab   No set limit
26739 @sp 1
26740
26741 @item  Maximum number of bits in any object
26742 @tab   2**31-1
26743 @tab   2**31-1
26744 @sp 1
26745
26746 @item  Maximum size of the static portion of a stack frame (approximate)
26747 @tab   2**31-1
26748 @tab   2**31-1
26749 @end multitable
26750
26751 @node Tools and Utilities
26752 @section Tools and Utilities
26753
26754 @noindent
26755 The following table lists some of the OpenVMS development tools
26756 available for HP Ada, and the corresponding tools for
26757 use with @value{EDITION} on Alpha and I64 platforms.
26758 Aside from the debugger, all the OpenVMS tools identified are part
26759 of the DECset package.
26760
26761 @iftex
26762 @c Specify table in TeX since Texinfo does a poor job
26763 @tex
26764 \smallskip
26765 \smallskip
26766 \settabs\+Language-Sensitive Editor\quad
26767    &Product with HP Ada\quad
26768    &\cr
26769 \+\it Tool
26770    &\it Product with HP Ada
26771    & \it Product with GNAT Pro\cr
26772 \smallskip
26773 \+Code Management System
26774    &HP CMS
26775    & HP CMS\cr
26776 \smallskip
26777 \+Language-Sensitive Editor
26778    &HP LSE
26779    & emacs or HP LSE (Alpha)\cr
26780 \+
26781    &
26782    & HP LSE (I64)\cr
26783 \smallskip
26784 \+Debugger
26785    &OpenVMS Debug
26786    & gdb (Alpha),\cr
26787 \+
26788    &
26789    & OpenVMS Debug (I64)\cr
26790 \smallskip
26791 \+Source Code Analyzer /
26792    &HP SCA
26793    & GNAT XREF\cr
26794 \+Cross Referencer
26795    &
26796    &\cr
26797 \smallskip
26798 \+Test Manager
26799    &HP Digital Test
26800    & HP DTM\cr
26801 \+
26802    &Manager (DTM)
26803    &\cr
26804 \smallskip
26805 \+Performance and
26806    & HP PCA
26807    & HP PCA\cr
26808 \+Coverage Analyzer
26809    &
26810    &\cr
26811 \smallskip
26812 \+Module Management
26813    & HP MMS
26814    & Not applicable\cr
26815 \+ System
26816    &
26817    &\cr
26818 \smallskip
26819 \smallskip
26820 @end tex
26821 @end iftex
26822
26823 @ifnottex
26824 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26825 @c the TeX version above for the printed version
26826 @flushleft
26827 @c @multitable @columnfractions .3 .4 .4
26828 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26829 @item @i{Tool}
26830 @tab @i{Tool with HP Ada}
26831 @tab @i{Tool with @value{EDITION}}
26832 @item Code Management@*System
26833 @tab HP CMS
26834 @tab HP CMS
26835 @item Language-Sensitive@*Editor
26836 @tab HP LSE
26837 @tab emacs or HP LSE (Alpha)
26838 @item
26839 @tab
26840 @tab HP LSE (I64)
26841 @item Debugger
26842 @tab OpenVMS Debug
26843 @tab gdb (Alpha),
26844 @item
26845 @tab
26846 @tab OpenVMS Debug (I64)
26847 @item Source Code Analyzer /@*Cross Referencer
26848 @tab HP SCA
26849 @tab GNAT XREF
26850 @item Test Manager
26851 @tab HP Digital Test@*Manager (DTM)
26852 @tab HP DTM
26853 @item Performance and@*Coverage Analyzer
26854 @tab HP PCA
26855 @tab HP PCA
26856 @item Module Management@*System
26857 @tab HP MMS
26858 @tab Not applicable
26859 @end multitable
26860 @end flushleft
26861 @end ifnottex
26862
26863 @end ifset
26864
26865 @c **************************************
26866 @node Platform-Specific Information for the Run-Time Libraries
26867 @appendix Platform-Specific Information for the Run-Time Libraries
26868 @cindex Tasking and threads libraries
26869 @cindex Threads libraries and tasking
26870 @cindex Run-time libraries (platform-specific information)
26871
26872 @noindent
26873 The GNAT run-time implementation may vary with respect to both the
26874 underlying threads library and the exception handling scheme.
26875 For threads support, one or more of the following are supplied:
26876 @itemize @bullet
26877 @item @b{native threads library}, a binding to the thread package from
26878 the underlying operating system
26879
26880 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26881 POSIX thread package
26882 @end itemize
26883
26884 @noindent
26885 For exception handling, either or both of two models are supplied:
26886 @itemize @bullet
26887 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26888 Most programs should experience a substantial speed improvement by
26889 being compiled with a ZCX run-time.
26890 This is especially true for
26891 tasking applications or applications with many exception handlers.}
26892 @cindex Zero-Cost Exceptions
26893 @cindex ZCX (Zero-Cost Exceptions)
26894 which uses binder-generated tables that
26895 are interrogated at run time to locate a handler
26896
26897 @item @b{setjmp / longjmp} (``SJLJ''),
26898 @cindex setjmp/longjmp Exception Model
26899 @cindex SJLJ (setjmp/longjmp Exception Model)
26900 which uses dynamically-set data to establish
26901 the set of handlers
26902 @end itemize
26903
26904 @noindent
26905 This appendix summarizes which combinations of threads and exception support
26906 are supplied on various GNAT platforms.
26907 It then shows how to select a particular library either
26908 permanently or temporarily,
26909 explains the properties of (and tradeoffs among) the various threads
26910 libraries, and provides some additional
26911 information about several specific platforms.
26912
26913 @menu
26914 * Summary of Run-Time Configurations::
26915 * Specifying a Run-Time Library::
26916 * Choosing the Scheduling Policy::
26917 * Solaris-Specific Considerations::
26918 * Linux-Specific Considerations::
26919 * AIX-Specific Considerations::
26920 * Irix-Specific Considerations::
26921 * RTX-Specific Considerations::
26922 @end menu
26923
26924 @node Summary of Run-Time Configurations
26925 @section Summary of Run-Time Configurations
26926
26927 @multitable @columnfractions .30 .70
26928 @item @b{alpha-openvms}
26929 @item @code{@ @ }@i{rts-native (default)}
26930 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26931 @item @code{@ @ @ @ }Exceptions @tab ZCX
26932 @*
26933 @item @b{alpha-tru64}
26934 @item @code{@ @ }@i{rts-native (default)}
26935 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26936 @item @code{@ @ @ @ }Exceptions @tab ZCX
26937 @*
26938 @item @code{@ @ }@i{rts-sjlj}
26939 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26940 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26941 @*
26942 @item @b{ia64-hp_linux}
26943 @item @code{@ @ }@i{rts-native (default)}
26944 @item @code{@ @ @ @ }Tasking    @tab pthread library
26945 @item @code{@ @ @ @ }Exceptions @tab ZCX
26946 @*
26947 @item @b{ia64-hpux}
26948 @item @code{@ @ }@i{rts-native (default)}
26949 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26950 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26951 @*
26952 @item @b{ia64-openvms}
26953 @item @code{@ @ }@i{rts-native (default)}
26954 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26955 @item @code{@ @ @ @ }Exceptions @tab ZCX
26956 @*
26957 @item @b{ia64-sgi_linux}
26958 @item @code{@ @ }@i{rts-native (default)}
26959 @item @code{@ @ @ @ }Tasking    @tab pthread library
26960 @item @code{@ @ @ @ }Exceptions @tab ZCX
26961 @*
26962 @item @b{mips-irix}
26963 @item @code{@ @ }@i{rts-native (default)}
26964 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26965 @item @code{@ @ @ @ }Exceptions @tab ZCX
26966 @*
26967 @item @b{pa-hpux}
26968 @item @code{@ @ }@i{rts-native (default)}
26969 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26970 @item @code{@ @ @ @ }Exceptions @tab ZCX
26971 @*
26972 @item @code{@ @ }@i{rts-sjlj}
26973 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26974 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26975 @*
26976 @item @b{ppc-aix}
26977 @item @code{@ @ }@i{rts-native (default)}
26978 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26979 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26980 @*
26981 @item @b{ppc-darwin}
26982 @item @code{@ @ }@i{rts-native (default)}
26983 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26984 @item @code{@ @ @ @ }Exceptions @tab ZCX
26985 @*
26986 @item @b{sparc-solaris}  @tab
26987 @item @code{@ @ }@i{rts-native (default)}
26988 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26989 @item @code{@ @ @ @ }Exceptions @tab ZCX
26990 @*
26991 @item @code{@ @ }@i{rts-pthread}
26992 @item @code{@ @ @ @ }Tasking    @tab pthread library
26993 @item @code{@ @ @ @ }Exceptions @tab ZCX
26994 @*
26995 @item @code{@ @ }@i{rts-sjlj}
26996 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26997 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26998 @*
26999 @item @b{sparc64-solaris}  @tab
27000 @item @code{@ @ }@i{rts-native (default)}
27001 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27002 @item @code{@ @ @ @ }Exceptions @tab ZCX
27003 @*
27004 @item @b{x86-linux}
27005 @item @code{@ @ }@i{rts-native (default)}
27006 @item @code{@ @ @ @ }Tasking    @tab pthread library
27007 @item @code{@ @ @ @ }Exceptions @tab ZCX
27008 @*
27009 @item @code{@ @ }@i{rts-sjlj}
27010 @item @code{@ @ @ @ }Tasking    @tab pthread library
27011 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27012 @*
27013 @item @b{x86-lynx}
27014 @item @code{@ @ }@i{rts-native (default)}
27015 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
27016 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27017 @*
27018 @item @b{x86-solaris}
27019 @item @code{@ @ }@i{rts-native (default)}
27020 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
27021 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27022 @*
27023 @item @b{x86-windows}
27024 @item @code{@ @ }@i{rts-native (default)}
27025 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27026 @item @code{@ @ @ @ }Exceptions @tab ZCX
27027 @*
27028 @item @code{@ @ }@i{rts-sjlj (default)}
27029 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27030 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27031 @*
27032 @item @b{x86-windows-rtx}
27033 @item @code{@ @ }@i{rts-rtx-rtss (default)}
27034 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
27035 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27036 @*
27037 @item @code{@ @ }@i{rts-rtx-w32}
27038 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
27039 @item @code{@ @ @ @ }Exceptions @tab ZCX
27040 @*
27041 @item @b{x86_64-linux}
27042 @item @code{@ @ }@i{rts-native (default)}
27043 @item @code{@ @ @ @ }Tasking    @tab pthread library
27044 @item @code{@ @ @ @ }Exceptions @tab ZCX
27045 @*
27046 @item @code{@ @ }@i{rts-sjlj}
27047 @item @code{@ @ @ @ }Tasking    @tab pthread library
27048 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27049 @*
27050 @end multitable
27051
27052 @node Specifying a Run-Time Library
27053 @section Specifying a Run-Time Library
27054
27055 @noindent
27056 The @file{adainclude} subdirectory containing the sources of the GNAT
27057 run-time library, and the @file{adalib} subdirectory containing the
27058 @file{ALI} files and the static and/or shared GNAT library, are located
27059 in the gcc target-dependent area:
27060
27061 @smallexample
27062 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
27063 @end smallexample
27064
27065 @noindent
27066 As indicated above, on some platforms several run-time libraries are supplied.
27067 These libraries are installed in the target dependent area and
27068 contain a complete source and binary subdirectory. The detailed description
27069 below explains the differences between the different libraries in terms of
27070 their thread support.
27071
27072 The default run-time library (when GNAT is installed) is @emph{rts-native}.
27073 This default run time is selected by the means of soft links.
27074 For example on x86-linux:
27075
27076 @smallexample
27077 @group
27078  $(target-dir)
27079      |
27080      +--- adainclude----------+
27081      |                        |
27082      +--- adalib-----------+  |
27083      |                     |  |
27084      +--- rts-native       |  |
27085      |    |                |  |
27086      |    +--- adainclude <---+
27087      |    |                |
27088      |    +--- adalib <----+
27089      |
27090      +--- rts-sjlj
27091           |
27092           +--- adainclude
27093           |
27094           +--- adalib
27095 @end group
27096 @end smallexample
27097
27098 @noindent
27099 If the @i{rts-sjlj} library is to be selected on a permanent basis,
27100 these soft links can be modified with the following commands:
27101
27102 @smallexample
27103 $ cd $target
27104 $ rm -f adainclude adalib
27105 $ ln -s rts-sjlj/adainclude adainclude
27106 $ ln -s rts-sjlj/adalib adalib
27107 @end smallexample
27108
27109 @noindent
27110 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
27111 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
27112 @file{$target/ada_object_path}.
27113
27114 Selecting another run-time library temporarily can be
27115 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
27116 @cindex @option{--RTS} option
27117
27118 @node Choosing the Scheduling Policy
27119 @section Choosing the Scheduling Policy
27120
27121 @noindent
27122 When using a POSIX threads implementation, you have a choice of several
27123 scheduling policies: @code{SCHED_FIFO},
27124 @cindex @code{SCHED_FIFO} scheduling policy
27125 @code{SCHED_RR}
27126 @cindex @code{SCHED_RR} scheduling policy
27127 and @code{SCHED_OTHER}.
27128 @cindex @code{SCHED_OTHER} scheduling policy
27129 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
27130 or @code{SCHED_RR} requires special (e.g., root) privileges.
27131
27132 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
27133 @code{SCHED_FIFO},
27134 @cindex @code{SCHED_FIFO} scheduling policy
27135 you can use one of the following:
27136
27137 @itemize @bullet
27138 @item
27139 @code{pragma Time_Slice (0.0)}
27140 @cindex pragma Time_Slice
27141 @item
27142 the corresponding binder option @option{-T0}
27143 @cindex @option{-T0} option
27144 @item
27145 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27146 @cindex pragma Task_Dispatching_Policy
27147 @end itemize
27148
27149 @noindent
27150 To specify @code{SCHED_RR},
27151 @cindex @code{SCHED_RR} scheduling policy
27152 you should use @code{pragma Time_Slice} with a
27153 value greater than @code{0.0}, or else use the corresponding @option{-T}
27154 binder option.
27155
27156 @node Solaris-Specific Considerations
27157 @section Solaris-Specific Considerations
27158 @cindex Solaris Sparc threads libraries
27159
27160 @noindent
27161 This section addresses some topics related to the various threads libraries
27162 on Sparc Solaris.
27163
27164 @menu
27165 * Solaris Threads Issues::
27166 @end menu
27167
27168 @node Solaris Threads Issues
27169 @subsection Solaris Threads Issues
27170
27171 @noindent
27172 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
27173 library based on POSIX threads --- @emph{rts-pthread}.
27174 @cindex rts-pthread threads library
27175 This run-time library has the advantage of being mostly shared across all
27176 POSIX-compliant thread implementations, and it also provides under
27177 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
27178 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
27179 and @code{PTHREAD_PRIO_PROTECT}
27180 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
27181 semantics that can be selected using the predefined pragma
27182 @code{Locking_Policy}
27183 @cindex pragma Locking_Policy (under rts-pthread)
27184 with respectively
27185 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
27186 @cindex @code{Inheritance_Locking} (under rts-pthread)
27187 @cindex @code{Ceiling_Locking} (under rts-pthread)
27188
27189 As explained above, the native run-time library is based on the Solaris thread
27190 library (@code{libthread}) and is the default library.
27191
27192 When the Solaris threads library is used (this is the default), programs
27193 compiled with GNAT can automatically take advantage of
27194 and can thus execute on multiple processors.
27195 The user can alternatively specify a processor on which the program should run
27196 to emulate a single-processor system. The multiprocessor / uniprocessor choice
27197 is made by
27198 setting the environment variable @env{GNAT_PROCESSOR}
27199 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
27200 to one of the following:
27201
27202 @table @code
27203 @item -2
27204 Use the default configuration (run the program on all
27205 available processors) - this is the same as having @code{GNAT_PROCESSOR}
27206 unset
27207
27208 @item -1
27209 Let the run-time implementation choose one processor and run the program on
27210 that processor
27211
27212 @item 0 .. Last_Proc
27213 Run the program on the specified processor.
27214 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
27215 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
27216 @end table
27217
27218 @node Linux-Specific Considerations
27219 @section Linux-Specific Considerations
27220 @cindex Linux threads libraries
27221
27222 @noindent
27223 On GNU/Linux without NPTL support (usually system with GNU C Library
27224 older than 2.3), the signal model is not POSIX compliant, which means
27225 that to send a signal to the process, you need to send the signal to all
27226 threads, e.g.@: by using @code{killpg()}.
27227
27228 @node AIX-Specific Considerations
27229 @section AIX-Specific Considerations
27230 @cindex AIX resolver library
27231
27232 @noindent
27233 On AIX, the resolver library initializes some internal structure on
27234 the first call to @code{get*by*} functions, which are used to implement
27235 @code{GNAT.Sockets.Get_Host_By_Name} and
27236 @code{GNAT.Sockets.Get_Host_By_Address}.
27237 If such initialization occurs within an Ada task, and the stack size for
27238 the task is the default size, a stack overflow may occur.
27239
27240 To avoid this overflow, the user should either ensure that the first call
27241 to @code{GNAT.Sockets.Get_Host_By_Name} or
27242 @code{GNAT.Sockets.Get_Host_By_Addrss}
27243 occurs in the environment task, or use @code{pragma Storage_Size} to
27244 specify a sufficiently large size for the stack of the task that contains
27245 this call.
27246
27247 @node Irix-Specific Considerations
27248 @section Irix-Specific Considerations
27249 @cindex Irix libraries
27250
27251 @noindent
27252 The GCC support libraries coming with the Irix compiler have moved to
27253 their canonical place with respect to the general Irix ABI related
27254 conventions. Running applications built with the default shared GNAT
27255 run-time now requires the LD_LIBRARY_PATH environment variable to
27256 include this location. A possible way to achieve this is to issue the
27257 following command line on a bash prompt:
27258
27259 @smallexample
27260 @group
27261 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27262 @end group
27263 @end smallexample
27264
27265 @node RTX-Specific Considerations
27266 @section RTX-Specific Considerations
27267 @cindex RTX libraries
27268
27269 @noindent
27270 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27271 API. Applications can be built to work in two different modes:
27272
27273 @itemize @bullet
27274 @item
27275 Windows executables that run in Ring 3 to utilize memory protection
27276 (@emph{rts-rtx-w32}).
27277
27278 @item
27279 Real-time subsystem (RTSS) executables that run in Ring 0, where
27280 performance can be optimized with RTSS applications taking precedent
27281 over all Windows applications (@emph{rts-rtx-rtss}).
27282
27283 @end itemize
27284
27285 @c *******************************
27286 @node Example of Binder Output File
27287 @appendix Example of Binder Output File
27288
27289 @noindent
27290 This Appendix displays the source code for @command{gnatbind}'s output
27291 file generated for a simple ``Hello World'' program.
27292 Comments have been added for clarification purposes.
27293
27294 @smallexample @c adanocomment
27295 @iftex
27296 @leftskip=0cm
27297 @end iftex
27298 --  The package is called Ada_Main unless this name is actually used
27299 --  as a unit name in the partition, in which case some other unique
27300 --  name is used.
27301
27302 with System;
27303 package ada_main is
27304
27305    Elab_Final_Code : Integer;
27306    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27307
27308    --  The main program saves the parameters (argument count,
27309    --  argument values, environment pointer) in global variables
27310    --  for later access by other units including
27311    --  Ada.Command_Line.
27312
27313    gnat_argc : Integer;
27314    gnat_argv : System.Address;
27315    gnat_envp : System.Address;
27316
27317    --  The actual variables are stored in a library routine. This
27318    --  is useful for some shared library situations, where there
27319    --  are problems if variables are not in the library.
27320
27321    pragma Import (C, gnat_argc);
27322    pragma Import (C, gnat_argv);
27323    pragma Import (C, gnat_envp);
27324
27325    --  The exit status is similarly an external location
27326
27327    gnat_exit_status : Integer;
27328    pragma Import (C, gnat_exit_status);
27329
27330    GNAT_Version : constant String :=
27331                     "GNAT Version: 6.0.0w (20061115)";
27332    pragma Export (C, GNAT_Version, "__gnat_version");
27333
27334    --  This is the generated adafinal routine that performs
27335    --  finalization at the end of execution. In the case where
27336    --  Ada is the main program, this main program makes a call
27337    --  to adafinal at program termination.
27338
27339    procedure adafinal;
27340    pragma Export (C, adafinal, "adafinal");
27341
27342    --  This is the generated adainit routine that performs
27343    --  initialization at the start of execution. In the case
27344    --  where Ada is the main program, this main program makes
27345    --  a call to adainit at program startup.
27346
27347    procedure adainit;
27348    pragma Export (C, adainit, "adainit");
27349
27350    --  This routine is called at the start of execution. It is
27351    --  a dummy routine that is used by the debugger to breakpoint
27352    --  at the start of execution.
27353
27354    procedure Break_Start;
27355    pragma Import (C, Break_Start, "__gnat_break_start");
27356
27357    --  This is the actual generated main program (it would be
27358    --  suppressed if the no main program switch were used). As
27359    --  required by standard system conventions, this program has
27360    --  the external name main.
27361
27362    function main
27363      (argc : Integer;
27364       argv : System.Address;
27365       envp : System.Address)
27366       return Integer;
27367    pragma Export (C, main, "main");
27368
27369    --  The following set of constants give the version
27370    --  identification values for every unit in the bound
27371    --  partition. This identification is computed from all
27372    --  dependent semantic units, and corresponds to the
27373    --  string that would be returned by use of the
27374    --  Body_Version or Version attributes.
27375
27376    type Version_32 is mod 2 ** 32;
27377    u00001 : constant Version_32 := 16#7880BEB3#;
27378    u00002 : constant Version_32 := 16#0D24CBD0#;
27379    u00003 : constant Version_32 := 16#3283DBEB#;
27380    u00004 : constant Version_32 := 16#2359F9ED#;
27381    u00005 : constant Version_32 := 16#664FB847#;
27382    u00006 : constant Version_32 := 16#68E803DF#;
27383    u00007 : constant Version_32 := 16#5572E604#;
27384    u00008 : constant Version_32 := 16#46B173D8#;
27385    u00009 : constant Version_32 := 16#156A40CF#;
27386    u00010 : constant Version_32 := 16#033DABE0#;
27387    u00011 : constant Version_32 := 16#6AB38FEA#;
27388    u00012 : constant Version_32 := 16#22B6217D#;
27389    u00013 : constant Version_32 := 16#68A22947#;
27390    u00014 : constant Version_32 := 16#18CC4A56#;
27391    u00015 : constant Version_32 := 16#08258E1B#;
27392    u00016 : constant Version_32 := 16#367D5222#;
27393    u00017 : constant Version_32 := 16#20C9ECA4#;
27394    u00018 : constant Version_32 := 16#50D32CB6#;
27395    u00019 : constant Version_32 := 16#39A8BB77#;
27396    u00020 : constant Version_32 := 16#5CF8FA2B#;
27397    u00021 : constant Version_32 := 16#2F1EB794#;
27398    u00022 : constant Version_32 := 16#31AB6444#;
27399    u00023 : constant Version_32 := 16#1574B6E9#;
27400    u00024 : constant Version_32 := 16#5109C189#;
27401    u00025 : constant Version_32 := 16#56D770CD#;
27402    u00026 : constant Version_32 := 16#02F9DE3D#;
27403    u00027 : constant Version_32 := 16#08AB6B2C#;
27404    u00028 : constant Version_32 := 16#3FA37670#;
27405    u00029 : constant Version_32 := 16#476457A0#;
27406    u00030 : constant Version_32 := 16#731E1B6E#;
27407    u00031 : constant Version_32 := 16#23C2E789#;
27408    u00032 : constant Version_32 := 16#0F1BD6A1#;
27409    u00033 : constant Version_32 := 16#7C25DE96#;
27410    u00034 : constant Version_32 := 16#39ADFFA2#;
27411    u00035 : constant Version_32 := 16#571DE3E7#;
27412    u00036 : constant Version_32 := 16#5EB646AB#;
27413    u00037 : constant Version_32 := 16#4249379B#;
27414    u00038 : constant Version_32 := 16#0357E00A#;
27415    u00039 : constant Version_32 := 16#3784FB72#;
27416    u00040 : constant Version_32 := 16#2E723019#;
27417    u00041 : constant Version_32 := 16#623358EA#;
27418    u00042 : constant Version_32 := 16#107F9465#;
27419    u00043 : constant Version_32 := 16#6843F68A#;
27420    u00044 : constant Version_32 := 16#63305874#;
27421    u00045 : constant Version_32 := 16#31E56CE1#;
27422    u00046 : constant Version_32 := 16#02917970#;
27423    u00047 : constant Version_32 := 16#6CCBA70E#;
27424    u00048 : constant Version_32 := 16#41CD4204#;
27425    u00049 : constant Version_32 := 16#572E3F58#;
27426    u00050 : constant Version_32 := 16#20729FF5#;
27427    u00051 : constant Version_32 := 16#1D4F93E8#;
27428    u00052 : constant Version_32 := 16#30B2EC3D#;
27429    u00053 : constant Version_32 := 16#34054F96#;
27430    u00054 : constant Version_32 := 16#5A199860#;
27431    u00055 : constant Version_32 := 16#0E7F912B#;
27432    u00056 : constant Version_32 := 16#5760634A#;
27433    u00057 : constant Version_32 := 16#5D851835#;
27434
27435    --  The following Export pragmas export the version numbers
27436    --  with symbolic names ending in B (for body) or S
27437    --  (for spec) so that they can be located in a link. The
27438    --  information provided here is sufficient to track down
27439    --  the exact versions of units used in a given build.
27440
27441    pragma Export (C, u00001, "helloB");
27442    pragma Export (C, u00002, "system__standard_libraryB");
27443    pragma Export (C, u00003, "system__standard_libraryS");
27444    pragma Export (C, u00004, "adaS");
27445    pragma Export (C, u00005, "ada__text_ioB");
27446    pragma Export (C, u00006, "ada__text_ioS");
27447    pragma Export (C, u00007, "ada__exceptionsB");
27448    pragma Export (C, u00008, "ada__exceptionsS");
27449    pragma Export (C, u00009, "gnatS");
27450    pragma Export (C, u00010, "gnat__heap_sort_aB");
27451    pragma Export (C, u00011, "gnat__heap_sort_aS");
27452    pragma Export (C, u00012, "systemS");
27453    pragma Export (C, u00013, "system__exception_tableB");
27454    pragma Export (C, u00014, "system__exception_tableS");
27455    pragma Export (C, u00015, "gnat__htableB");
27456    pragma Export (C, u00016, "gnat__htableS");
27457    pragma Export (C, u00017, "system__exceptionsS");
27458    pragma Export (C, u00018, "system__machine_state_operationsB");
27459    pragma Export (C, u00019, "system__machine_state_operationsS");
27460    pragma Export (C, u00020, "system__machine_codeS");
27461    pragma Export (C, u00021, "system__storage_elementsB");
27462    pragma Export (C, u00022, "system__storage_elementsS");
27463    pragma Export (C, u00023, "system__secondary_stackB");
27464    pragma Export (C, u00024, "system__secondary_stackS");
27465    pragma Export (C, u00025, "system__parametersB");
27466    pragma Export (C, u00026, "system__parametersS");
27467    pragma Export (C, u00027, "system__soft_linksB");
27468    pragma Export (C, u00028, "system__soft_linksS");
27469    pragma Export (C, u00029, "system__stack_checkingB");
27470    pragma Export (C, u00030, "system__stack_checkingS");
27471    pragma Export (C, u00031, "system__tracebackB");
27472    pragma Export (C, u00032, "system__tracebackS");
27473    pragma Export (C, u00033, "ada__streamsS");
27474    pragma Export (C, u00034, "ada__tagsB");
27475    pragma Export (C, u00035, "ada__tagsS");
27476    pragma Export (C, u00036, "system__string_opsB");
27477    pragma Export (C, u00037, "system__string_opsS");
27478    pragma Export (C, u00038, "interfacesS");
27479    pragma Export (C, u00039, "interfaces__c_streamsB");
27480    pragma Export (C, u00040, "interfaces__c_streamsS");
27481    pragma Export (C, u00041, "system__file_ioB");
27482    pragma Export (C, u00042, "system__file_ioS");
27483    pragma Export (C, u00043, "ada__finalizationB");
27484    pragma Export (C, u00044, "ada__finalizationS");
27485    pragma Export (C, u00045, "system__finalization_rootB");
27486    pragma Export (C, u00046, "system__finalization_rootS");
27487    pragma Export (C, u00047, "system__finalization_implementationB");
27488    pragma Export (C, u00048, "system__finalization_implementationS");
27489    pragma Export (C, u00049, "system__string_ops_concat_3B");
27490    pragma Export (C, u00050, "system__string_ops_concat_3S");
27491    pragma Export (C, u00051, "system__stream_attributesB");
27492    pragma Export (C, u00052, "system__stream_attributesS");
27493    pragma Export (C, u00053, "ada__io_exceptionsS");
27494    pragma Export (C, u00054, "system__unsigned_typesS");
27495    pragma Export (C, u00055, "system__file_control_blockS");
27496    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27497    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27498
27499    -- BEGIN ELABORATION ORDER
27500    -- ada (spec)
27501    -- gnat (spec)
27502    -- gnat.heap_sort_a (spec)
27503    -- gnat.heap_sort_a (body)
27504    -- gnat.htable (spec)
27505    -- gnat.htable (body)
27506    -- interfaces (spec)
27507    -- system (spec)
27508    -- system.machine_code (spec)
27509    -- system.parameters (spec)
27510    -- system.parameters (body)
27511    -- interfaces.c_streams (spec)
27512    -- interfaces.c_streams (body)
27513    -- system.standard_library (spec)
27514    -- ada.exceptions (spec)
27515    -- system.exception_table (spec)
27516    -- system.exception_table (body)
27517    -- ada.io_exceptions (spec)
27518    -- system.exceptions (spec)
27519    -- system.storage_elements (spec)
27520    -- system.storage_elements (body)
27521    -- system.machine_state_operations (spec)
27522    -- system.machine_state_operations (body)
27523    -- system.secondary_stack (spec)
27524    -- system.stack_checking (spec)
27525    -- system.soft_links (spec)
27526    -- system.soft_links (body)
27527    -- system.stack_checking (body)
27528    -- system.secondary_stack (body)
27529    -- system.standard_library (body)
27530    -- system.string_ops (spec)
27531    -- system.string_ops (body)
27532    -- ada.tags (spec)
27533    -- ada.tags (body)
27534    -- ada.streams (spec)
27535    -- system.finalization_root (spec)
27536    -- system.finalization_root (body)
27537    -- system.string_ops_concat_3 (spec)
27538    -- system.string_ops_concat_3 (body)
27539    -- system.traceback (spec)
27540    -- system.traceback (body)
27541    -- ada.exceptions (body)
27542    -- system.unsigned_types (spec)
27543    -- system.stream_attributes (spec)
27544    -- system.stream_attributes (body)
27545    -- system.finalization_implementation (spec)
27546    -- system.finalization_implementation (body)
27547    -- ada.finalization (spec)
27548    -- ada.finalization (body)
27549    -- ada.finalization.list_controller (spec)
27550    -- ada.finalization.list_controller (body)
27551    -- system.file_control_block (spec)
27552    -- system.file_io (spec)
27553    -- system.file_io (body)
27554    -- ada.text_io (spec)
27555    -- ada.text_io (body)
27556    -- hello (body)
27557    -- END ELABORATION ORDER
27558
27559 end ada_main;
27560
27561 --  The following source file name pragmas allow the generated file
27562 --  names to be unique for different main programs. They are needed
27563 --  since the package name will always be Ada_Main.
27564
27565 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27566 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27567
27568 --  Generated package body for Ada_Main starts here
27569
27570 package body ada_main is
27571
27572    --  The actual finalization is performed by calling the
27573    --  library routine in System.Standard_Library.Adafinal
27574
27575    procedure Do_Finalize;
27576    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27577
27578    -------------
27579    -- adainit --
27580    -------------
27581
27582 @findex adainit
27583    procedure adainit is
27584
27585       --  These booleans are set to True once the associated unit has
27586       --  been elaborated. It is also used to avoid elaborating the
27587       --  same unit twice.
27588
27589       E040 : Boolean;
27590       pragma Import (Ada, E040, "interfaces__c_streams_E");
27591
27592       E008 : Boolean;
27593       pragma Import (Ada, E008, "ada__exceptions_E");
27594
27595       E014 : Boolean;
27596       pragma Import (Ada, E014, "system__exception_table_E");
27597
27598       E053 : Boolean;
27599       pragma Import (Ada, E053, "ada__io_exceptions_E");
27600
27601       E017 : Boolean;
27602       pragma Import (Ada, E017, "system__exceptions_E");
27603
27604       E024 : Boolean;
27605       pragma Import (Ada, E024, "system__secondary_stack_E");
27606
27607       E030 : Boolean;
27608       pragma Import (Ada, E030, "system__stack_checking_E");
27609
27610       E028 : Boolean;
27611       pragma Import (Ada, E028, "system__soft_links_E");
27612
27613       E035 : Boolean;
27614       pragma Import (Ada, E035, "ada__tags_E");
27615
27616       E033 : Boolean;
27617       pragma Import (Ada, E033, "ada__streams_E");
27618
27619       E046 : Boolean;
27620       pragma Import (Ada, E046, "system__finalization_root_E");
27621
27622       E048 : Boolean;
27623       pragma Import (Ada, E048, "system__finalization_implementation_E");
27624
27625       E044 : Boolean;
27626       pragma Import (Ada, E044, "ada__finalization_E");
27627
27628       E057 : Boolean;
27629       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27630
27631       E055 : Boolean;
27632       pragma Import (Ada, E055, "system__file_control_block_E");
27633
27634       E042 : Boolean;
27635       pragma Import (Ada, E042, "system__file_io_E");
27636
27637       E006 : Boolean;
27638       pragma Import (Ada, E006, "ada__text_io_E");
27639
27640       --  Set_Globals is a library routine that stores away the
27641       --  value of the indicated set of global values in global
27642       --  variables within the library.
27643
27644       procedure Set_Globals
27645         (Main_Priority            : Integer;
27646          Time_Slice_Value         : Integer;
27647          WC_Encoding              : Character;
27648          Locking_Policy           : Character;
27649          Queuing_Policy           : Character;
27650          Task_Dispatching_Policy  : Character;
27651          Adafinal                 : System.Address;
27652          Unreserve_All_Interrupts : Integer;
27653          Exception_Tracebacks     : Integer);
27654 @findex __gnat_set_globals
27655       pragma Import (C, Set_Globals, "__gnat_set_globals");
27656
27657       --  SDP_Table_Build is a library routine used to build the
27658       --  exception tables. See unit Ada.Exceptions in files
27659       --  a-except.ads/adb for full details of how zero cost
27660       --  exception handling works. This procedure, the call to
27661       --  it, and the two following tables are all omitted if the
27662       --  build is in longjmp/setjmp exception mode.
27663
27664 @findex SDP_Table_Build
27665 @findex Zero Cost Exceptions
27666       procedure SDP_Table_Build
27667         (SDP_Addresses   : System.Address;
27668          SDP_Count       : Natural;
27669          Elab_Addresses  : System.Address;
27670          Elab_Addr_Count : Natural);
27671       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27672
27673       --  Table of Unit_Exception_Table addresses. Used for zero
27674       --  cost exception handling to build the top level table.
27675
27676       ST : aliased constant array (1 .. 23) of System.Address := (
27677         Hello'UET_Address,
27678         Ada.Text_Io'UET_Address,
27679         Ada.Exceptions'UET_Address,
27680         Gnat.Heap_Sort_A'UET_Address,
27681         System.Exception_Table'UET_Address,
27682         System.Machine_State_Operations'UET_Address,
27683         System.Secondary_Stack'UET_Address,
27684         System.Parameters'UET_Address,
27685         System.Soft_Links'UET_Address,
27686         System.Stack_Checking'UET_Address,
27687         System.Traceback'UET_Address,
27688         Ada.Streams'UET_Address,
27689         Ada.Tags'UET_Address,
27690         System.String_Ops'UET_Address,
27691         Interfaces.C_Streams'UET_Address,
27692         System.File_Io'UET_Address,
27693         Ada.Finalization'UET_Address,
27694         System.Finalization_Root'UET_Address,
27695         System.Finalization_Implementation'UET_Address,
27696         System.String_Ops_Concat_3'UET_Address,
27697         System.Stream_Attributes'UET_Address,
27698         System.File_Control_Block'UET_Address,
27699         Ada.Finalization.List_Controller'UET_Address);
27700
27701       --  Table of addresses of elaboration routines. Used for
27702       --  zero cost exception handling to make sure these
27703       --  addresses are included in the top level procedure
27704       --  address table.
27705
27706       EA : aliased constant array (1 .. 23) of System.Address := (
27707         adainit'Code_Address,
27708         Do_Finalize'Code_Address,
27709         Ada.Exceptions'Elab_Spec'Address,
27710         System.Exceptions'Elab_Spec'Address,
27711         Interfaces.C_Streams'Elab_Spec'Address,
27712         System.Exception_Table'Elab_Body'Address,
27713         Ada.Io_Exceptions'Elab_Spec'Address,
27714         System.Stack_Checking'Elab_Spec'Address,
27715         System.Soft_Links'Elab_Body'Address,
27716         System.Secondary_Stack'Elab_Body'Address,
27717         Ada.Tags'Elab_Spec'Address,
27718         Ada.Tags'Elab_Body'Address,
27719         Ada.Streams'Elab_Spec'Address,
27720         System.Finalization_Root'Elab_Spec'Address,
27721         Ada.Exceptions'Elab_Body'Address,
27722         System.Finalization_Implementation'Elab_Spec'Address,
27723         System.Finalization_Implementation'Elab_Body'Address,
27724         Ada.Finalization'Elab_Spec'Address,
27725         Ada.Finalization.List_Controller'Elab_Spec'Address,
27726         System.File_Control_Block'Elab_Spec'Address,
27727         System.File_Io'Elab_Body'Address,
27728         Ada.Text_Io'Elab_Spec'Address,
27729         Ada.Text_Io'Elab_Body'Address);
27730
27731    --  Start of processing for adainit
27732
27733    begin
27734
27735       --  Call SDP_Table_Build to build the top level procedure
27736       --  table for zero cost exception handling (omitted in
27737       --  longjmp/setjmp mode).
27738
27739       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27740
27741       --  Call Set_Globals to record various information for
27742       --  this partition.  The values are derived by the binder
27743       --  from information stored in the ali files by the compiler.
27744
27745 @findex __gnat_set_globals
27746       Set_Globals
27747         (Main_Priority            => -1,
27748          --  Priority of main program, -1 if no pragma Priority used
27749
27750          Time_Slice_Value         => -1,
27751          --  Time slice from Time_Slice pragma, -1 if none used
27752
27753          WC_Encoding              => 'b',
27754          --  Wide_Character encoding used, default is brackets
27755
27756          Locking_Policy           => ' ',
27757          --  Locking_Policy used, default of space means not
27758          --  specified, otherwise it is the first character of
27759          --  the policy name.
27760
27761          Queuing_Policy           => ' ',
27762          --  Queuing_Policy used, default of space means not
27763          --  specified, otherwise it is the first character of
27764          --  the policy name.
27765
27766          Task_Dispatching_Policy  => ' ',
27767          --  Task_Dispatching_Policy used, default of space means
27768          --  not specified, otherwise first character of the
27769          --  policy name.
27770
27771          Adafinal                 => System.Null_Address,
27772          --  Address of Adafinal routine, not used anymore
27773
27774          Unreserve_All_Interrupts => 0,
27775          --  Set true if pragma Unreserve_All_Interrupts was used
27776
27777          Exception_Tracebacks     => 0);
27778          --  Indicates if exception tracebacks are enabled
27779
27780       Elab_Final_Code := 1;
27781
27782       --  Now we have the elaboration calls for all units in the partition.
27783       --  The Elab_Spec and Elab_Body attributes generate references to the
27784       --  implicit elaboration procedures generated by the compiler for
27785       --  each unit that requires elaboration.
27786
27787       if not E040 then
27788          Interfaces.C_Streams'Elab_Spec;
27789       end if;
27790       E040 := True;
27791       if not E008 then
27792          Ada.Exceptions'Elab_Spec;
27793       end if;
27794       if not E014 then
27795          System.Exception_Table'Elab_Body;
27796          E014 := True;
27797       end if;
27798       if not E053 then
27799          Ada.Io_Exceptions'Elab_Spec;
27800          E053 := True;
27801       end if;
27802       if not E017 then
27803          System.Exceptions'Elab_Spec;
27804          E017 := True;
27805       end if;
27806       if not E030 then
27807          System.Stack_Checking'Elab_Spec;
27808       end if;
27809       if not E028 then
27810          System.Soft_Links'Elab_Body;
27811          E028 := True;
27812       end if;
27813       E030 := True;
27814       if not E024 then
27815          System.Secondary_Stack'Elab_Body;
27816          E024 := True;
27817       end if;
27818       if not E035 then
27819          Ada.Tags'Elab_Spec;
27820       end if;
27821       if not E035 then
27822          Ada.Tags'Elab_Body;
27823          E035 := True;
27824       end if;
27825       if not E033 then
27826          Ada.Streams'Elab_Spec;
27827          E033 := True;
27828       end if;
27829       if not E046 then
27830          System.Finalization_Root'Elab_Spec;
27831       end if;
27832       E046 := True;
27833       if not E008 then
27834          Ada.Exceptions'Elab_Body;
27835          E008 := True;
27836       end if;
27837       if not E048 then
27838          System.Finalization_Implementation'Elab_Spec;
27839       end if;
27840       if not E048 then
27841          System.Finalization_Implementation'Elab_Body;
27842          E048 := True;
27843       end if;
27844       if not E044 then
27845          Ada.Finalization'Elab_Spec;
27846       end if;
27847       E044 := True;
27848       if not E057 then
27849          Ada.Finalization.List_Controller'Elab_Spec;
27850       end if;
27851       E057 := True;
27852       if not E055 then
27853          System.File_Control_Block'Elab_Spec;
27854          E055 := True;
27855       end if;
27856       if not E042 then
27857          System.File_Io'Elab_Body;
27858          E042 := True;
27859       end if;
27860       if not E006 then
27861          Ada.Text_Io'Elab_Spec;
27862       end if;
27863       if not E006 then
27864          Ada.Text_Io'Elab_Body;
27865          E006 := True;
27866       end if;
27867
27868       Elab_Final_Code := 0;
27869    end adainit;
27870
27871    --------------
27872    -- adafinal --
27873    --------------
27874
27875 @findex adafinal
27876    procedure adafinal is
27877    begin
27878       Do_Finalize;
27879    end adafinal;
27880
27881    ----------
27882    -- main --
27883    ----------
27884
27885    --  main is actually a function, as in the ANSI C standard,
27886    --  defined to return the exit status. The three parameters
27887    --  are the argument count, argument values and environment
27888    --  pointer.
27889
27890 @findex Main Program
27891    function main
27892      (argc : Integer;
27893       argv : System.Address;
27894       envp : System.Address)
27895       return Integer
27896    is
27897       --  The initialize routine performs low level system
27898       --  initialization using a standard library routine which
27899       --  sets up signal handling and performs any other
27900       --  required setup. The routine can be found in file
27901       --  a-init.c.
27902
27903 @findex __gnat_initialize
27904       procedure initialize;
27905       pragma Import (C, initialize, "__gnat_initialize");
27906
27907       --  The finalize routine performs low level system
27908       --  finalization using a standard library routine. The
27909       --  routine is found in file a-final.c and in the standard
27910       --  distribution is a dummy routine that does nothing, so
27911       --  really this is a hook for special user finalization.
27912
27913 @findex __gnat_finalize
27914       procedure finalize;
27915       pragma Import (C, finalize, "__gnat_finalize");
27916
27917       --  We get to the main program of the partition by using
27918       --  pragma Import because if we try to with the unit and
27919       --  call it Ada style, then not only do we waste time
27920       --  recompiling it, but also, we don't really know the right
27921       --  switches (e.g.@: identifier character set) to be used
27922       --  to compile it.
27923
27924       procedure Ada_Main_Program;
27925       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27926
27927    --  Start of processing for main
27928
27929    begin
27930       --  Save global variables
27931
27932       gnat_argc := argc;
27933       gnat_argv := argv;
27934       gnat_envp := envp;
27935
27936       --  Call low level system initialization
27937
27938       Initialize;
27939
27940       --  Call our generated Ada initialization routine
27941
27942       adainit;
27943
27944       --  This is the point at which we want the debugger to get
27945       --  control
27946
27947       Break_Start;
27948
27949       --  Now we call the main program of the partition
27950
27951       Ada_Main_Program;
27952
27953       --  Perform Ada finalization
27954
27955       adafinal;
27956
27957       --  Perform low level system finalization
27958
27959       Finalize;
27960
27961       --  Return the proper exit status
27962       return (gnat_exit_status);
27963    end;
27964
27965 --  This section is entirely comments, so it has no effect on the
27966 --  compilation of the Ada_Main package. It provides the list of
27967 --  object files and linker options, as well as some standard
27968 --  libraries needed for the link. The gnatlink utility parses
27969 --  this b~hello.adb file to read these comment lines to generate
27970 --  the appropriate command line arguments for the call to the
27971 --  system linker. The BEGIN/END lines are used for sentinels for
27972 --  this parsing operation.
27973
27974 --  The exact file names will of course depend on the environment,
27975 --  host/target and location of files on the host system.
27976
27977 @findex Object file list
27978 -- BEGIN Object file/option list
27979    --   ./hello.o
27980    --   -L./
27981    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27982    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27983 -- END Object file/option list
27984
27985 end ada_main;
27986 @end smallexample
27987
27988 @noindent
27989 The Ada code in the above example is exactly what is generated by the
27990 binder. We have added comments to more clearly indicate the function
27991 of each part of the generated @code{Ada_Main} package.
27992
27993 The code is standard Ada in all respects, and can be processed by any
27994 tools that handle Ada. In particular, it is possible to use the debugger
27995 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27996 suppose that for reasons that you do not understand, your program is crashing
27997 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27998 you can place a breakpoint on the call:
27999
28000 @smallexample @c ada
28001 Ada.Text_Io'Elab_Body;
28002 @end smallexample
28003
28004 @noindent
28005 and trace the elaboration routine for this package to find out where
28006 the problem might be (more usually of course you would be debugging
28007 elaboration code in your own application).
28008
28009 @node Elaboration Order Handling in GNAT
28010 @appendix Elaboration Order Handling in GNAT
28011 @cindex Order of elaboration
28012 @cindex Elaboration control
28013
28014 @menu
28015 * Elaboration Code::
28016 * Checking the Elaboration Order::
28017 * Controlling the Elaboration Order::
28018 * Controlling Elaboration in GNAT - Internal Calls::
28019 * Controlling Elaboration in GNAT - External Calls::
28020 * Default Behavior in GNAT - Ensuring Safety::
28021 * Treatment of Pragma Elaborate::
28022 * Elaboration Issues for Library Tasks::
28023 * Mixing Elaboration Models::
28024 * What to Do If the Default Elaboration Behavior Fails::
28025 * Elaboration for Access-to-Subprogram Values::
28026 * Summary of Procedures for Elaboration Control::
28027 * Other Elaboration Order Considerations::
28028 @end menu
28029
28030 @noindent
28031 This chapter describes the handling of elaboration code in Ada and
28032 in GNAT, and discusses how the order of elaboration of program units can
28033 be controlled in GNAT, either automatically or with explicit programming
28034 features.
28035
28036 @node Elaboration Code
28037 @section Elaboration Code
28038
28039 @noindent
28040 Ada provides rather general mechanisms for executing code at elaboration
28041 time, that is to say before the main program starts executing. Such code arises
28042 in three contexts:
28043
28044 @table @asis
28045 @item Initializers for variables.
28046 Variables declared at the library level, in package specs or bodies, can
28047 require initialization that is performed at elaboration time, as in:
28048 @smallexample @c ada
28049 @cartouche
28050 Sqrt_Half : Float := Sqrt (0.5);
28051 @end cartouche
28052 @end smallexample
28053
28054 @item Package initialization code
28055 Code in a @code{BEGIN-END} section at the outer level of a package body is
28056 executed as part of the package body elaboration code.
28057
28058 @item Library level task allocators
28059 Tasks that are declared using task allocators at the library level
28060 start executing immediately and hence can execute at elaboration time.
28061 @end table
28062
28063 @noindent
28064 Subprogram calls are possible in any of these contexts, which means that
28065 any arbitrary part of the program may be executed as part of the elaboration
28066 code. It is even possible to write a program which does all its work at
28067 elaboration time, with a null main program, although stylistically this
28068 would usually be considered an inappropriate way to structure
28069 a program.
28070
28071 An important concern arises in the context of elaboration code:
28072 we have to be sure that it is executed in an appropriate order. What we
28073 have is a series of elaboration code sections, potentially one section
28074 for each unit in the program. It is important that these execute
28075 in the correct order. Correctness here means that, taking the above
28076 example of the declaration of @code{Sqrt_Half},
28077 if some other piece of
28078 elaboration code references @code{Sqrt_Half},
28079 then it must run after the
28080 section of elaboration code that contains the declaration of
28081 @code{Sqrt_Half}.
28082
28083 There would never be any order of elaboration problem if we made a rule
28084 that whenever you @code{with} a unit, you must elaborate both the spec and body
28085 of that unit before elaborating the unit doing the @code{with}'ing:
28086
28087 @smallexample @c ada
28088 @group
28089 @cartouche
28090 with Unit_1;
28091 package Unit_2 is @dots{}
28092 @end cartouche
28093 @end group
28094 @end smallexample
28095
28096 @noindent
28097 would require that both the body and spec of @code{Unit_1} be elaborated
28098 before the spec of @code{Unit_2}. However, a rule like that would be far too
28099 restrictive. In particular, it would make it impossible to have routines
28100 in separate packages that were mutually recursive.
28101
28102 You might think that a clever enough compiler could look at the actual
28103 elaboration code and determine an appropriate correct order of elaboration,
28104 but in the general case, this is not possible. Consider the following
28105 example.
28106
28107 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
28108 that references
28109 the variable @code{Sqrt_1}, which is declared in the elaboration code
28110 of the body of @code{Unit_1}:
28111
28112 @smallexample @c ada
28113 @cartouche
28114 Sqrt_1 : Float := Sqrt (0.1);
28115 @end cartouche
28116 @end smallexample
28117
28118 @noindent
28119 The elaboration code of the body of @code{Unit_1} also contains:
28120
28121 @smallexample @c ada
28122 @group
28123 @cartouche
28124 if expression_1 = 1 then
28125    Q := Unit_2.Func_2;
28126 end if;
28127 @end cartouche
28128 @end group
28129 @end smallexample
28130
28131 @noindent
28132 @code{Unit_2} is exactly parallel,
28133 it has a procedure @code{Func_2} that references
28134 the variable @code{Sqrt_2}, which is declared in the elaboration code of
28135 the body @code{Unit_2}:
28136
28137 @smallexample @c ada
28138 @cartouche
28139 Sqrt_2 : Float := Sqrt (0.1);
28140 @end cartouche
28141 @end smallexample
28142
28143 @noindent
28144 The elaboration code of the body of @code{Unit_2} also contains:
28145
28146 @smallexample @c ada
28147 @group
28148 @cartouche
28149 if expression_2 = 2 then
28150    Q := Unit_1.Func_1;
28151 end if;
28152 @end cartouche
28153 @end group
28154 @end smallexample
28155
28156 @noindent
28157 Now the question is, which of the following orders of elaboration is
28158 acceptable:
28159
28160 @smallexample
28161 @group
28162 Spec of Unit_1
28163 Spec of Unit_2
28164 Body of Unit_1
28165 Body of Unit_2
28166 @end group
28167 @end smallexample
28168
28169 @noindent
28170 or
28171
28172 @smallexample
28173 @group
28174 Spec of Unit_2
28175 Spec of Unit_1
28176 Body of Unit_2
28177 Body of Unit_1
28178 @end group
28179 @end smallexample
28180
28181 @noindent
28182 If you carefully analyze the flow here, you will see that you cannot tell
28183 at compile time the answer to this question.
28184 If @code{expression_1} is not equal to 1,
28185 and @code{expression_2} is not equal to 2,
28186 then either order is acceptable, because neither of the function calls is
28187 executed. If both tests evaluate to true, then neither order is acceptable
28188 and in fact there is no correct order.
28189
28190 If one of the two expressions is true, and the other is false, then one
28191 of the above orders is correct, and the other is incorrect. For example,
28192 if @code{expression_1} /= 1 and @code{expression_2} = 2,
28193 then the call to @code{Func_1}
28194 will occur, but not the call to @code{Func_2.}
28195 This means that it is essential
28196 to elaborate the body of @code{Unit_1} before
28197 the body of @code{Unit_2}, so the first
28198 order of elaboration is correct and the second is wrong.
28199
28200 By making @code{expression_1} and @code{expression_2}
28201 depend on input data, or perhaps
28202 the time of day, we can make it impossible for the compiler or binder
28203 to figure out which of these expressions will be true, and hence it
28204 is impossible to guarantee a safe order of elaboration at run time.
28205
28206 @node Checking the Elaboration Order
28207 @section Checking the Elaboration Order
28208
28209 @noindent
28210 In some languages that involve the same kind of elaboration problems,
28211 e.g.@: Java and C++, the programmer is expected to worry about these
28212 ordering problems himself, and it is common to
28213 write a program in which an incorrect elaboration order  gives
28214 surprising results, because it references variables before they
28215 are initialized.
28216 Ada is designed to be a safe language, and a programmer-beware approach is
28217 clearly not sufficient. Consequently, the language provides three lines
28218 of defense:
28219
28220 @table @asis
28221 @item Standard rules
28222 Some standard rules restrict the possible choice of elaboration
28223 order. In particular, if you @code{with} a unit, then its spec is always
28224 elaborated before the unit doing the @code{with}. Similarly, a parent
28225 spec is always elaborated before the child spec, and finally
28226 a spec is always elaborated before its corresponding body.
28227
28228 @item Dynamic elaboration checks
28229 @cindex Elaboration checks
28230 @cindex Checks, elaboration
28231 Dynamic checks are made at run time, so that if some entity is accessed
28232 before it is elaborated (typically  by means of a subprogram call)
28233 then the exception (@code{Program_Error}) is raised.
28234
28235 @item Elaboration control
28236 Facilities are provided for the programmer to specify the desired order
28237 of elaboration.
28238 @end table
28239
28240 Let's look at these facilities in more detail. First, the rules for
28241 dynamic checking. One possible rule would be simply to say that the
28242 exception is raised if you access a variable which has not yet been
28243 elaborated. The trouble with this approach is that it could require
28244 expensive checks on every variable reference. Instead Ada has two
28245 rules which are a little more restrictive, but easier to check, and
28246 easier to state:
28247
28248 @table @asis
28249 @item Restrictions on calls
28250 A subprogram can only be called at elaboration time if its body
28251 has been elaborated. The rules for elaboration given above guarantee
28252 that the spec of the subprogram has been elaborated before the
28253 call, but not the body. If this rule is violated, then the
28254 exception @code{Program_Error} is raised.
28255
28256 @item Restrictions on instantiations
28257 A generic unit can only be instantiated if the body of the generic
28258 unit has been elaborated. Again, the rules for elaboration given above
28259 guarantee that the spec of the generic unit has been elaborated
28260 before the instantiation, but not the body. If this rule is
28261 violated, then the exception @code{Program_Error} is raised.
28262 @end table
28263
28264 @noindent
28265 The idea is that if the body has been elaborated, then any variables
28266 it references must have been elaborated; by checking for the body being
28267 elaborated we guarantee that none of its references causes any
28268 trouble. As we noted above, this is a little too restrictive, because a
28269 subprogram that has no non-local references in its body may in fact be safe
28270 to call. However, it really would be unsafe to rely on this, because
28271 it would mean that the caller was aware of details of the implementation
28272 in the body. This goes against the basic tenets of Ada.
28273
28274 A plausible implementation can be described as follows.
28275 A Boolean variable is associated with each subprogram
28276 and each generic unit. This variable is initialized to False, and is set to
28277 True at the point body is elaborated. Every call or instantiation checks the
28278 variable, and raises @code{Program_Error} if the variable is False.
28279
28280 Note that one might think that it would be good enough to have one Boolean
28281 variable for each package, but that would not deal with cases of trying
28282 to call a body in the same package as the call
28283 that has not been elaborated yet.
28284 Of course a compiler may be able to do enough analysis to optimize away
28285 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28286 does such optimizations, but still the easiest conceptual model is to
28287 think of there being one variable per subprogram.
28288
28289 @node Controlling the Elaboration Order
28290 @section Controlling the Elaboration Order
28291
28292 @noindent
28293 In the previous section we discussed the rules in Ada which ensure
28294 that @code{Program_Error} is raised if an incorrect elaboration order is
28295 chosen. This prevents erroneous executions, but we need mechanisms to
28296 specify a correct execution and avoid the exception altogether.
28297 To achieve this, Ada provides a number of features for controlling
28298 the order of elaboration. We discuss these features in this section.
28299
28300 First, there are several ways of indicating to the compiler that a given
28301 unit has no elaboration problems:
28302
28303 @table @asis
28304 @item packages that do not require a body
28305 A library package that does not require a body does not permit
28306 a body (this rule was introduced in Ada 95).
28307 Thus if we have a such a package, as in:
28308
28309 @smallexample @c ada
28310 @group
28311 @cartouche
28312 package Definitions is
28313    generic
28314       type m is new integer;
28315    package Subp is
28316       type a is array (1 .. 10) of m;
28317       type b is array (1 .. 20) of m;
28318    end Subp;
28319 end Definitions;
28320 @end cartouche
28321 @end group
28322 @end smallexample
28323
28324 @noindent
28325 A package that @code{with}'s @code{Definitions} may safely instantiate
28326 @code{Definitions.Subp} because the compiler can determine that there
28327 definitely is no package body to worry about in this case
28328
28329 @item pragma Pure
28330 @cindex pragma Pure
28331 @findex Pure
28332 Places sufficient restrictions on a unit to guarantee that
28333 no call to any subprogram in the unit can result in an
28334 elaboration problem. This means that the compiler does not need
28335 to worry about the point of elaboration of such units, and in
28336 particular, does not need to check any calls to any subprograms
28337 in this unit.
28338
28339 @item pragma Preelaborate
28340 @findex Preelaborate
28341 @cindex pragma Preelaborate
28342 This pragma places slightly less stringent restrictions on a unit than
28343 does pragma Pure,
28344 but these restrictions are still sufficient to ensure that there
28345 are no elaboration problems with any calls to the unit.
28346
28347 @item pragma Elaborate_Body
28348 @findex Elaborate_Body
28349 @cindex pragma Elaborate_Body
28350 This pragma requires that the body of a unit be elaborated immediately
28351 after its spec. Suppose a unit @code{A} has such a pragma,
28352 and unit @code{B} does
28353 a @code{with} of unit @code{A}. Recall that the standard rules require
28354 the spec of unit @code{A}
28355 to be elaborated before the @code{with}'ing unit; given the pragma in
28356 @code{A}, we also know that the body of @code{A}
28357 will be elaborated before @code{B}, so
28358 that calls to @code{A} are safe and do not need a check.
28359 @end table
28360
28361 @noindent
28362 Note that,
28363 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28364 the use of
28365 @code{Elaborate_Body} does not guarantee that the program is
28366 free of elaboration problems, because it may not be possible
28367 to satisfy the requested elaboration order.
28368 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28369 If a programmer
28370 marks @code{Unit_1} as @code{Elaborate_Body},
28371 and not @code{Unit_2,} then the order of
28372 elaboration will be:
28373
28374 @smallexample
28375 @group
28376 Spec of Unit_2
28377 Spec of Unit_1
28378 Body of Unit_1
28379 Body of Unit_2
28380 @end group
28381 @end smallexample
28382
28383 @noindent
28384 Now that means that the call to @code{Func_1} in @code{Unit_2}
28385 need not be checked,
28386 it must be safe. But the call to @code{Func_2} in
28387 @code{Unit_1} may still fail if
28388 @code{Expression_1} is equal to 1,
28389 and the programmer must still take
28390 responsibility for this not being the case.
28391
28392 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28393 eliminated, except for calls entirely within a body, which are
28394 in any case fully under programmer control. However, using the pragma
28395 everywhere is not always possible.
28396 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28397 we marked both of them as having pragma @code{Elaborate_Body}, then
28398 clearly there would be no possible elaboration order.
28399
28400 The above pragmas allow a server to guarantee safe use by clients, and
28401 clearly this is the preferable approach. Consequently a good rule
28402 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28403 and if this is not possible,
28404 mark them as @code{Elaborate_Body} if possible.
28405 As we have seen, there are situations where neither of these
28406 three pragmas can be used.
28407 So we also provide methods for clients to control the
28408 order of elaboration of the servers on which they depend:
28409
28410 @table @asis
28411 @item pragma Elaborate (unit)
28412 @findex Elaborate
28413 @cindex pragma Elaborate
28414 This pragma is placed in the context clause, after a @code{with} clause,
28415 and it requires that the body of the named unit be elaborated before
28416 the unit in which the pragma occurs. The idea is to use this pragma
28417 if the current unit calls at elaboration time, directly or indirectly,
28418 some subprogram in the named unit.
28419
28420 @item pragma Elaborate_All (unit)
28421 @findex Elaborate_All
28422 @cindex pragma Elaborate_All
28423 This is a stronger version of the Elaborate pragma. Consider the
28424 following example:
28425
28426 @smallexample
28427 Unit A @code{with}'s unit B and calls B.Func in elab code
28428 Unit B @code{with}'s unit C, and B.Func calls C.Func
28429 @end smallexample
28430
28431 @noindent
28432 Now if we put a pragma @code{Elaborate (B)}
28433 in unit @code{A}, this ensures that the
28434 body of @code{B} is elaborated before the call, but not the
28435 body of @code{C}, so
28436 the call to @code{C.Func} could still cause @code{Program_Error} to
28437 be raised.
28438
28439 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28440 not only that the body of the named unit be elaborated before the
28441 unit doing the @code{with}, but also the bodies of all units that the
28442 named unit uses, following @code{with} links transitively. For example,
28443 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28444 then it requires
28445 not only that the body of @code{B} be elaborated before @code{A},
28446 but also the
28447 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28448 @end table
28449
28450 @noindent
28451 We are now in a position to give a usage rule in Ada for avoiding
28452 elaboration problems, at least if dynamic dispatching and access to
28453 subprogram values are not used. We will handle these cases separately
28454 later.
28455
28456 The rule is simple. If a unit has elaboration code that can directly or
28457 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28458 a generic package in a @code{with}'ed unit,
28459 then if the @code{with}'ed unit does not have
28460 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28461 a pragma @code{Elaborate_All}
28462 for the @code{with}'ed unit. By following this rule a client is
28463 assured that calls can be made without risk of an exception.
28464
28465 For generic subprogram instantiations, the rule can be relaxed to
28466 require only a pragma @code{Elaborate} since elaborating the body
28467 of a subprogram cannot cause any transitive elaboration (we are
28468 not calling the subprogram in this case, just elaborating its
28469 declaration).
28470
28471 If this rule is not followed, then a program may be in one of four
28472 states:
28473
28474 @table @asis
28475 @item No order exists
28476 No order of elaboration exists which follows the rules, taking into
28477 account any @code{Elaborate}, @code{Elaborate_All},
28478 or @code{Elaborate_Body} pragmas. In
28479 this case, an Ada compiler must diagnose the situation at bind
28480 time, and refuse to build an executable program.
28481
28482 @item One or more orders exist, all incorrect
28483 One or more acceptable elaboration orders exist, and all of them
28484 generate an elaboration order problem. In this case, the binder
28485 can build an executable program, but @code{Program_Error} will be raised
28486 when the program is run.
28487
28488 @item Several orders exist, some right, some incorrect
28489 One or more acceptable elaboration orders exists, and some of them
28490 work, and some do not. The programmer has not controlled
28491 the order of elaboration, so the binder may or may not pick one of
28492 the correct orders, and the program may or may not raise an
28493 exception when it is run. This is the worst case, because it means
28494 that the program may fail when moved to another compiler, or even
28495 another version of the same compiler.
28496
28497 @item One or more orders exists, all correct
28498 One ore more acceptable elaboration orders exist, and all of them
28499 work. In this case the program runs successfully. This state of
28500 affairs can be guaranteed by following the rule we gave above, but
28501 may be true even if the rule is not followed.
28502 @end table
28503
28504 @noindent
28505 Note that one additional advantage of following our rules on the use
28506 of @code{Elaborate} and @code{Elaborate_All}
28507 is that the program continues to stay in the ideal (all orders OK) state
28508 even if maintenance
28509 changes some bodies of some units. Conversely, if a program that does
28510 not follow this rule happens to be safe at some point, this state of affairs
28511 may deteriorate silently as a result of maintenance changes.
28512
28513 You may have noticed that the above discussion did not mention
28514 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28515 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28516 code in the body makes calls to some other unit, so it is still necessary
28517 to use @code{Elaborate_All} on such units.
28518
28519 @node Controlling Elaboration in GNAT - Internal Calls
28520 @section Controlling Elaboration in GNAT - Internal Calls
28521
28522 @noindent
28523 In the case of internal calls, i.e., calls within a single package, the
28524 programmer has full control over the order of elaboration, and it is up
28525 to the programmer to elaborate declarations in an appropriate order. For
28526 example writing:
28527
28528 @smallexample @c ada
28529 @group
28530 @cartouche
28531 function One return Float;
28532
28533 Q : Float := One;
28534
28535 function One return Float is
28536 begin
28537      return 1.0;
28538 end One;
28539 @end cartouche
28540 @end group
28541 @end smallexample
28542
28543 @noindent
28544 will obviously raise @code{Program_Error} at run time, because function
28545 One will be called before its body is elaborated. In this case GNAT will
28546 generate a warning that the call will raise @code{Program_Error}:
28547
28548 @smallexample
28549 @group
28550 @cartouche
28551  1. procedure y is
28552  2.    function One return Float;
28553  3.
28554  4.    Q : Float := One;
28555                     |
28556     >>> warning: cannot call "One" before body is elaborated
28557     >>> warning: Program_Error will be raised at run time
28558
28559  5.
28560  6.    function One return Float is
28561  7.    begin
28562  8.         return 1.0;
28563  9.    end One;
28564 10.
28565 11. begin
28566 12.    null;
28567 13. end;
28568 @end cartouche
28569 @end group
28570 @end smallexample
28571
28572 @noindent
28573 Note that in this particular case, it is likely that the call is safe, because
28574 the function @code{One} does not access any global variables.
28575 Nevertheless in Ada, we do not want the validity of the check to depend on
28576 the contents of the body (think about the separate compilation case), so this
28577 is still wrong, as we discussed in the previous sections.
28578
28579 The error is easily corrected by rearranging the declarations so that the
28580 body of @code{One} appears before the declaration containing the call
28581 (note that in Ada 95 and Ada 2005,
28582 declarations can appear in any order, so there is no restriction that
28583 would prevent this reordering, and if we write:
28584
28585 @smallexample @c ada
28586 @group
28587 @cartouche
28588 function One return Float;
28589
28590 function One return Float is
28591 begin
28592      return 1.0;
28593 end One;
28594
28595 Q : Float := One;
28596 @end cartouche
28597 @end group
28598 @end smallexample
28599
28600 @noindent
28601 then all is well, no warning is generated, and no
28602 @code{Program_Error} exception
28603 will be raised.
28604 Things are more complicated when a chain of subprograms is executed:
28605
28606 @smallexample @c ada
28607 @group
28608 @cartouche
28609 function A return Integer;
28610 function B return Integer;
28611 function C return Integer;
28612
28613 function B return Integer is begin return A; end;
28614 function C return Integer is begin return B; end;
28615
28616 X : Integer := C;
28617
28618 function A return Integer is begin return 1; end;
28619 @end cartouche
28620 @end group
28621 @end smallexample
28622
28623 @noindent
28624 Now the call to @code{C}
28625 at elaboration time in the declaration of @code{X} is correct, because
28626 the body of @code{C} is already elaborated,
28627 and the call to @code{B} within the body of
28628 @code{C} is correct, but the call
28629 to @code{A} within the body of @code{B} is incorrect, because the body
28630 of @code{A} has not been elaborated, so @code{Program_Error}
28631 will be raised on the call to @code{A}.
28632 In this case GNAT will generate a
28633 warning that @code{Program_Error} may be
28634 raised at the point of the call. Let's look at the warning:
28635
28636 @smallexample
28637 @group
28638 @cartouche
28639  1. procedure x is
28640  2.    function A return Integer;
28641  3.    function B return Integer;
28642  4.    function C return Integer;
28643  5.
28644  6.    function B return Integer is begin return A; end;
28645                                                     |
28646     >>> warning: call to "A" before body is elaborated may
28647                  raise Program_Error
28648     >>> warning: "B" called at line 7
28649     >>> warning: "C" called at line 9
28650
28651  7.    function C return Integer is begin return B; end;
28652  8.
28653  9.    X : Integer := C;
28654 10.
28655 11.    function A return Integer is begin return 1; end;
28656 12.
28657 13. begin
28658 14.    null;
28659 15. end;
28660 @end cartouche
28661 @end group
28662 @end smallexample
28663
28664 @noindent
28665 Note that the message here says ``may raise'', instead of the direct case,
28666 where the message says ``will be raised''. That's because whether
28667 @code{A} is
28668 actually called depends in general on run-time flow of control.
28669 For example, if the body of @code{B} said
28670
28671 @smallexample @c ada
28672 @group
28673 @cartouche
28674 function B return Integer is
28675 begin
28676    if some-condition-depending-on-input-data then
28677       return A;
28678    else
28679       return 1;
28680    end if;
28681 end B;
28682 @end cartouche
28683 @end group
28684 @end smallexample
28685
28686 @noindent
28687 then we could not know until run time whether the incorrect call to A would
28688 actually occur, so @code{Program_Error} might
28689 or might not be raised. It is possible for a compiler to
28690 do a better job of analyzing bodies, to
28691 determine whether or not @code{Program_Error}
28692 might be raised, but it certainly
28693 couldn't do a perfect job (that would require solving the halting problem
28694 and is provably impossible), and because this is a warning anyway, it does
28695 not seem worth the effort to do the analysis. Cases in which it
28696 would be relevant are rare.
28697
28698 In practice, warnings of either of the forms given
28699 above will usually correspond to
28700 real errors, and should be examined carefully and eliminated.
28701 In the rare case where a warning is bogus, it can be suppressed by any of
28702 the following methods:
28703
28704 @itemize @bullet
28705 @item
28706 Compile with the @option{-gnatws} switch set
28707
28708 @item
28709 Suppress @code{Elaboration_Check} for the called subprogram
28710
28711 @item
28712 Use pragma @code{Warnings_Off} to turn warnings off for the call
28713 @end itemize
28714
28715 @noindent
28716 For the internal elaboration check case,
28717 GNAT by default generates the
28718 necessary run-time checks to ensure
28719 that @code{Program_Error} is raised if any
28720 call fails an elaboration check. Of course this can only happen if a
28721 warning has been issued as described above. The use of pragma
28722 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28723 some of these checks, meaning that it may be possible (but is not
28724 guaranteed) for a program to be able to call a subprogram whose body
28725 is not yet elaborated, without raising a @code{Program_Error} exception.
28726
28727 @node Controlling Elaboration in GNAT - External Calls
28728 @section Controlling Elaboration in GNAT - External Calls
28729
28730 @noindent
28731 The previous section discussed the case in which the execution of a
28732 particular thread of elaboration code occurred entirely within a
28733 single unit. This is the easy case to handle, because a programmer
28734 has direct and total control over the order of elaboration, and
28735 furthermore, checks need only be generated in cases which are rare
28736 and which the compiler can easily detect.
28737 The situation is more complex when separate compilation is taken into account.
28738 Consider the following:
28739
28740 @smallexample @c ada
28741 @cartouche
28742 @group
28743 package Math is
28744    function Sqrt (Arg : Float) return Float;
28745 end Math;
28746
28747 package body Math is
28748    function Sqrt (Arg : Float) return Float is
28749    begin
28750          @dots{}
28751    end Sqrt;
28752 end Math;
28753 @end group
28754 @group
28755 with Math;
28756 package Stuff is
28757    X : Float := Math.Sqrt (0.5);
28758 end Stuff;
28759
28760 with Stuff;
28761 procedure Main is
28762 begin
28763    @dots{}
28764 end Main;
28765 @end group
28766 @end cartouche
28767 @end smallexample
28768
28769 @noindent
28770 where @code{Main} is the main program. When this program is executed, the
28771 elaboration code must first be executed, and one of the jobs of the
28772 binder is to determine the order in which the units of a program are
28773 to be elaborated. In this case we have four units: the spec and body
28774 of @code{Math},
28775 the spec of @code{Stuff} and the body of @code{Main}).
28776 In what order should the four separate sections of elaboration code
28777 be executed?
28778
28779 There are some restrictions in the order of elaboration that the binder
28780 can choose. In particular, if unit U has a @code{with}
28781 for a package @code{X}, then you
28782 are assured that the spec of @code{X}
28783 is elaborated before U , but you are
28784 not assured that the body of @code{X}
28785 is elaborated before U.
28786 This means that in the above case, the binder is allowed to choose the
28787 order:
28788
28789 @smallexample
28790 spec of Math
28791 spec of Stuff
28792 body of Math
28793 body of Main
28794 @end smallexample
28795
28796 @noindent
28797 but that's not good, because now the call to @code{Math.Sqrt}
28798 that happens during
28799 the elaboration of the @code{Stuff}
28800 spec happens before the body of @code{Math.Sqrt} is
28801 elaborated, and hence causes @code{Program_Error} exception to be raised.
28802 At first glance, one might say that the binder is misbehaving, because
28803 obviously you want to elaborate the body of something you @code{with}
28804 first, but
28805 that is not a general rule that can be followed in all cases. Consider
28806
28807 @smallexample @c ada
28808 @group
28809 @cartouche
28810 package X is @dots{}
28811
28812 package Y is @dots{}
28813
28814 with X;
28815 package body Y is @dots{}
28816
28817 with Y;
28818 package body X is @dots{}
28819 @end cartouche
28820 @end group
28821 @end smallexample
28822
28823 @noindent
28824 This is a common arrangement, and, apart from the order of elaboration
28825 problems that might arise in connection with elaboration code, this works fine.
28826 A rule that says that you must first elaborate the body of anything you
28827 @code{with} cannot work in this case:
28828 the body of @code{X} @code{with}'s @code{Y},
28829 which means you would have to
28830 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28831 which means
28832 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28833 loop that cannot be broken.
28834
28835 It is true that the binder can in many cases guess an order of elaboration
28836 that is unlikely to cause a @code{Program_Error}
28837 exception to be raised, and it tries to do so (in the
28838 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28839 by default
28840 elaborate the body of @code{Math} right after its spec, so all will be well).
28841
28842 However, a program that blindly relies on the binder to be helpful can
28843 get into trouble, as we discussed in the previous sections, so
28844 GNAT
28845 provides a number of facilities for assisting the programmer in
28846 developing programs that are robust with respect to elaboration order.
28847
28848 @node Default Behavior in GNAT - Ensuring Safety
28849 @section Default Behavior in GNAT - Ensuring Safety
28850
28851 @noindent
28852 The default behavior in GNAT ensures elaboration safety. In its
28853 default mode GNAT implements the
28854 rule we previously described as the right approach. Let's restate it:
28855
28856 @itemize
28857 @item
28858 @emph{If a unit has elaboration code that can directly or indirectly make a
28859 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28860 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28861 does not have pragma @code{Pure} or
28862 @code{Preelaborate}, then the client should have an
28863 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28864
28865 @emph{In the case of instantiating a generic subprogram, it is always
28866 sufficient to have only an @code{Elaborate} pragma for the
28867 @code{with}'ed unit.}
28868 @end itemize
28869
28870 @noindent
28871 By following this rule a client is assured that calls and instantiations
28872 can be made without risk of an exception.
28873
28874 In this mode GNAT traces all calls that are potentially made from
28875 elaboration code, and puts in any missing implicit @code{Elaborate}
28876 and @code{Elaborate_All} pragmas.
28877 The advantage of this approach is that no elaboration problems
28878 are possible if the binder can find an elaboration order that is
28879 consistent with these implicit @code{Elaborate} and
28880 @code{Elaborate_All} pragmas. The
28881 disadvantage of this approach is that no such order may exist.
28882
28883 If the binder does not generate any diagnostics, then it means that it has
28884 found an elaboration order that is guaranteed to be safe. However, the binder
28885 may still be relying on implicitly generated @code{Elaborate} and
28886 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28887 guaranteed.
28888
28889 If it is important to guarantee portability, then the compilations should
28890 use the
28891 @option{-gnatwl}
28892 (warn on elaboration problems) switch. This will cause warning messages
28893 to be generated indicating the missing @code{Elaborate} and
28894 @code{Elaborate_All} pragmas.
28895 Consider the following source program:
28896
28897 @smallexample @c ada
28898 @group
28899 @cartouche
28900 with k;
28901 package j is
28902   m : integer := k.r;
28903 end;
28904 @end cartouche
28905 @end group
28906 @end smallexample
28907
28908 @noindent
28909 where it is clear that there
28910 should be a pragma @code{Elaborate_All}
28911 for unit @code{k}. An implicit pragma will be generated, and it is
28912 likely that the binder will be able to honor it. However, if you want
28913 to port this program to some other Ada compiler than GNAT.
28914 it is safer to include the pragma explicitly in the source. If this
28915 unit is compiled with the
28916 @option{-gnatwl}
28917 switch, then the compiler outputs a warning:
28918
28919 @smallexample
28920 @group
28921 @cartouche
28922 1. with k;
28923 2. package j is
28924 3.   m : integer := k.r;
28925                      |
28926    >>> warning: call to "r" may raise Program_Error
28927    >>> warning: missing pragma Elaborate_All for "k"
28928
28929 4. end;
28930 @end cartouche
28931 @end group
28932 @end smallexample
28933
28934 @noindent
28935 and these warnings can be used as a guide for supplying manually
28936 the missing pragmas. It is usually a bad idea to use this warning
28937 option during development. That's because it will warn you when
28938 you need to put in a pragma, but cannot warn you when it is time
28939 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28940 unnecessary dependencies and even false circularities.
28941
28942 This default mode is more restrictive than the Ada Reference
28943 Manual, and it is possible to construct programs which will compile
28944 using the dynamic model described there, but will run into a
28945 circularity using the safer static model we have described.
28946
28947 Of course any Ada compiler must be able to operate in a mode
28948 consistent with the requirements of the Ada Reference Manual,
28949 and in particular must have the capability of implementing the
28950 standard dynamic model of elaboration with run-time checks.
28951
28952 In GNAT, this standard mode can be achieved either by the use of
28953 the @option{-gnatE} switch on the compiler (@command{gcc} or
28954 @command{gnatmake}) command, or by the use of the configuration pragma:
28955
28956 @smallexample @c ada
28957 pragma Elaboration_Checks (DYNAMIC);
28958 @end smallexample
28959
28960 @noindent
28961 Either approach will cause the unit affected to be compiled using the
28962 standard dynamic run-time elaboration checks described in the Ada
28963 Reference Manual. The static model is generally preferable, since it
28964 is clearly safer to rely on compile and link time checks rather than
28965 run-time checks. However, in the case of legacy code, it may be
28966 difficult to meet the requirements of the static model. This
28967 issue is further discussed in
28968 @ref{What to Do If the Default Elaboration Behavior Fails}.
28969
28970 Note that the static model provides a strict subset of the allowed
28971 behavior and programs of the Ada Reference Manual, so if you do
28972 adhere to the static model and no circularities exist,
28973 then you are assured that your program will
28974 work using the dynamic model, providing that you remove any
28975 pragma Elaborate statements from the source.
28976
28977 @node Treatment of Pragma Elaborate
28978 @section Treatment of Pragma Elaborate
28979 @cindex Pragma Elaborate
28980
28981 @noindent
28982 The use of @code{pragma Elaborate}
28983 should generally be avoided in Ada 95 and Ada 2005 programs,
28984 since there is no guarantee that transitive calls
28985 will be properly handled. Indeed at one point, this pragma was placed
28986 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28987
28988 Now that's a bit restrictive. In practice, the case in which
28989 @code{pragma Elaborate} is useful is when the caller knows that there
28990 are no transitive calls, or that the called unit contains all necessary
28991 transitive @code{pragma Elaborate} statements, and legacy code often
28992 contains such uses.
28993
28994 Strictly speaking the static mode in GNAT should ignore such pragmas,
28995 since there is no assurance at compile time that the necessary safety
28996 conditions are met. In practice, this would cause GNAT to be incompatible
28997 with correctly written Ada 83 code that had all necessary
28998 @code{pragma Elaborate} statements in place. Consequently, we made the
28999 decision that GNAT in its default mode will believe that if it encounters
29000 a @code{pragma Elaborate} then the programmer knows what they are doing,
29001 and it will trust that no elaboration errors can occur.
29002
29003 The result of this decision is two-fold. First to be safe using the
29004 static mode, you should remove all @code{pragma Elaborate} statements.
29005 Second, when fixing circularities in existing code, you can selectively
29006 use @code{pragma Elaborate} statements to convince the static mode of
29007 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
29008 statement.
29009
29010 When using the static mode with @option{-gnatwl}, any use of
29011 @code{pragma Elaborate} will generate a warning about possible
29012 problems.
29013
29014 @node Elaboration Issues for Library Tasks
29015 @section Elaboration Issues for Library Tasks
29016 @cindex Library tasks, elaboration issues
29017 @cindex Elaboration of library tasks
29018
29019 @noindent
29020 In this section we examine special elaboration issues that arise for
29021 programs that declare library level tasks.
29022
29023 Generally the model of execution of an Ada program is that all units are
29024 elaborated, and then execution of the program starts. However, the
29025 declaration of library tasks definitely does not fit this model. The
29026 reason for this is that library tasks start as soon as they are declared
29027 (more precisely, as soon as the statement part of the enclosing package
29028 body is reached), that is to say before elaboration
29029 of the program is complete. This means that if such a task calls a
29030 subprogram, or an entry in another task, the callee may or may not be
29031 elaborated yet, and in the standard
29032 Reference Manual model of dynamic elaboration checks, you can even
29033 get timing dependent Program_Error exceptions, since there can be
29034 a race between the elaboration code and the task code.
29035
29036 The static model of elaboration in GNAT seeks to avoid all such
29037 dynamic behavior, by being conservative, and the conservative
29038 approach in this particular case is to assume that all the code
29039 in a task body is potentially executed at elaboration time if
29040 a task is declared at the library level.
29041
29042 This can definitely result in unexpected circularities. Consider
29043 the following example
29044
29045 @smallexample @c ada
29046 package Decls is
29047   task Lib_Task is
29048      entry Start;
29049   end Lib_Task;
29050
29051   type My_Int is new Integer;
29052
29053   function Ident (M : My_Int) return My_Int;
29054 end Decls;
29055
29056 with Utils;
29057 package body Decls is
29058   task body Lib_Task is
29059   begin
29060      accept Start;
29061      Utils.Put_Val (2);
29062   end Lib_Task;
29063
29064   function Ident (M : My_Int) return My_Int is
29065   begin
29066      return M;
29067   end Ident;
29068 end Decls;
29069
29070 with Decls;
29071 package Utils is
29072   procedure Put_Val (Arg : Decls.My_Int);
29073 end Utils;
29074
29075 with Text_IO;
29076 package body Utils is
29077   procedure Put_Val (Arg : Decls.My_Int) is
29078   begin
29079      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29080   end Put_Val;
29081 end Utils;
29082
29083 with Decls;
29084 procedure Main is
29085 begin
29086    Decls.Lib_Task.Start;
29087 end;
29088 @end smallexample
29089
29090 @noindent
29091 If the above example is compiled in the default static elaboration
29092 mode, then a circularity occurs. The circularity comes from the call
29093 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
29094 this call occurs in elaboration code, we need an implicit pragma
29095 @code{Elaborate_All} for @code{Utils}. This means that not only must
29096 the spec and body of @code{Utils} be elaborated before the body
29097 of @code{Decls}, but also the spec and body of any unit that is
29098 @code{with'ed} by the body of @code{Utils} must also be elaborated before
29099 the body of @code{Decls}. This is the transitive implication of
29100 pragma @code{Elaborate_All} and it makes sense, because in general
29101 the body of @code{Put_Val} might have a call to something in a
29102 @code{with'ed} unit.
29103
29104 In this case, the body of Utils (actually its spec) @code{with's}
29105 @code{Decls}. Unfortunately this means that the body of @code{Decls}
29106 must be elaborated before itself, in case there is a call from the
29107 body of @code{Utils}.
29108
29109 Here is the exact chain of events we are worrying about:
29110
29111 @enumerate
29112 @item
29113 In the body of @code{Decls} a call is made from within the body of a library
29114 task to a subprogram in the package @code{Utils}. Since this call may
29115 occur at elaboration time (given that the task is activated at elaboration
29116 time), we have to assume the worst, i.e., that the
29117 call does happen at elaboration time.
29118
29119 @item
29120 This means that the body and spec of @code{Util} must be elaborated before
29121 the body of @code{Decls} so that this call does not cause an access before
29122 elaboration.
29123
29124 @item
29125 Within the body of @code{Util}, specifically within the body of
29126 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
29127 by this package.
29128
29129 @item
29130 One such @code{with}'ed package is package @code{Decls}, so there
29131 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
29132 In fact there is such a call in this example, but we would have to
29133 assume that there was such a call even if it were not there, since
29134 we are not supposed to write the body of @code{Decls} knowing what
29135 is in the body of @code{Utils}; certainly in the case of the
29136 static elaboration model, the compiler does not know what is in
29137 other bodies and must assume the worst.
29138
29139 @item
29140 This means that the spec and body of @code{Decls} must also be
29141 elaborated before we elaborate the unit containing the call, but
29142 that unit is @code{Decls}! This means that the body of @code{Decls}
29143 must be elaborated before itself, and that's a circularity.
29144 @end enumerate
29145
29146 @noindent
29147 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
29148 the body of @code{Decls} you will get a true Ada Reference Manual
29149 circularity that makes the program illegal.
29150
29151 In practice, we have found that problems with the static model of
29152 elaboration in existing code often arise from library tasks, so
29153 we must address this particular situation.
29154
29155 Note that if we compile and run the program above, using the dynamic model of
29156 elaboration (that is to say use the @option{-gnatE} switch),
29157 then it compiles, binds,
29158 links, and runs, printing the expected result of 2. Therefore in some sense
29159 the circularity here is only apparent, and we need to capture
29160 the properties of this program that  distinguish it from other library-level
29161 tasks that have real elaboration problems.
29162
29163 We have four possible answers to this question:
29164
29165 @itemize @bullet
29166
29167 @item
29168 Use the dynamic model of elaboration.
29169
29170 If we use the @option{-gnatE} switch, then as noted above, the program works.
29171 Why is this? If we examine the task body, it is apparent that the task cannot
29172 proceed past the
29173 @code{accept} statement until after elaboration has been completed, because
29174 the corresponding entry call comes from the main program, not earlier.
29175 This is why the dynamic model works here. But that's really giving
29176 up on a precise analysis, and we prefer to take this approach only if we cannot
29177 solve the
29178 problem in any other manner. So let us examine two ways to reorganize
29179 the program to avoid the potential elaboration problem.
29180
29181 @item
29182 Split library tasks into separate packages.
29183
29184 Write separate packages, so that library tasks are isolated from
29185 other declarations as much as possible. Let us look at a variation on
29186 the above program.
29187
29188 @smallexample @c ada
29189 package Decls1 is
29190   task Lib_Task is
29191      entry Start;
29192   end Lib_Task;
29193 end Decls1;
29194
29195 with Utils;
29196 package body Decls1 is
29197   task body Lib_Task is
29198   begin
29199      accept Start;
29200      Utils.Put_Val (2);
29201   end Lib_Task;
29202 end Decls1;
29203
29204 package Decls2 is
29205   type My_Int is new Integer;
29206   function Ident (M : My_Int) return My_Int;
29207 end Decls2;
29208
29209 with Utils;
29210 package body Decls2 is
29211   function Ident (M : My_Int) return My_Int is
29212   begin
29213      return M;
29214   end Ident;
29215 end Decls2;
29216
29217 with Decls2;
29218 package Utils is
29219   procedure Put_Val (Arg : Decls2.My_Int);
29220 end Utils;
29221
29222 with Text_IO;
29223 package body Utils is
29224   procedure Put_Val (Arg : Decls2.My_Int) is
29225   begin
29226      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
29227   end Put_Val;
29228 end Utils;
29229
29230 with Decls1;
29231 procedure Main is
29232 begin
29233    Decls1.Lib_Task.Start;
29234 end;
29235 @end smallexample
29236
29237 @noindent
29238 All we have done is to split @code{Decls} into two packages, one
29239 containing the library task, and one containing everything else. Now
29240 there is no cycle, and the program compiles, binds, links and executes
29241 using the default static model of elaboration.
29242
29243 @item
29244 Declare separate task types.
29245
29246 A significant part of the problem arises because of the use of the
29247 single task declaration form. This means that the elaboration of
29248 the task type, and the elaboration of the task itself (i.e.@: the
29249 creation of the task) happen at the same time. A good rule
29250 of style in Ada is to always create explicit task types. By
29251 following the additional step of placing task objects in separate
29252 packages from the task type declaration, many elaboration problems
29253 are avoided. Here is another modified example of the example program:
29254
29255 @smallexample @c ada
29256 package Decls is
29257   task type Lib_Task_Type is
29258      entry Start;
29259   end Lib_Task_Type;
29260
29261   type My_Int is new Integer;
29262
29263   function Ident (M : My_Int) return My_Int;
29264 end Decls;
29265
29266 with Utils;
29267 package body Decls is
29268   task body Lib_Task_Type is
29269   begin
29270      accept Start;
29271      Utils.Put_Val (2);
29272   end Lib_Task_Type;
29273
29274   function Ident (M : My_Int) return My_Int is
29275   begin
29276      return M;
29277   end Ident;
29278 end Decls;
29279
29280 with Decls;
29281 package Utils is
29282   procedure Put_Val (Arg : Decls.My_Int);
29283 end Utils;
29284
29285 with Text_IO;
29286 package body Utils is
29287   procedure Put_Val (Arg : Decls.My_Int) is
29288   begin
29289      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29290   end Put_Val;
29291 end Utils;
29292
29293 with Decls;
29294 package Declst is
29295    Lib_Task : Decls.Lib_Task_Type;
29296 end Declst;
29297
29298 with Declst;
29299 procedure Main is
29300 begin
29301    Declst.Lib_Task.Start;
29302 end;
29303 @end smallexample
29304
29305 @noindent
29306 What we have done here is to replace the @code{task} declaration in
29307 package @code{Decls} with a @code{task type} declaration. Then we
29308 introduce a separate package @code{Declst} to contain the actual
29309 task object. This separates the elaboration issues for
29310 the @code{task type}
29311 declaration, which causes no trouble, from the elaboration issues
29312 of the task object, which is also unproblematic, since it is now independent
29313 of the elaboration of  @code{Utils}.
29314 This separation of concerns also corresponds to
29315 a generally sound engineering principle of separating declarations
29316 from instances. This version of the program also compiles, binds, links,
29317 and executes, generating the expected output.
29318
29319 @item
29320 Use No_Entry_Calls_In_Elaboration_Code restriction.
29321 @cindex No_Entry_Calls_In_Elaboration_Code
29322
29323 The previous two approaches described how a program can be restructured
29324 to avoid the special problems caused by library task bodies. in practice,
29325 however, such restructuring may be difficult to apply to existing legacy code,
29326 so we must consider solutions that do not require massive rewriting.
29327
29328 Let us consider more carefully why our original sample program works
29329 under the dynamic model of elaboration. The reason is that the code
29330 in the task body blocks immediately on the @code{accept}
29331 statement. Now of course there is nothing to prohibit elaboration
29332 code from making entry calls (for example from another library level task),
29333 so we cannot tell in isolation that
29334 the task will not execute the accept statement  during elaboration.
29335
29336 However, in practice it is very unusual to see elaboration code
29337 make any entry calls, and the pattern of tasks starting
29338 at elaboration time and then immediately blocking on @code{accept} or
29339 @code{select} statements is very common. What this means is that
29340 the compiler is being too pessimistic when it analyzes the
29341 whole package body as though it might be executed at elaboration
29342 time.
29343
29344 If we know that the elaboration code contains no entry calls, (a very safe
29345 assumption most of the time, that could almost be made the default
29346 behavior), then we can compile all units of the program under control
29347 of the following configuration pragma:
29348
29349 @smallexample
29350 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29351 @end smallexample
29352
29353 @noindent
29354 This pragma can be placed in the @file{gnat.adc} file in the usual
29355 manner. If we take our original unmodified program and compile it
29356 in the presence of a @file{gnat.adc} containing the above pragma,
29357 then once again, we can compile, bind, link, and execute, obtaining
29358 the expected result. In the presence of this pragma, the compiler does
29359 not trace calls in a task body, that appear after the first @code{accept}
29360 or @code{select} statement, and therefore does not report a potential
29361 circularity in the original program.
29362
29363 The compiler will check to the extent it can that the above
29364 restriction is not violated, but it is not always possible to do a
29365 complete check at compile time, so it is important to use this
29366 pragma only if the stated restriction is in fact met, that is to say
29367 no task receives an entry call before elaboration of all units is completed.
29368
29369 @end itemize
29370
29371 @node Mixing Elaboration Models
29372 @section Mixing Elaboration Models
29373 @noindent
29374 So far, we have assumed that the entire program is either compiled
29375 using the dynamic model or static model, ensuring consistency. It
29376 is possible to mix the two models, but rules have to be followed
29377 if this mixing is done to ensure that elaboration checks are not
29378 omitted.
29379
29380 The basic rule is that @emph{a unit compiled with the static model cannot
29381 be @code{with'ed} by a unit compiled with the dynamic model}. The
29382 reason for this is that in the static model, a unit assumes that
29383 its clients guarantee to use (the equivalent of) pragma
29384 @code{Elaborate_All} so that no elaboration checks are required
29385 in inner subprograms, and this assumption is violated if the
29386 client is compiled with dynamic checks.
29387
29388 The precise rule is as follows. A unit that is compiled with dynamic
29389 checks can only @code{with} a unit that meets at least one of the
29390 following criteria:
29391
29392 @itemize @bullet
29393
29394 @item
29395 The @code{with'ed} unit is itself compiled with dynamic elaboration
29396 checks (that is with the @option{-gnatE} switch.
29397
29398 @item
29399 The @code{with'ed} unit is an internal GNAT implementation unit from
29400 the System, Interfaces, Ada, or GNAT hierarchies.
29401
29402 @item
29403 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29404
29405 @item
29406 The @code{with'ing} unit (that is the client) has an explicit pragma
29407 @code{Elaborate_All} for the @code{with'ed} unit.
29408
29409 @end itemize
29410
29411 @noindent
29412 If this rule is violated, that is if a unit with dynamic elaboration
29413 checks @code{with's} a unit that does not meet one of the above four
29414 criteria, then the binder (@code{gnatbind}) will issue a warning
29415 similar to that in the following example:
29416
29417 @smallexample
29418 warning: "x.ads" has dynamic elaboration checks and with's
29419 warning:   "y.ads" which has static elaboration checks
29420 @end smallexample
29421
29422 @noindent
29423 These warnings indicate that the rule has been violated, and that as a result
29424 elaboration checks may be missed in the resulting executable file.
29425 This warning may be suppressed using the @option{-ws} binder switch
29426 in the usual manner.
29427
29428 One useful application of this mixing rule is in the case of a subsystem
29429 which does not itself @code{with} units from the remainder of the
29430 application. In this case, the entire subsystem can be compiled with
29431 dynamic checks to resolve a circularity in the subsystem, while
29432 allowing the main application that uses this subsystem to be compiled
29433 using the more reliable default static model.
29434
29435 @node What to Do If the Default Elaboration Behavior Fails
29436 @section What to Do If the Default Elaboration Behavior Fails
29437
29438 @noindent
29439 If the binder cannot find an acceptable order, it outputs detailed
29440 diagnostics. For example:
29441 @smallexample
29442 @group
29443 @iftex
29444 @leftskip=0cm
29445 @end iftex
29446 error: elaboration circularity detected
29447 info:   "proc (body)" must be elaborated before "pack (body)"
29448 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29449 info:     recompile "pack (body)" with -gnatwl
29450 info:                             for full details
29451 info:       "proc (body)"
29452 info:         is needed by its spec:
29453 info:       "proc (spec)"
29454 info:         which is withed by:
29455 info:       "pack (body)"
29456 info:  "pack (body)" must be elaborated before "proc (body)"
29457 info:     reason: pragma Elaborate in unit "proc (body)"
29458 @end group
29459
29460 @end smallexample
29461
29462 @noindent
29463 In this case we have a cycle that the binder cannot break. On the one
29464 hand, there is an explicit pragma Elaborate in @code{proc} for
29465 @code{pack}. This means that the body of @code{pack} must be elaborated
29466 before the body of @code{proc}. On the other hand, there is elaboration
29467 code in @code{pack} that calls a subprogram in @code{proc}. This means
29468 that for maximum safety, there should really be a pragma
29469 Elaborate_All in @code{pack} for @code{proc} which would require that
29470 the body of @code{proc} be elaborated before the body of
29471 @code{pack}. Clearly both requirements cannot be satisfied.
29472 Faced with a circularity of this kind, you have three different options.
29473
29474 @table @asis
29475 @item Fix the program
29476 The most desirable option from the point of view of long-term maintenance
29477 is to rearrange the program so that the elaboration problems are avoided.
29478 One useful technique is to place the elaboration code into separate
29479 child packages. Another is to move some of the initialization code to
29480 explicitly called subprograms, where the program controls the order
29481 of initialization explicitly. Although this is the most desirable option,
29482 it may be impractical and involve too much modification, especially in
29483 the case of complex legacy code.
29484
29485 @item Perform dynamic checks
29486 If the compilations are done using the
29487 @option{-gnatE}
29488 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29489 manner. Dynamic checks are generated for all calls that could possibly result
29490 in raising an exception. With this switch, the compiler does not generate
29491 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29492 exactly as specified in the @cite{Ada Reference Manual}.
29493 The binder will generate
29494 an executable program that may or may not raise @code{Program_Error}, and then
29495 it is the programmer's job to ensure that it does not raise an exception. Note
29496 that it is important to compile all units with the switch, it cannot be used
29497 selectively.
29498
29499 @item Suppress checks
29500 The drawback of dynamic checks is that they generate a
29501 significant overhead at run time, both in space and time. If you
29502 are absolutely sure that your program cannot raise any elaboration
29503 exceptions, and you still want to use the dynamic elaboration model,
29504 then you can use the configuration pragma
29505 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29506 example this pragma could be placed in the @file{gnat.adc} file.
29507
29508 @item Suppress checks selectively
29509 When you know that certain calls or instantiations in elaboration code cannot
29510 possibly lead to an elaboration error, and the binder nevertheless complains
29511 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29512 elaboration circularities, it is possible to remove those warnings locally and
29513 obtain a program that will bind. Clearly this can be unsafe, and it is the
29514 responsibility of the programmer to make sure that the resulting program has no
29515 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29516 used with different granularity to suppress warnings and break elaboration
29517 circularities:
29518
29519 @itemize @bullet
29520 @item
29521 Place the pragma that names the called subprogram in the declarative part
29522 that contains the call.
29523
29524 @item
29525 Place the pragma in the declarative part, without naming an entity. This
29526 disables warnings on all calls in the corresponding  declarative region.
29527
29528 @item
29529 Place the pragma in the package spec that declares the called subprogram,
29530 and name the subprogram. This disables warnings on all elaboration calls to
29531 that subprogram.
29532
29533 @item
29534 Place the pragma in the package spec that declares the called subprogram,
29535 without naming any entity. This disables warnings on all elaboration calls to
29536 all subprograms declared in this spec.
29537
29538 @item Use Pragma Elaborate
29539 As previously described in section @xref{Treatment of Pragma Elaborate},
29540 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29541 that no elaboration checks are required on calls to the designated unit.
29542 There may be cases in which the caller knows that no transitive calls
29543 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29544 case where @code{pragma Elaborate_All} would cause a circularity.
29545 @end itemize
29546
29547 @noindent
29548 These five cases are listed in order of decreasing safety, and therefore
29549 require increasing programmer care in their application. Consider the
29550 following program:
29551
29552 @smallexample @c adanocomment
29553 package Pack1 is
29554   function F1 return Integer;
29555   X1 : Integer;
29556 end Pack1;
29557
29558 package Pack2 is
29559   function F2 return Integer;
29560   function Pure (x : integer) return integer;
29561   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29562   --  pragma Suppress (Elaboration_Check);              -- (4)
29563 end Pack2;
29564
29565 with Pack2;
29566 package body Pack1 is
29567   function F1 return Integer is
29568   begin
29569     return 100;
29570   end F1;
29571   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29572 begin
29573   declare
29574     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29575     --  pragma Suppress(Elaboration_Check);             -- (2)
29576   begin
29577     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29578   end;
29579 end Pack1;
29580
29581 with Pack1;
29582 package body Pack2 is
29583   function F2 return Integer is
29584   begin
29585      return Pack1.F1;
29586   end F2;
29587   function Pure (x : integer) return integer is
29588   begin
29589      return x ** 3 - 3 * x;
29590   end;
29591 end Pack2;
29592
29593 with Pack1, Ada.Text_IO;
29594 procedure Proc3 is
29595 begin
29596   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29597 end Proc3;
29598 @end smallexample
29599 In the absence of any pragmas, an attempt to bind this program produces
29600 the following diagnostics:
29601 @smallexample
29602 @group
29603 @iftex
29604 @leftskip=.5cm
29605 @end iftex
29606 error: elaboration circularity detected
29607 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29608 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29609 info:       recompile "pack1 (body)" with -gnatwl for full details
29610 info:          "pack1 (body)"
29611 info:             must be elaborated along with its spec:
29612 info:          "pack1 (spec)"
29613 info:             which is withed by:
29614 info:          "pack2 (body)"
29615 info:             which must be elaborated along with its spec:
29616 info:          "pack2 (spec)"
29617 info:             which is withed by:
29618 info:          "pack1 (body)"
29619 @end group
29620 @end smallexample
29621 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29622 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29623 F2 is safe, even though F2 calls F1, because the call appears after the
29624 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29625 remove the warning on the call. It is also possible to use pragma (2)
29626 because there are no other potentially unsafe calls in the block.
29627
29628 @noindent
29629 The call to @code{Pure} is safe because this function does not depend on the
29630 state of @code{Pack2}. Therefore any call to this function is safe, and it
29631 is correct to place pragma (3) in the corresponding package spec.
29632
29633 @noindent
29634 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29635 warnings on all calls to functions declared therein. Note that this is not
29636 necessarily safe, and requires more detailed examination of the subprogram
29637 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29638 be already elaborated.
29639 @end table
29640
29641 @noindent
29642 It is hard to generalize on which of these four approaches should be
29643 taken. Obviously if it is possible to fix the program so that the default
29644 treatment works, this is preferable, but this may not always be practical.
29645 It is certainly simple enough to use
29646 @option{-gnatE}
29647 but the danger in this case is that, even if the GNAT binder
29648 finds a correct elaboration order, it may not always do so,
29649 and certainly a binder from another Ada compiler might not. A
29650 combination of testing and analysis (for which the warnings generated
29651 with the
29652 @option{-gnatwl}
29653 switch can be useful) must be used to ensure that the program is free
29654 of errors. One switch that is useful in this testing is the
29655 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29656 switch for
29657 @code{gnatbind}.
29658 Normally the binder tries to find an order that has the best chance
29659 of avoiding elaboration problems. However, if this switch is used, the binder
29660 plays a devil's advocate role, and tries to choose the order that
29661 has the best chance of failing. If your program works even with this
29662 switch, then it has a better chance of being error free, but this is still
29663 not a guarantee.
29664
29665 For an example of this approach in action, consider the C-tests (executable
29666 tests) from the ACVC suite. If these are compiled and run with the default
29667 treatment, then all but one of them succeed without generating any error
29668 diagnostics from the binder. However, there is one test that fails, and
29669 this is not surprising, because the whole point of this test is to ensure
29670 that the compiler can handle cases where it is impossible to determine
29671 a correct order statically, and it checks that an exception is indeed
29672 raised at run time.
29673
29674 This one test must be compiled and run using the
29675 @option{-gnatE}
29676 switch, and then it passes. Alternatively, the entire suite can
29677 be run using this switch. It is never wrong to run with the dynamic
29678 elaboration switch if your code is correct, and we assume that the
29679 C-tests are indeed correct (it is less efficient, but efficiency is
29680 not a factor in running the ACVC tests.)
29681
29682 @node Elaboration for Access-to-Subprogram Values
29683 @section Elaboration for Access-to-Subprogram Values
29684 @cindex Access-to-subprogram
29685
29686 @noindent
29687 Access-to-subprogram types (introduced in Ada 95) complicate
29688 the handling of elaboration. The trouble is that it becomes
29689 impossible to tell at compile time which procedure
29690 is being called. This means that it is not possible for the binder
29691 to analyze the elaboration requirements in this case.
29692
29693 If at the point at which the access value is created
29694 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29695 the body of the subprogram is
29696 known to have been elaborated, then the access value is safe, and its use
29697 does not require a check. This may be achieved by appropriate arrangement
29698 of the order of declarations if the subprogram is in the current unit,
29699 or, if the subprogram is in another unit, by using pragma
29700 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29701 on the referenced unit.
29702
29703 If the referenced body is not known to have been elaborated at the point
29704 the access value is created, then any use of the access value must do a
29705 dynamic check, and this dynamic check will fail and raise a
29706 @code{Program_Error} exception if the body has not been elaborated yet.
29707 GNAT will generate the necessary checks, and in addition, if the
29708 @option{-gnatwl}
29709 switch is set, will generate warnings that such checks are required.
29710
29711 The use of dynamic dispatching for tagged types similarly generates
29712 a requirement for dynamic checks, and premature calls to any primitive
29713 operation of a tagged type before the body of the operation has been
29714 elaborated, will result in the raising of @code{Program_Error}.
29715
29716 @node Summary of Procedures for Elaboration Control
29717 @section Summary of Procedures for Elaboration Control
29718 @cindex Elaboration control
29719
29720 @noindent
29721 First, compile your program with the default options, using none of
29722 the special elaboration control switches. If the binder successfully
29723 binds your program, then you can be confident that, apart from issues
29724 raised by the use of access-to-subprogram types and dynamic dispatching,
29725 the program is free of elaboration errors. If it is important that the
29726 program be portable, then use the
29727 @option{-gnatwl}
29728 switch to generate warnings about missing @code{Elaborate} or
29729 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29730
29731 If the program fails to bind using the default static elaboration
29732 handling, then you can fix the program to eliminate the binder
29733 message, or recompile the entire program with the
29734 @option{-gnatE} switch to generate dynamic elaboration checks,
29735 and, if you are sure there really are no elaboration problems,
29736 use a global pragma @code{Suppress (Elaboration_Check)}.
29737
29738 @node Other Elaboration Order Considerations
29739 @section Other Elaboration Order Considerations
29740 @noindent
29741 This section has been entirely concerned with the issue of finding a valid
29742 elaboration order, as defined by the Ada Reference Manual. In a case
29743 where several elaboration orders are valid, the task is to find one
29744 of the possible valid elaboration orders (and the static model in GNAT
29745 will ensure that this is achieved).
29746
29747 The purpose of the elaboration rules in the Ada Reference Manual is to
29748 make sure that no entity is accessed before it has been elaborated. For
29749 a subprogram, this means that the spec and body must have been elaborated
29750 before the subprogram is called. For an object, this means that the object
29751 must have been elaborated before its value is read or written. A violation
29752 of either of these two requirements is an access before elaboration order,
29753 and this section has been all about avoiding such errors.
29754
29755 In the case where more than one order of elaboration is possible, in the
29756 sense that access before elaboration errors are avoided, then any one of
29757 the orders is ``correct'' in the sense that it meets the requirements of
29758 the Ada Reference Manual, and no such error occurs.
29759
29760 However, it may be the case for a given program, that there are
29761 constraints on the order of elaboration that come not from consideration
29762 of avoiding elaboration errors, but rather from extra-lingual logic
29763 requirements. Consider this example:
29764
29765 @smallexample @c ada
29766 with Init_Constants;
29767 package Constants is
29768    X : Integer := 0;
29769    Y : Integer := 0;
29770 end Constants;
29771
29772 package Init_Constants is
29773    procedure P; -- require a body
29774 end Init_Constants;
29775
29776 with Constants;
29777 package body Init_Constants is
29778    procedure P is begin null; end;
29779 begin
29780    Constants.X := 3;
29781    Constants.Y := 4;
29782 end Init_Constants;
29783
29784 with Constants;
29785 package Calc is
29786    Z : Integer := Constants.X + Constants.Y;
29787 end Calc;
29788
29789 with Calc;
29790 with Text_IO; use Text_IO;
29791 procedure Main is
29792 begin
29793    Put_Line (Calc.Z'Img);
29794 end Main;
29795 @end smallexample
29796
29797 @noindent
29798 In this example, there is more than one valid order of elaboration. For
29799 example both the following are correct orders:
29800
29801 @smallexample
29802 Init_Constants spec
29803 Constants spec
29804 Calc spec
29805 Init_Constants body
29806 Main body
29807
29808   and
29809
29810 Init_Constants spec
29811 Init_Constants body
29812 Constants spec
29813 Calc spec
29814 Main body
29815 @end smallexample
29816
29817 @noindent
29818 There is no language rule to prefer one or the other, both are correct
29819 from an order of elaboration point of view. But the programmatic effects
29820 of the two orders are very different. In the first, the elaboration routine
29821 of @code{Calc} initializes @code{Z} to zero, and then the main program
29822 runs with this value of zero. But in the second order, the elaboration
29823 routine of @code{Calc} runs after the body of Init_Constants has set
29824 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29825 runs.
29826
29827 One could perhaps by applying pretty clever non-artificial intelligence
29828 to the situation guess that it is more likely that the second order of
29829 elaboration is the one desired, but there is no formal linguistic reason
29830 to prefer one over the other. In fact in this particular case, GNAT will
29831 prefer the second order, because of the rule that bodies are elaborated
29832 as soon as possible, but it's just luck that this is what was wanted
29833 (if indeed the second order was preferred).
29834
29835 If the program cares about the order of elaboration routines in a case like
29836 this, it is important to specify the order required. In this particular
29837 case, that could have been achieved by adding to the spec of Calc:
29838
29839 @smallexample @c ada
29840 pragma Elaborate_All (Constants);
29841 @end smallexample
29842
29843 @noindent
29844 which requires that the body (if any) and spec of @code{Constants},
29845 as well as the body and spec of any unit @code{with}'ed by
29846 @code{Constants} be elaborated before @code{Calc} is elaborated.
29847
29848 Clearly no automatic method can always guess which alternative you require,
29849 and if you are working with legacy code that had constraints of this kind
29850 which were not properly specified by adding @code{Elaborate} or
29851 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29852 compilers can choose different orders.
29853
29854 However, GNAT does attempt to diagnose the common situation where there
29855 are uninitialized variables in the visible part of a package spec, and the
29856 corresponding package body has an elaboration block that directly or
29857 indirectly initialized one or more of these variables. This is the situation
29858 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29859 a warning that suggests this addition if it detects this situation.
29860
29861 The @code{gnatbind}
29862 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29863 out problems. This switch causes bodies to be elaborated as late as possible
29864 instead of as early as possible. In the example above, it would have forced
29865 the choice of the first elaboration order. If you get different results
29866 when using this switch, and particularly if one set of results is right,
29867 and one is wrong as far as you are concerned, it shows that you have some
29868 missing @code{Elaborate} pragmas. For the example above, we have the
29869 following output:
29870
29871 @smallexample
29872 gnatmake -f -q main
29873 main
29874  7
29875 gnatmake -f -q main -bargs -p
29876 main
29877  0
29878 @end smallexample
29879
29880 @noindent
29881 It is of course quite unlikely that both these results are correct, so
29882 it is up to you in a case like this to investigate the source of the
29883 difference, by looking at the two elaboration orders that are chosen,
29884 and figuring out which is correct, and then adding the necessary
29885 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29886
29887
29888
29889 @c *******************************
29890 @node Conditional Compilation
29891 @appendix Conditional Compilation
29892 @c *******************************
29893 @cindex Conditional compilation
29894
29895 @noindent
29896 It is often necessary to arrange for a single source program
29897 to serve multiple purposes, where it is compiled in different
29898 ways to achieve these different goals. Some examples of the
29899 need for this feature are
29900
29901 @itemize @bullet
29902 @item  Adapting a program to a different hardware environment
29903 @item  Adapting a program to a different target architecture
29904 @item  Turning debugging features on and off
29905 @item  Arranging for a program to compile with different compilers
29906 @end itemize
29907
29908 @noindent
29909 In C, or C++, the typical approach would be to use the preprocessor
29910 that is defined as part of the language. The Ada language does not
29911 contain such a feature. This is not an oversight, but rather a very
29912 deliberate design decision, based on the experience that overuse of
29913 the preprocessing features in C and C++ can result in programs that
29914 are extremely difficult to maintain. For example, if we have ten
29915 switches that can be on or off, this means that there are a thousand
29916 separate programs, any one of which might not even be syntactically
29917 correct, and even if syntactically correct, the resulting program
29918 might not work correctly. Testing all combinations can quickly become
29919 impossible.
29920
29921 Nevertheless, the need to tailor programs certainly exists, and in
29922 this Appendix we will discuss how this can
29923 be achieved using Ada in general, and GNAT in particular.
29924
29925 @menu
29926 * Use of Boolean Constants::
29927 * Debugging - A Special Case::
29928 * Conditionalizing Declarations::
29929 * Use of Alternative Implementations::
29930 * Preprocessing::
29931 @end menu
29932
29933 @node Use of Boolean Constants
29934 @section Use of Boolean Constants
29935
29936 @noindent
29937 In the case where the difference is simply which code
29938 sequence is executed, the cleanest solution is to use Boolean
29939 constants to control which code is executed.
29940
29941 @smallexample @c ada
29942 @group
29943 FP_Initialize_Required : constant Boolean := True;
29944 @dots{}
29945 if FP_Initialize_Required then
29946 @dots{}
29947 end if;
29948 @end group
29949 @end smallexample
29950
29951 @noindent
29952 Not only will the code inside the @code{if} statement not be executed if
29953 the constant Boolean is @code{False}, but it will also be completely
29954 deleted from the program.
29955 However, the code is only deleted after the @code{if} statement
29956 has been checked for syntactic and semantic correctness.
29957 (In contrast, with preprocessors the code is deleted before the
29958 compiler ever gets to see it, so it is not checked until the switch
29959 is turned on.)
29960 @cindex Preprocessors (contrasted with conditional compilation)
29961
29962 Typically the Boolean constants will be in a separate package,
29963 something like:
29964
29965 @smallexample @c ada
29966 @group
29967 package Config is
29968    FP_Initialize_Required : constant Boolean := True;
29969    Reset_Available        : constant Boolean := False;
29970    @dots{}
29971 end Config;
29972 @end group
29973 @end smallexample
29974
29975 @noindent
29976 The @code{Config} package exists in multiple forms for the various targets,
29977 with an appropriate script selecting the version of @code{Config} needed.
29978 Then any other unit requiring conditional compilation can do a @code{with}
29979 of @code{Config} to make the constants visible.
29980
29981
29982 @node Debugging - A Special Case
29983 @section Debugging - A Special Case
29984
29985 @noindent
29986 A common use of conditional code is to execute statements (for example
29987 dynamic checks, or output of intermediate results) under control of a
29988 debug switch, so that the debugging behavior can be turned on and off.
29989 This can be done using a Boolean constant to control whether the code
29990 is active:
29991
29992 @smallexample @c ada
29993 @group
29994 if Debugging then
29995    Put_Line ("got to the first stage!");
29996 end if;
29997 @end group
29998 @end smallexample
29999
30000 @noindent
30001 or
30002
30003 @smallexample @c ada
30004 @group
30005 if Debugging and then Temperature > 999.0 then
30006    raise Temperature_Crazy;
30007 end if;
30008 @end group
30009 @end smallexample
30010
30011 @noindent
30012 Since this is a common case, there are special features to deal with
30013 this in a convenient manner. For the case of tests, Ada 2005 has added
30014 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
30015 @cindex pragma @code{Assert}
30016 on the @code{Assert} pragma that has always been available in GNAT, so this
30017 feature may be used with GNAT even if you are not using Ada 2005 features.
30018 The use of pragma @code{Assert} is described in
30019 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
30020 example, the last test could be written:
30021
30022 @smallexample @c ada
30023 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
30024 @end smallexample
30025
30026 @noindent
30027 or simply
30028
30029 @smallexample @c ada
30030 pragma Assert (Temperature <= 999.0);
30031 @end smallexample
30032
30033 @noindent
30034 In both cases, if assertions are active and the temperature is excessive,
30035 the exception @code{Assert_Failure} will be raised, with the given string in
30036 the first case or a string indicating the location of the pragma in the second
30037 case used as the exception message.
30038
30039 You can turn assertions on and off by using the @code{Assertion_Policy}
30040 pragma.
30041 @cindex pragma @code{Assertion_Policy}
30042 This is an Ada 2005 pragma which is implemented in all modes by
30043 GNAT, but only in the latest versions of GNAT which include Ada 2005
30044 capability. Alternatively, you can use the @option{-gnata} switch
30045 @cindex @option{-gnata} switch
30046 to enable assertions from the command line (this is recognized by all versions
30047 of GNAT).
30048
30049 For the example above with the @code{Put_Line}, the GNAT-specific pragma
30050 @code{Debug} can be used:
30051 @cindex pragma @code{Debug}
30052
30053 @smallexample @c ada
30054 pragma Debug (Put_Line ("got to the first stage!"));
30055 @end smallexample
30056
30057 @noindent
30058 If debug pragmas are enabled, the argument, which must be of the form of
30059 a procedure call, is executed (in this case, @code{Put_Line} will be called).
30060 Only one call can be present, but of course a special debugging procedure
30061 containing any code you like can be included in the program and then
30062 called in a pragma @code{Debug} argument as needed.
30063
30064 One advantage of pragma @code{Debug} over the @code{if Debugging then}
30065 construct is that pragma @code{Debug} can appear in declarative contexts,
30066 such as at the very beginning of a procedure, before local declarations have
30067 been elaborated.
30068
30069 Debug pragmas are enabled using either the @option{-gnata} switch that also
30070 controls assertions, or with a separate Debug_Policy pragma.
30071 @cindex pragma @code{Debug_Policy}
30072 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
30073 in Ada 95 and Ada 83 programs as well), and is analogous to
30074 pragma @code{Assertion_Policy} to control assertions.
30075
30076 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
30077 and thus they can appear in @file{gnat.adc} if you are not using a
30078 project file, or in the file designated to contain configuration pragmas
30079 in a project file.
30080 They then apply to all subsequent compilations. In practice the use of
30081 the @option{-gnata} switch is often the most convenient method of controlling
30082 the status of these pragmas.
30083
30084 Note that a pragma is not a statement, so in contexts where a statement
30085 sequence is required, you can't just write a pragma on its own. You have
30086 to add a @code{null} statement.
30087
30088 @smallexample @c ada
30089 @group
30090 if @dots{} then
30091    @dots{} -- some statements
30092 else
30093    pragma Assert (Num_Cases < 10);
30094    null;
30095 end if;
30096 @end group
30097 @end smallexample
30098
30099
30100 @node Conditionalizing Declarations
30101 @section Conditionalizing Declarations
30102
30103 @noindent
30104 In some cases, it may be necessary to conditionalize declarations to meet
30105 different requirements. For example we might want a bit string whose length
30106 is set to meet some hardware message requirement.
30107
30108 In some cases, it may be possible to do this using declare blocks controlled
30109 by conditional constants:
30110
30111 @smallexample @c ada
30112 @group
30113 if Small_Machine then
30114    declare
30115       X : Bit_String (1 .. 10);
30116    begin
30117       @dots{}
30118    end;
30119 else
30120    declare
30121       X : Large_Bit_String (1 .. 1000);
30122    begin
30123       @dots{}
30124    end;
30125 end if;
30126 @end group
30127 @end smallexample
30128
30129 @noindent
30130 Note that in this approach, both declarations are analyzed by the
30131 compiler so this can only be used where both declarations are legal,
30132 even though one of them will not be used.
30133
30134 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
30135 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
30136 that are parameterized by these constants. For example
30137
30138 @smallexample @c ada
30139 @group
30140 for Rec use
30141   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
30142 end record;
30143 @end group
30144 @end smallexample
30145
30146 @noindent
30147 If @code{Bits_Per_Word} is set to 32, this generates either
30148
30149 @smallexample @c ada
30150 @group
30151 for Rec use
30152   Field1 at 0 range 0 .. 32;
30153 end record;
30154 @end group
30155 @end smallexample
30156
30157 @noindent
30158 for the big endian case, or
30159
30160 @smallexample @c ada
30161 @group
30162 for Rec use record
30163   Field1 at 0 range 10 .. 32;
30164 end record;
30165 @end group
30166 @end smallexample
30167
30168 @noindent
30169 for the little endian case. Since a powerful subset of Ada expression
30170 notation is usable for creating static constants, clever use of this
30171 feature can often solve quite difficult problems in conditionalizing
30172 compilation (note incidentally that in Ada 95, the little endian
30173 constant was introduced as @code{System.Default_Bit_Order}, so you do not
30174 need to define this one yourself).
30175
30176
30177 @node Use of Alternative Implementations
30178 @section Use of Alternative Implementations
30179
30180 @noindent
30181 In some cases, none of the approaches described above are adequate. This
30182 can occur for example if the set of declarations required is radically
30183 different for two different configurations.
30184
30185 In this situation, the official Ada way of dealing with conditionalizing
30186 such code is to write separate units for the different cases. As long as
30187 this does not result in excessive duplication of code, this can be done
30188 without creating maintenance problems. The approach is to share common
30189 code as far as possible, and then isolate the code and declarations
30190 that are different. Subunits are often a convenient method for breaking
30191 out a piece of a unit that is to be conditionalized, with separate files
30192 for different versions of the subunit for different targets, where the
30193 build script selects the right one to give to the compiler.
30194 @cindex Subunits (and conditional compilation)
30195
30196 As an example, consider a situation where a new feature in Ada 2005
30197 allows something to be done in a really nice way. But your code must be able
30198 to compile with an Ada 95 compiler. Conceptually you want to say:
30199
30200 @smallexample @c ada
30201 @group
30202 if Ada_2005 then
30203    @dots{} neat Ada 2005 code
30204 else
30205    @dots{} not quite as neat Ada 95 code
30206 end if;
30207 @end group
30208 @end smallexample
30209
30210 @noindent
30211 where @code{Ada_2005} is a Boolean constant.
30212
30213 But this won't work when @code{Ada_2005} is set to @code{False},
30214 since the @code{then} clause will be illegal for an Ada 95 compiler.
30215 (Recall that although such unreachable code would eventually be deleted
30216 by the compiler, it still needs to be legal.  If it uses features
30217 introduced in Ada 2005, it will be illegal in Ada 95.)
30218
30219 So instead we write
30220
30221 @smallexample @c ada
30222 procedure Insert is separate;
30223 @end smallexample
30224
30225 @noindent
30226 Then we have two files for the subunit @code{Insert}, with the two sets of
30227 code.
30228 If the package containing this is called @code{File_Queries}, then we might
30229 have two files
30230
30231 @itemize @bullet
30232 @item    @file{file_queries-insert-2005.adb}
30233 @item    @file{file_queries-insert-95.adb}
30234 @end itemize
30235
30236 @noindent
30237 and the build script renames the appropriate file to
30238
30239 @smallexample
30240 file_queries-insert.adb
30241 @end smallexample
30242
30243 @noindent
30244 and then carries out the compilation.
30245
30246 This can also be done with project files' naming schemes. For example:
30247
30248 @smallexample @c project
30249 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30250 @end smallexample
30251
30252 @noindent
30253 Note also that with project files it is desirable to use a different extension
30254 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30255 conflict may arise through another commonly used feature: to declare as part
30256 of the project a set of directories containing all the sources obeying the
30257 default naming scheme.
30258
30259 The use of alternative units is certainly feasible in all situations,
30260 and for example the Ada part of the GNAT run-time is conditionalized
30261 based on the target architecture using this approach. As a specific example,
30262 consider the implementation of the AST feature in VMS. There is one
30263 spec:
30264
30265 @smallexample
30266 s-asthan.ads
30267 @end smallexample
30268
30269 @noindent
30270 which is the same for all architectures, and three bodies:
30271
30272 @table @file
30273 @item    s-asthan.adb
30274 used for all non-VMS operating systems
30275 @item    s-asthan-vms-alpha.adb
30276 used for VMS on the Alpha
30277 @item    s-asthan-vms-ia64.adb
30278 used for VMS on the ia64
30279 @end table
30280
30281 @noindent
30282 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30283 this operating system feature is not available, and the two remaining
30284 versions interface with the corresponding versions of VMS to provide
30285 VMS-compatible AST handling. The GNAT build script knows the architecture
30286 and operating system, and automatically selects the right version,
30287 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30288
30289 Another style for arranging alternative implementations is through Ada's
30290 access-to-subprogram facility.
30291 In case some functionality is to be conditionally included,
30292 you can declare an access-to-procedure variable @code{Ref} that is initialized
30293 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30294 when appropriate.
30295 In some library package, set @code{Ref} to @code{Proc'Access} for some
30296 procedure @code{Proc} that performs the relevant processing.
30297 The initialization only occurs if the library package is included in the
30298 program.
30299 The same idea can also be implemented using tagged types and dispatching
30300 calls.
30301
30302
30303 @node Preprocessing
30304 @section Preprocessing
30305 @cindex Preprocessing
30306
30307 @noindent
30308 Although it is quite possible to conditionalize code without the use of
30309 C-style preprocessing, as described earlier in this section, it is
30310 nevertheless convenient in some cases to use the C approach. Moreover,
30311 older Ada compilers have often provided some preprocessing capability,
30312 so legacy code may depend on this approach, even though it is not
30313 standard.
30314
30315 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30316 extent on the various preprocessors that have been used
30317 with legacy code on other compilers, to enable easier transition).
30318
30319 The preprocessor may be used in two separate modes. It can be used quite
30320 separately from the compiler, to generate a separate output source file
30321 that is then fed to the compiler as a separate step. This is the
30322 @code{gnatprep} utility, whose use is fully described in
30323 @ref{Preprocessing Using gnatprep}.
30324 @cindex @code{gnatprep}
30325
30326 The preprocessing language allows such constructs as
30327
30328 @smallexample
30329 @group
30330 #if DEBUG or PRIORITY > 4 then
30331    bunch of declarations
30332 #else
30333    completely different bunch of declarations
30334 #end if;
30335 @end group
30336 @end smallexample
30337
30338 @noindent
30339 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30340 defined either on the command line or in a separate file.
30341
30342 The other way of running the preprocessor is even closer to the C style and
30343 often more convenient. In this approach the preprocessing is integrated into
30344 the compilation process. The compiler is fed the preprocessor input which
30345 includes @code{#if} lines etc, and then the compiler carries out the
30346 preprocessing internally and processes the resulting output.
30347 For more details on this approach, see @ref{Integrated Preprocessing}.
30348
30349
30350 @c *******************************
30351 @node Inline Assembler
30352 @appendix Inline Assembler
30353 @c *******************************
30354
30355 @noindent
30356 If you need to write low-level software that interacts directly
30357 with the hardware, Ada provides two ways to incorporate assembly
30358 language code into your program.  First, you can import and invoke
30359 external routines written in assembly language, an Ada feature fully
30360 supported by GNAT@.  However, for small sections of code it may be simpler
30361 or more efficient to include assembly language statements directly
30362 in your Ada source program, using the facilities of the implementation-defined
30363 package @code{System.Machine_Code}, which incorporates the gcc
30364 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30365 including the following:
30366
30367 @itemize @bullet
30368 @item No need to use non-Ada tools
30369 @item Consistent interface over different targets
30370 @item Automatic usage of the proper calling conventions
30371 @item Access to Ada constants and variables
30372 @item Definition of intrinsic routines
30373 @item Possibility of inlining a subprogram comprising assembler code
30374 @item Code optimizer can take Inline Assembler code into account
30375 @end itemize
30376
30377 This chapter presents a series of examples to show you how to use
30378 the Inline Assembler.  Although it focuses on the Intel x86,
30379 the general approach applies also to other processors.
30380 It is assumed that you are familiar with Ada
30381 and with assembly language programming.
30382
30383 @menu
30384 * Basic Assembler Syntax::
30385 * A Simple Example of Inline Assembler::
30386 * Output Variables in Inline Assembler::
30387 * Input Variables in Inline Assembler::
30388 * Inlining Inline Assembler Code::
30389 * Other Asm Functionality::
30390 @end menu
30391
30392 @c ---------------------------------------------------------------------------
30393 @node Basic Assembler Syntax
30394 @section Basic Assembler Syntax
30395
30396 @noindent
30397 The assembler used by GNAT and gcc is based not on the Intel assembly
30398 language, but rather on a language that descends from the AT&T Unix
30399 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30400 The following table summarizes the main features of @emph{as} syntax
30401 and points out the differences from the Intel conventions.
30402 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30403 pre-processor) documentation for further information.
30404
30405 @table @asis
30406 @item Register names
30407 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30408 @*
30409 Intel: No extra punctuation; for example @code{eax}
30410
30411 @item Immediate operand
30412 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30413 @*
30414 Intel: No extra punctuation; for example @code{4}
30415
30416 @item Address
30417 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30418 @*
30419 Intel: No extra punctuation; for example @code{loc}
30420
30421 @item Memory contents
30422 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30423 @*
30424 Intel: Square brackets; for example @code{[loc]}
30425
30426 @item Register contents
30427 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30428 @*
30429 Intel: Square brackets; for example @code{[eax]}
30430
30431 @item Hexadecimal numbers
30432 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30433 @*
30434 Intel: Trailing ``h''; for example @code{A0h}
30435
30436 @item Operand size
30437 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30438 a 16-bit word
30439 @*
30440 Intel: Implicit, deduced by assembler; for example @code{mov}
30441
30442 @item Instruction repetition
30443 gcc / @emph{as}: Split into two lines; for example
30444 @*
30445 @code{rep}
30446 @*
30447 @code{stosl}
30448 @*
30449 Intel: Keep on one line; for example @code{rep stosl}
30450
30451 @item Order of operands
30452 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30453 @*
30454 Intel: Destination first; for example @code{mov eax, 4}
30455 @end table
30456
30457 @c ---------------------------------------------------------------------------
30458 @node A Simple Example of Inline Assembler
30459 @section A Simple Example of Inline Assembler
30460
30461 @noindent
30462 The following example will generate a single assembly language statement,
30463 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30464 the example will be useful in illustrating the basics of
30465 the Inline Assembler facility.
30466
30467 @smallexample @c ada
30468 @group
30469 with System.Machine_Code; use System.Machine_Code;
30470 procedure Nothing is
30471 begin
30472    Asm ("nop");
30473 end Nothing;
30474 @end group
30475 @end smallexample
30476
30477 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30478 here it takes one parameter, a @emph{template string} that must be a static
30479 expression and that will form the generated instruction.
30480 @code{Asm} may be regarded as a compile-time procedure that parses
30481 the template string and additional parameters (none here),
30482 from which it generates a sequence of assembly language instructions.
30483
30484 The examples in this chapter will illustrate several of the forms
30485 for invoking @code{Asm}; a complete specification of the syntax
30486 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30487 Manual}.
30488
30489 Under the standard GNAT conventions, the @code{Nothing} procedure
30490 should be in a file named @file{nothing.adb}.
30491 You can build the executable in the usual way:
30492 @smallexample
30493 gnatmake nothing
30494 @end smallexample
30495 However, the interesting aspect of this example is not its run-time behavior
30496 but rather the generated assembly code.
30497 To see this output, invoke the compiler as follows:
30498 @smallexample
30499    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30500 @end smallexample
30501 where the options are:
30502
30503 @table @code
30504 @item -c
30505 compile only (no bind or link)
30506 @item -S
30507 generate assembler listing
30508 @item -fomit-frame-pointer
30509 do not set up separate stack frames
30510 @item -gnatp
30511 do not add runtime checks
30512 @end table
30513
30514 This gives a human-readable assembler version of the code. The resulting
30515 file will have the same name as the Ada source file, but with a @code{.s}
30516 extension. In our example, the file @file{nothing.s} has the following
30517 contents:
30518
30519 @smallexample
30520 @group
30521 .file "nothing.adb"
30522 gcc2_compiled.:
30523 ___gnu_compiled_ada:
30524 .text
30525    .align 4
30526 .globl __ada_nothing
30527 __ada_nothing:
30528 #APP
30529    nop
30530 #NO_APP
30531    jmp L1
30532    .align 2,0x90
30533 L1:
30534    ret
30535 @end group
30536 @end smallexample
30537
30538 The assembly code you included is clearly indicated by
30539 the compiler, between the @code{#APP} and @code{#NO_APP}
30540 delimiters. The character before the 'APP' and 'NOAPP'
30541 can differ on different targets. For example, GNU/Linux uses '#APP' while
30542 on NT you will see '/APP'.
30543
30544 If you make a mistake in your assembler code (such as using the
30545 wrong size modifier, or using a wrong operand for the instruction) GNAT
30546 will report this error in a temporary file, which will be deleted when
30547 the compilation is finished.  Generating an assembler file will help
30548 in such cases, since you can assemble this file separately using the
30549 @emph{as} assembler that comes with gcc.
30550
30551 Assembling the file using the command
30552
30553 @smallexample
30554 as @file{nothing.s}
30555 @end smallexample
30556 @noindent
30557 will give you error messages whose lines correspond to the assembler
30558 input file, so you can easily find and correct any mistakes you made.
30559 If there are no errors, @emph{as} will generate an object file
30560 @file{nothing.out}.
30561
30562 @c ---------------------------------------------------------------------------
30563 @node Output Variables in Inline Assembler
30564 @section Output Variables in Inline Assembler
30565
30566 @noindent
30567 The examples in this section, showing how to access the processor flags,
30568 illustrate how to specify the destination operands for assembly language
30569 statements.
30570
30571 @smallexample @c ada
30572 @group
30573 with Interfaces; use Interfaces;
30574 with Ada.Text_IO; use Ada.Text_IO;
30575 with System.Machine_Code; use System.Machine_Code;
30576 procedure Get_Flags is
30577    Flags : Unsigned_32;
30578    use ASCII;
30579 begin
30580    Asm ("pushfl"          & LF & HT & -- push flags on stack
30581         "popl %%eax"      & LF & HT & -- load eax with flags
30582         "movl %%eax, %0",             -- store flags in variable
30583         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30584    Put_Line ("Flags register:" & Flags'Img);
30585 end Get_Flags;
30586 @end group
30587 @end smallexample
30588
30589 In order to have a nicely aligned assembly listing, we have separated
30590 multiple assembler statements in the Asm template string with linefeed
30591 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30592 The resulting section of the assembly output file is:
30593
30594 @smallexample
30595 @group
30596 #APP
30597    pushfl
30598    popl %eax
30599    movl %eax, -40(%ebp)
30600 #NO_APP
30601 @end group
30602 @end smallexample
30603
30604 It would have been legal to write the Asm invocation as:
30605
30606 @smallexample
30607 Asm ("pushfl popl %%eax movl %%eax, %0")
30608 @end smallexample
30609
30610 but in the generated assembler file, this would come out as:
30611
30612 @smallexample
30613 #APP
30614    pushfl popl %eax movl %eax, -40(%ebp)
30615 #NO_APP
30616 @end smallexample
30617
30618 which is not so convenient for the human reader.
30619
30620 We use Ada comments
30621 at the end of each line to explain what the assembler instructions
30622 actually do.  This is a useful convention.
30623
30624 When writing Inline Assembler instructions, you need to precede each register
30625 and variable name with a percent sign.  Since the assembler already requires
30626 a percent sign at the beginning of a register name, you need two consecutive
30627 percent signs for such names in the Asm template string, thus @code{%%eax}.
30628 In the generated assembly code, one of the percent signs will be stripped off.
30629
30630 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30631 variables: operands you later define using @code{Input} or @code{Output}
30632 parameters to @code{Asm}.
30633 An output variable is illustrated in
30634 the third statement in the Asm template string:
30635 @smallexample
30636 movl %%eax, %0
30637 @end smallexample
30638 The intent is to store the contents of the eax register in a variable that can
30639 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30640 necessarily work, since the compiler might optimize by using a register
30641 to hold Flags, and the expansion of the @code{movl} instruction would not be
30642 aware of this optimization.  The solution is not to store the result directly
30643 but rather to advise the compiler to choose the correct operand form;
30644 that is the purpose of the @code{%0} output variable.
30645
30646 Information about the output variable is supplied in the @code{Outputs}
30647 parameter to @code{Asm}:
30648 @smallexample
30649 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30650 @end smallexample
30651
30652 The output is defined by the @code{Asm_Output} attribute of the target type;
30653 the general format is
30654 @smallexample
30655 Type'Asm_Output (constraint_string, variable_name)
30656 @end smallexample
30657
30658 The constraint string directs the compiler how
30659 to store/access the associated variable.  In the example
30660 @smallexample
30661 Unsigned_32'Asm_Output ("=m", Flags);
30662 @end smallexample
30663 the @code{"m"} (memory) constraint tells the compiler that the variable
30664 @code{Flags} should be stored in a memory variable, thus preventing
30665 the optimizer from keeping it in a register.  In contrast,
30666 @smallexample
30667 Unsigned_32'Asm_Output ("=r", Flags);
30668 @end smallexample
30669 uses the @code{"r"} (register) constraint, telling the compiler to
30670 store the variable in a register.
30671
30672 If the constraint is preceded by the equal character (@strong{=}), it tells
30673 the compiler that the variable will be used to store data into it.
30674
30675 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30676 allowing the optimizer to choose whatever it deems best.
30677
30678 There are a fairly large number of constraints, but the ones that are
30679 most useful (for the Intel x86 processor) are the following:
30680
30681 @table @code
30682 @item =
30683 output constraint
30684 @item g
30685 global (i.e.@: can be stored anywhere)
30686 @item m
30687 in memory
30688 @item I
30689 a constant
30690 @item a
30691 use eax
30692 @item b
30693 use ebx
30694 @item c
30695 use ecx
30696 @item d
30697 use edx
30698 @item S
30699 use esi
30700 @item D
30701 use edi
30702 @item r
30703 use one of eax, ebx, ecx or edx
30704 @item q
30705 use one of eax, ebx, ecx, edx, esi or edi
30706 @end table
30707
30708 The full set of constraints is described in the gcc and @emph{as}
30709 documentation; note that it is possible to combine certain constraints
30710 in one constraint string.
30711
30712 You specify the association of an output variable with an assembler operand
30713 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30714 integer.  Thus in
30715 @smallexample @c ada
30716 @group
30717 Asm ("pushfl"          & LF & HT & -- push flags on stack
30718      "popl %%eax"      & LF & HT & -- load eax with flags
30719      "movl %%eax, %0",             -- store flags in variable
30720      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30721 @end group
30722 @end smallexample
30723 @noindent
30724 @code{%0} will be replaced in the expanded code by the appropriate operand,
30725 whatever
30726 the compiler decided for the @code{Flags} variable.
30727
30728 In general, you may have any number of output variables:
30729 @itemize @bullet
30730 @item
30731 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30732 @item
30733 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30734 of @code{Asm_Output} attributes
30735 @end itemize
30736
30737 For example:
30738 @smallexample @c ada
30739 @group
30740 Asm ("movl %%eax, %0" & LF & HT &
30741      "movl %%ebx, %1" & LF & HT &
30742      "movl %%ecx, %2",
30743      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30744                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30745                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30746 @end group
30747 @end smallexample
30748 @noindent
30749 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30750 in the Ada program.
30751
30752 As a variation on the @code{Get_Flags} example, we can use the constraints
30753 string to direct the compiler to store the eax register into the @code{Flags}
30754 variable, instead of including the store instruction explicitly in the
30755 @code{Asm} template string:
30756
30757 @smallexample @c ada
30758 @group
30759 with Interfaces; use Interfaces;
30760 with Ada.Text_IO; use Ada.Text_IO;
30761 with System.Machine_Code; use System.Machine_Code;
30762 procedure Get_Flags_2 is
30763    Flags : Unsigned_32;
30764    use ASCII;
30765 begin
30766    Asm ("pushfl"      & LF & HT & -- push flags on stack
30767         "popl %%eax",             -- save flags in eax
30768         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30769    Put_Line ("Flags register:" & Flags'Img);
30770 end Get_Flags_2;
30771 @end group
30772 @end smallexample
30773
30774 @noindent
30775 The @code{"a"} constraint tells the compiler that the @code{Flags}
30776 variable will come from the eax register. Here is the resulting code:
30777
30778 @smallexample
30779 @group
30780 #APP
30781    pushfl
30782    popl %eax
30783 #NO_APP
30784    movl %eax,-40(%ebp)
30785 @end group
30786 @end smallexample
30787
30788 @noindent
30789 The compiler generated the store of eax into Flags after
30790 expanding the assembler code.
30791
30792 Actually, there was no need to pop the flags into the eax register;
30793 more simply, we could just pop the flags directly into the program variable:
30794
30795 @smallexample @c ada
30796 @group
30797 with Interfaces; use Interfaces;
30798 with Ada.Text_IO; use Ada.Text_IO;
30799 with System.Machine_Code; use System.Machine_Code;
30800 procedure Get_Flags_3 is
30801    Flags : Unsigned_32;
30802    use ASCII;
30803 begin
30804    Asm ("pushfl"  & LF & HT & -- push flags on stack
30805         "pop %0",             -- save flags in Flags
30806         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30807    Put_Line ("Flags register:" & Flags'Img);
30808 end Get_Flags_3;
30809 @end group
30810 @end smallexample
30811
30812 @c ---------------------------------------------------------------------------
30813 @node Input Variables in Inline Assembler
30814 @section Input Variables in Inline Assembler
30815
30816 @noindent
30817 The example in this section illustrates how to specify the source operands
30818 for assembly language statements.
30819 The program simply increments its input value by 1:
30820
30821 @smallexample @c ada
30822 @group
30823 with Interfaces; use Interfaces;
30824 with Ada.Text_IO; use Ada.Text_IO;
30825 with System.Machine_Code; use System.Machine_Code;
30826 procedure Increment is
30827
30828    function Incr (Value : Unsigned_32) return Unsigned_32 is
30829       Result : Unsigned_32;
30830    begin
30831       Asm ("incl %0",
30832            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30833            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30834       return Result;
30835    end Incr;
30836
30837    Value : Unsigned_32;
30838
30839 begin
30840    Value := 5;
30841    Put_Line ("Value before is" & Value'Img);
30842    Value := Incr (Value);
30843    Put_Line ("Value after is" & Value'Img);
30844 end Increment;
30845 @end group
30846 @end smallexample
30847
30848 The @code{Outputs} parameter to @code{Asm} specifies
30849 that the result will be in the eax register and that it is to be stored
30850 in the @code{Result} variable.
30851
30852 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30853 but with an @code{Asm_Input} attribute.
30854 The @code{"="} constraint, indicating an output value, is not present.
30855
30856 You can have multiple input variables, in the same way that you can have more
30857 than one output variable.
30858
30859 The parameter count (%0, %1) etc, now starts at the first input
30860 statement, and continues with the output statements.
30861 When both parameters use the same variable, the
30862 compiler will treat them as the same %n operand, which is the case here.
30863
30864 Just as the @code{Outputs} parameter causes the register to be stored into the
30865 target variable after execution of the assembler statements, so does the
30866 @code{Inputs} parameter cause its variable to be loaded into the register
30867 before execution of the assembler statements.
30868
30869 Thus the effect of the @code{Asm} invocation is:
30870 @enumerate
30871 @item load the 32-bit value of @code{Value} into eax
30872 @item execute the @code{incl %eax} instruction
30873 @item store the contents of eax into the @code{Result} variable
30874 @end enumerate
30875
30876 The resulting assembler file (with @option{-O2} optimization) contains:
30877 @smallexample
30878 @group
30879 _increment__incr.1:
30880    subl $4,%esp
30881    movl 8(%esp),%eax
30882 #APP
30883    incl %eax
30884 #NO_APP
30885    movl %eax,%edx
30886    movl %ecx,(%esp)
30887    addl $4,%esp
30888    ret
30889 @end group
30890 @end smallexample
30891
30892 @c ---------------------------------------------------------------------------
30893 @node Inlining Inline Assembler Code
30894 @section Inlining Inline Assembler Code
30895
30896 @noindent
30897 For a short subprogram such as the @code{Incr} function in the previous
30898 section, the overhead of the call and return (creating / deleting the stack
30899 frame) can be significant, compared to the amount of code in the subprogram
30900 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30901 which directs the compiler to expand invocations of the subprogram at the
30902 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30903 Here is the resulting program:
30904
30905 @smallexample @c ada
30906 @group
30907 with Interfaces; use Interfaces;
30908 with Ada.Text_IO; use Ada.Text_IO;
30909 with System.Machine_Code; use System.Machine_Code;
30910 procedure Increment_2 is
30911
30912    function Incr (Value : Unsigned_32) return Unsigned_32 is
30913       Result : Unsigned_32;
30914    begin
30915       Asm ("incl %0",
30916            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30917            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30918       return Result;
30919    end Incr;
30920    pragma Inline (Increment);
30921
30922    Value : Unsigned_32;
30923
30924 begin
30925    Value := 5;
30926    Put_Line ("Value before is" & Value'Img);
30927    Value := Increment (Value);
30928    Put_Line ("Value after is" & Value'Img);
30929 end Increment_2;
30930 @end group
30931 @end smallexample
30932
30933 Compile the program with both optimization (@option{-O2}) and inlining
30934 (@option{-gnatn}) enabled.
30935
30936 The @code{Incr} function is still compiled as usual, but at the
30937 point in @code{Increment} where our function used to be called:
30938
30939 @smallexample
30940 @group
30941 pushl %edi
30942 call _increment__incr.1
30943 @end group
30944 @end smallexample
30945
30946 @noindent
30947 the code for the function body directly appears:
30948
30949 @smallexample
30950 @group
30951 movl %esi,%eax
30952 #APP
30953    incl %eax
30954 #NO_APP
30955    movl %eax,%edx
30956 @end group
30957 @end smallexample
30958
30959 @noindent
30960 thus saving the overhead of stack frame setup and an out-of-line call.
30961
30962 @c ---------------------------------------------------------------------------
30963 @node Other Asm Functionality
30964 @section Other @code{Asm} Functionality
30965
30966 @noindent
30967 This section describes two important parameters to the @code{Asm}
30968 procedure: @code{Clobber}, which identifies register usage;
30969 and @code{Volatile}, which inhibits unwanted optimizations.
30970
30971 @menu
30972 * The Clobber Parameter::
30973 * The Volatile Parameter::
30974 @end menu
30975
30976 @c ---------------------------------------------------------------------------
30977 @node The Clobber Parameter
30978 @subsection The @code{Clobber} Parameter
30979
30980 @noindent
30981 One of the dangers of intermixing assembly language and a compiled language
30982 such as Ada is that the compiler needs to be aware of which registers are
30983 being used by the assembly code.  In some cases, such as the earlier examples,
30984 the constraint string is sufficient to indicate register usage (e.g.,
30985 @code{"a"} for
30986 the eax register).  But more generally, the compiler needs an explicit
30987 identification of the registers that are used by the Inline Assembly
30988 statements.
30989
30990 Using a register that the compiler doesn't know about
30991 could be a side effect of an instruction (like @code{mull}
30992 storing its result in both eax and edx).
30993 It can also arise from explicit register usage in your
30994 assembly code; for example:
30995 @smallexample
30996 @group
30997 Asm ("movl %0, %%ebx" & LF & HT &
30998      "movl %%ebx, %1",
30999      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31000      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
31001 @end group
31002 @end smallexample
31003 @noindent
31004 where the compiler (since it does not analyze the @code{Asm} template string)
31005 does not know you are using the ebx register.
31006
31007 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
31008 to identify the registers that will be used by your assembly code:
31009
31010 @smallexample
31011 @group
31012 Asm ("movl %0, %%ebx" & LF & HT &
31013      "movl %%ebx, %1",
31014      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31015      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
31016      Clobber => "ebx");
31017 @end group
31018 @end smallexample
31019
31020 The Clobber parameter is a static string expression specifying the
31021 register(s) you are using.  Note that register names are @emph{not} prefixed
31022 by a percent sign. Also, if more than one register is used then their names
31023 are separated by commas; e.g., @code{"eax, ebx"}
31024
31025 The @code{Clobber} parameter has several additional uses:
31026 @enumerate
31027 @item Use ``register'' name @code{cc} to indicate that flags might have changed
31028 @item Use ``register'' name @code{memory} if you changed a memory location
31029 @end enumerate
31030
31031 @c ---------------------------------------------------------------------------
31032 @node The Volatile Parameter
31033 @subsection The @code{Volatile} Parameter
31034 @cindex Volatile parameter
31035
31036 @noindent
31037 Compiler optimizations in the presence of Inline Assembler may sometimes have
31038 unwanted effects.  For example, when an @code{Asm} invocation with an input
31039 variable is inside a loop, the compiler might move the loading of the input
31040 variable outside the loop, regarding it as a one-time initialization.
31041
31042 If this effect is not desired, you can disable such optimizations by setting
31043 the @code{Volatile} parameter to @code{True}; for example:
31044
31045 @smallexample @c ada
31046 @group
31047 Asm ("movl %0, %%ebx" & LF & HT &
31048      "movl %%ebx, %1",
31049      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
31050      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
31051      Clobber  => "ebx",
31052      Volatile => True);
31053 @end group
31054 @end smallexample
31055
31056 By default, @code{Volatile} is set to @code{False} unless there is no
31057 @code{Outputs} parameter.
31058
31059 Although setting @code{Volatile} to @code{True} prevents unwanted
31060 optimizations, it will also disable other optimizations that might be
31061 important for efficiency. In general, you should set @code{Volatile}
31062 to @code{True} only if the compiler's optimizations have created
31063 problems.
31064 @c END OF INLINE ASSEMBLER CHAPTER
31065 @c ===============================
31066
31067 @c ***********************************
31068 @c * Compatibility and Porting Guide *
31069 @c ***********************************
31070 @node Compatibility and Porting Guide
31071 @appendix Compatibility and Porting Guide
31072
31073 @noindent
31074 This chapter describes the compatibility issues that may arise between
31075 GNAT and other Ada compilation systems (including those for Ada 83),
31076 and shows how GNAT can expedite porting
31077 applications developed in other Ada environments.
31078
31079 @menu
31080 * Compatibility with Ada 83::
31081 * Compatibility between Ada 95 and Ada 2005::
31082 * Implementation-dependent characteristics::
31083 * Compatibility with Other Ada Systems::
31084 * Representation Clauses::
31085 @ifclear vms
31086 @c Brief section is only in non-VMS version
31087 @c Full chapter is in VMS version
31088 * Compatibility with HP Ada 83::
31089 @end ifclear
31090 @ifset vms
31091 * Transitioning to 64-Bit GNAT for OpenVMS::
31092 @end ifset
31093 @end menu
31094
31095 @node Compatibility with Ada 83
31096 @section Compatibility with Ada 83
31097 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
31098
31099 @noindent
31100 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
31101 particular, the design intention was that the difficulties associated
31102 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
31103 that occur when moving from one Ada 83 system to another.
31104
31105 However, there are a number of points at which there are minor
31106 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
31107 full details of these issues,
31108 and should be consulted for a complete treatment.
31109 In practice the
31110 following subsections treat the most likely issues to be encountered.
31111
31112 @menu
31113 * Legal Ada 83 programs that are illegal in Ada 95::
31114 * More deterministic semantics::
31115 * Changed semantics::
31116 * Other language compatibility issues::
31117 @end menu
31118
31119 @node Legal Ada 83 programs that are illegal in Ada 95
31120 @subsection Legal Ada 83 programs that are illegal in Ada 95
31121
31122 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
31123 Ada 95 and thus also in Ada 2005:
31124
31125 @table @emph
31126 @item Character literals
31127 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
31128 @code{Wide_Character} as a new predefined character type, some uses of
31129 character literals that were legal in Ada 83 are illegal in Ada 95.
31130 For example:
31131 @smallexample @c ada
31132    for Char in 'A' .. 'Z' loop @dots{} end loop;
31133 @end smallexample
31134
31135 @noindent
31136 The problem is that @code{'A'} and @code{'Z'} could be from either
31137 @code{Character} or @code{Wide_Character}.  The simplest correction
31138 is to make the type explicit; e.g.:
31139 @smallexample @c ada
31140    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
31141 @end smallexample
31142
31143 @item New reserved words
31144 The identifiers @code{abstract}, @code{aliased}, @code{protected},
31145 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
31146 Existing Ada 83 code using any of these identifiers must be edited to
31147 use some alternative name.
31148
31149 @item Freezing rules
31150 The rules in Ada 95 are slightly different with regard to the point at
31151 which entities are frozen, and representation pragmas and clauses are
31152 not permitted past the freeze point.  This shows up most typically in
31153 the form of an error message complaining that a representation item
31154 appears too late, and the appropriate corrective action is to move
31155 the item nearer to the declaration of the entity to which it refers.
31156
31157 A particular case is that representation pragmas
31158 @ifset vms
31159 (including the
31160 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
31161 @end ifset
31162 cannot be applied to a subprogram body.  If necessary, a separate subprogram
31163 declaration must be introduced to which the pragma can be applied.
31164
31165 @item Optional bodies for library packages
31166 In Ada 83, a package that did not require a package body was nevertheless
31167 allowed to have one.  This lead to certain surprises in compiling large
31168 systems (situations in which the body could be unexpectedly ignored by the
31169 binder).  In Ada 95, if a package does not require a body then it is not
31170 permitted to have a body.  To fix this problem, simply remove a redundant
31171 body if it is empty, or, if it is non-empty, introduce a dummy declaration
31172 into the spec that makes the body required.  One approach is to add a private
31173 part to the package declaration (if necessary), and define a parameterless
31174 procedure called @code{Requires_Body}, which must then be given a dummy
31175 procedure body in the package body, which then becomes required.
31176 Another approach (assuming that this does not introduce elaboration
31177 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
31178 since one effect of this pragma is to require the presence of a package body.
31179
31180 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
31181 In Ada 95, the exception @code{Numeric_Error} is a renaming of
31182 @code{Constraint_Error}.
31183 This means that it is illegal to have separate exception handlers for
31184 the two exceptions.  The fix is simply to remove the handler for the
31185 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
31186 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
31187
31188 @item Indefinite subtypes in generics
31189 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
31190 as the actual for a generic formal private type, but then the instantiation
31191 would be illegal if there were any instances of declarations of variables
31192 of this type in the generic body.  In Ada 95, to avoid this clear violation
31193 of the methodological principle known as the ``contract model'',
31194 the generic declaration explicitly indicates whether
31195 or not such instantiations are permitted.  If a generic formal parameter
31196 has explicit unknown discriminants, indicated by using @code{(<>)} after the
31197 type name, then it can be instantiated with indefinite types, but no
31198 stand-alone variables can be declared of this type.  Any attempt to declare
31199 such a variable will result in an illegality at the time the generic is
31200 declared.  If the @code{(<>)} notation is not used, then it is illegal
31201 to instantiate the generic with an indefinite type.
31202 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
31203 It will show up as a compile time error, and
31204 the fix is usually simply to add the @code{(<>)} to the generic declaration.
31205 @end table
31206
31207 @node More deterministic semantics
31208 @subsection More deterministic semantics
31209
31210 @table @emph
31211 @item Conversions
31212 Conversions from real types to integer types round away from 0.  In Ada 83
31213 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
31214 implementation freedom was intended to support unbiased rounding in
31215 statistical applications, but in practice it interfered with portability.
31216 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
31217 is required.  Numeric code may be affected by this change in semantics.
31218 Note, though, that this issue is no worse than already existed in Ada 83
31219 when porting code from one vendor to another.
31220
31221 @item Tasking
31222 The Real-Time Annex introduces a set of policies that define the behavior of
31223 features that were implementation dependent in Ada 83, such as the order in
31224 which open select branches are executed.
31225 @end table
31226
31227 @node Changed semantics
31228 @subsection Changed semantics
31229
31230 @noindent
31231 The worst kind of incompatibility is one where a program that is legal in
31232 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31233 possible in Ada 83.  Fortunately this is extremely rare, but the one
31234 situation that you should be alert to is the change in the predefined type
31235 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31236
31237 @table @emph
31238 @item Range of type @code{Character}
31239 The range of @code{Standard.Character} is now the full 256 characters
31240 of Latin-1, whereas in most Ada 83 implementations it was restricted
31241 to 128 characters. Although some of the effects of
31242 this change will be manifest in compile-time rejection of legal
31243 Ada 83 programs it is possible for a working Ada 83 program to have
31244 a different effect in Ada 95, one that was not permitted in Ada 83.
31245 As an example, the expression
31246 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31247 delivers @code{255} as its value.
31248 In general, you should look at the logic of any
31249 character-processing Ada 83 program and see whether it needs to be adapted
31250 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31251 character handling package that may be relevant if code needs to be adapted
31252 to account for the additional Latin-1 elements.
31253 The desirable fix is to
31254 modify the program to accommodate the full character set, but in some cases
31255 it may be convenient to define a subtype or derived type of Character that
31256 covers only the restricted range.
31257 @cindex Latin-1
31258 @end table
31259
31260 @node Other language compatibility issues
31261 @subsection Other language compatibility issues
31262
31263 @table @emph
31264 @item @option{-gnat83} switch
31265 All implementations of GNAT provide a switch that causes GNAT to operate
31266 in Ada 83 mode.  In this mode, some but not all compatibility problems
31267 of the type described above are handled automatically.  For example, the
31268 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31269 as identifiers as in Ada 83.
31270 However,
31271 in practice, it is usually advisable to make the necessary modifications
31272 to the program to remove the need for using this switch.
31273 See @ref{Compiling Different Versions of Ada}.
31274
31275 @item Support for removed Ada 83 pragmas and attributes
31276 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31277 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31278 compilers are allowed, but not required, to implement these missing
31279 elements.  In contrast with some other compilers, GNAT implements all
31280 such pragmas and attributes, eliminating this compatibility concern.  These
31281 include @code{pragma Interface} and the floating point type attributes
31282 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31283 @end table
31284
31285
31286 @node Compatibility between Ada 95 and Ada 2005
31287 @section Compatibility between Ada 95 and Ada 2005
31288 @cindex Compatibility between Ada 95 and Ada 2005
31289
31290 @noindent
31291 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31292 a number of incompatibilities. Several are enumerated below;
31293 for a complete description please see the
31294 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31295 @cite{Rationale for Ada 2005}.
31296
31297 @table @emph
31298 @item New reserved words.
31299 The words @code{interface}, @code{overriding} and @code{synchronized} are
31300 reserved in Ada 2005.
31301 A pre-Ada 2005 program that uses any of these as an identifier will be
31302 illegal.
31303
31304 @item New declarations in predefined packages.
31305 A number of packages in the predefined environment contain new declarations:
31306 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31307 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31308 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31309 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31310 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31311 If an Ada 95 program does a @code{with} and @code{use} of any of these
31312 packages, the new declarations may cause name clashes.
31313
31314 @item Access parameters.
31315 A nondispatching subprogram with an access parameter cannot be renamed
31316 as a dispatching operation.  This was permitted in Ada 95.
31317
31318 @item Access types, discriminants, and constraints.
31319 Rule changes in this area have led to some incompatibilities; for example,
31320 constrained subtypes of some access types are not permitted in Ada 2005.
31321
31322 @item Aggregates for limited types.
31323 The allowance of aggregates for limited types in Ada 2005 raises the
31324 possibility of ambiguities in legal Ada 95 programs, since additional types
31325 now need to be considered in expression resolution.
31326
31327 @item Fixed-point multiplication and division.
31328 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31329 were legal in Ada 95 and invoked the predefined versions of these operations,
31330 are now ambiguous.
31331 The ambiguity may be resolved either by applying a type conversion to the
31332 expression, or by explicitly invoking the operation from package
31333 @code{Standard}.
31334
31335 @item Return-by-reference types.
31336 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31337 can declare a function returning a value from an anonymous access type.
31338 @end table
31339
31340
31341 @node Implementation-dependent characteristics
31342 @section Implementation-dependent characteristics
31343 @noindent
31344 Although the Ada language defines the semantics of each construct as
31345 precisely as practical, in some situations (for example for reasons of
31346 efficiency, or where the effect is heavily dependent on the host or target
31347 platform) the implementation is allowed some freedom.  In porting Ada 83
31348 code to GNAT, you need to be aware of whether / how the existing code
31349 exercised such implementation dependencies.  Such characteristics fall into
31350 several categories, and GNAT offers specific support in assisting the
31351 transition from certain Ada 83 compilers.
31352
31353 @menu
31354 * Implementation-defined pragmas::
31355 * Implementation-defined attributes::
31356 * Libraries::
31357 * Elaboration order::
31358 * Target-specific aspects::
31359 @end menu
31360
31361 @node Implementation-defined pragmas
31362 @subsection Implementation-defined pragmas
31363
31364 @noindent
31365 Ada compilers are allowed to supplement the language-defined pragmas, and
31366 these are a potential source of non-portability.  All GNAT-defined pragmas
31367 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31368 Reference Manual}, and these include several that are specifically
31369 intended to correspond to other vendors' Ada 83 pragmas.
31370 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31371 For compatibility with HP Ada 83, GNAT supplies the pragmas
31372 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31373 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31374 and @code{Volatile}.
31375 Other relevant pragmas include @code{External} and @code{Link_With}.
31376 Some vendor-specific
31377 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31378 recognized, thus
31379 avoiding compiler rejection of units that contain such pragmas; they are not
31380 relevant in a GNAT context and hence are not otherwise implemented.
31381
31382 @node Implementation-defined attributes
31383 @subsection Implementation-defined attributes
31384
31385 Analogous to pragmas, the set of attributes may be extended by an
31386 implementation.  All GNAT-defined attributes are described in
31387 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31388 Manual}, and these include several that are specifically intended
31389 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31390 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31391 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31392 @code{Type_Class}.
31393
31394 @node Libraries
31395 @subsection Libraries
31396 @noindent
31397 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31398 code uses vendor-specific libraries then there are several ways to manage
31399 this in Ada 95 or Ada 2005:
31400 @enumerate
31401 @item
31402 If the source code for the libraries (specs and bodies) are
31403 available, then the libraries can be migrated in the same way as the
31404 application.
31405 @item
31406 If the source code for the specs but not the bodies are
31407 available, then you can reimplement the bodies.
31408 @item
31409 Some features introduced by Ada 95 obviate the need for library support.  For
31410 example most Ada 83 vendors supplied a package for unsigned integers.  The
31411 Ada 95 modular type feature is the preferred way to handle this need, so
31412 instead of migrating or reimplementing the unsigned integer package it may
31413 be preferable to retrofit the application using modular types.
31414 @end enumerate
31415
31416 @node Elaboration order
31417 @subsection Elaboration order
31418 @noindent
31419 The implementation can choose any elaboration order consistent with the unit
31420 dependency relationship.  This freedom means that some orders can result in
31421 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31422 to invoke a subprogram its body has been elaborated, or to instantiate a
31423 generic before the generic body has been elaborated.  By default GNAT
31424 attempts to choose a safe order (one that will not encounter access before
31425 elaboration problems) by implicitly inserting @code{Elaborate} or
31426 @code{Elaborate_All} pragmas where
31427 needed.  However, this can lead to the creation of elaboration circularities
31428 and a resulting rejection of the program by gnatbind.  This issue is
31429 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31430 In brief, there are several
31431 ways to deal with this situation:
31432
31433 @itemize @bullet
31434 @item
31435 Modify the program to eliminate the circularities, e.g.@: by moving
31436 elaboration-time code into explicitly-invoked procedures
31437 @item
31438 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31439 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31440 @code{Elaborate_All}
31441 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31442 (by selectively suppressing elaboration checks via pragma
31443 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31444 @end itemize
31445
31446 @node Target-specific aspects
31447 @subsection Target-specific aspects
31448 @noindent
31449 Low-level applications need to deal with machine addresses, data
31450 representations, interfacing with assembler code, and similar issues.  If
31451 such an Ada 83 application is being ported to different target hardware (for
31452 example where the byte endianness has changed) then you will need to
31453 carefully examine the program logic; the porting effort will heavily depend
31454 on the robustness of the original design.  Moreover, Ada 95 (and thus
31455 Ada 2005) are sometimes
31456 incompatible with typical Ada 83 compiler practices regarding implicit
31457 packing, the meaning of the Size attribute, and the size of access values.
31458 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31459
31460 @node Compatibility with Other Ada Systems
31461 @section Compatibility with Other Ada Systems
31462
31463 @noindent
31464 If programs avoid the use of implementation dependent and
31465 implementation defined features, as documented in the @cite{Ada
31466 Reference Manual}, there should be a high degree of portability between
31467 GNAT and other Ada systems.  The following are specific items which
31468 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31469 compilers, but do not affect porting code to GNAT@.
31470 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31471 the following issues may or may not arise for Ada 2005 programs
31472 when other compilers appear.)
31473
31474 @table @emph
31475 @item Ada 83 Pragmas and Attributes
31476 Ada 95 compilers are allowed, but not required, to implement the missing
31477 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31478 GNAT implements all such pragmas and attributes, eliminating this as
31479 a compatibility concern, but some other Ada 95 compilers reject these
31480 pragmas and attributes.
31481
31482 @item Specialized Needs Annexes
31483 GNAT implements the full set of special needs annexes.  At the
31484 current time, it is the only Ada 95 compiler to do so.  This means that
31485 programs making use of these features may not be portable to other Ada
31486 95 compilation systems.
31487
31488 @item Representation Clauses
31489 Some other Ada 95 compilers implement only the minimal set of
31490 representation clauses required by the Ada 95 reference manual.  GNAT goes
31491 far beyond this minimal set, as described in the next section.
31492 @end table
31493
31494 @node Representation Clauses
31495 @section Representation Clauses
31496
31497 @noindent
31498 The Ada 83 reference manual was quite vague in describing both the minimal
31499 required implementation of representation clauses, and also their precise
31500 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31501 minimal set of capabilities required is still quite limited.
31502
31503 GNAT implements the full required set of capabilities in
31504 Ada 95 and Ada 2005, but also goes much further, and in particular
31505 an effort has been made to be compatible with existing Ada 83 usage to the
31506 greatest extent possible.
31507
31508 A few cases exist in which Ada 83 compiler behavior is incompatible with
31509 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31510 intentional or accidental dependence on specific implementation dependent
31511 characteristics of these Ada 83 compilers.  The following is a list of
31512 the cases most likely to arise in existing Ada 83 code.
31513
31514 @table @emph
31515 @item Implicit Packing
31516 Some Ada 83 compilers allowed a Size specification to cause implicit
31517 packing of an array or record.  This could cause expensive implicit
31518 conversions for change of representation in the presence of derived
31519 types, and the Ada design intends to avoid this possibility.
31520 Subsequent AI's were issued to make it clear that such implicit
31521 change of representation in response to a Size clause is inadvisable,
31522 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31523 Reference Manuals as implementation advice that is followed by GNAT@.
31524 The problem will show up as an error
31525 message rejecting the size clause.  The fix is simply to provide
31526 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31527 a Component_Size clause.
31528
31529 @item Meaning of Size Attribute
31530 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31531 the minimal number of bits required to hold values of the type.  For example,
31532 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31533 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31534 some 32 in this situation.  This problem will usually show up as a compile
31535 time error, but not always.  It is a good idea to check all uses of the
31536 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31537 Object_Size can provide a useful way of duplicating the behavior of
31538 some Ada 83 compiler systems.
31539
31540 @item Size of Access Types
31541 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31542 and that therefore it will be the same size as a System.Address value.  This
31543 assumption is true for GNAT in most cases with one exception.  For the case of
31544 a pointer to an unconstrained array type (where the bounds may vary from one
31545 value of the access type to another), the default is to use a ``fat pointer'',
31546 which is represented as two separate pointers, one to the bounds, and one to
31547 the array.  This representation has a number of advantages, including improved
31548 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31549 code which makes the assumption that, for example, pointers fit in 32 bits on
31550 a machine with 32-bit addressing.
31551
31552 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31553 access types in this case (where the designated type is an unconstrained array
31554 type).  These thin pointers are indeed the same size as a System.Address value.
31555 To specify a thin pointer, use a size clause for the type, for example:
31556
31557 @smallexample @c ada
31558 type X is access all String;
31559 for X'Size use Standard'Address_Size;
31560 @end smallexample
31561
31562 @noindent
31563 which will cause the type X to be represented using a single pointer.
31564 When using this representation, the bounds are right behind the array.
31565 This representation is slightly less efficient, and does not allow quite
31566 such flexibility in the use of foreign pointers or in using the
31567 Unrestricted_Access attribute to create pointers to non-aliased objects.
31568 But for any standard portable use of the access type it will work in
31569 a functionally correct manner and allow porting of existing code.
31570 Note that another way of forcing a thin pointer representation
31571 is to use a component size clause for the element size in an array,
31572 or a record representation clause for an access field in a record.
31573 @end table
31574
31575 @ifclear vms
31576 @c This brief section is only in the non-VMS version
31577 @c The complete chapter on HP Ada is in the VMS version
31578 @node Compatibility with HP Ada 83
31579 @section Compatibility with HP Ada 83
31580
31581 @noindent
31582 The VMS version of GNAT fully implements all the pragmas and attributes
31583 provided by HP Ada 83, as well as providing the standard HP Ada 83
31584 libraries, including Starlet.  In addition, data layouts and parameter
31585 passing conventions are highly compatible.  This means that porting
31586 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31587 most other porting efforts.  The following are some of the most
31588 significant differences between GNAT and HP Ada 83.
31589
31590 @table @emph
31591 @item Default floating-point representation
31592 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31593 it is VMS format.  GNAT does implement the necessary pragmas
31594 (Long_Float, Float_Representation) for changing this default.
31595
31596 @item System
31597 The package System in GNAT exactly corresponds to the definition in the
31598 Ada 95 reference manual, which means that it excludes many of the
31599 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31600 that contains the additional definitions, and a special pragma,
31601 Extend_System allows this package to be treated transparently as an
31602 extension of package System.
31603
31604 @item To_Address
31605 The definitions provided by Aux_DEC are exactly compatible with those
31606 in the HP Ada 83 version of System, with one exception.
31607 HP Ada provides the following declarations:
31608
31609 @smallexample @c ada
31610 TO_ADDRESS (INTEGER)
31611 TO_ADDRESS (UNSIGNED_LONGWORD)
31612 TO_ADDRESS (@i{universal_integer})
31613 @end smallexample
31614
31615 @noindent
31616 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31617 an extension to Ada 83 not strictly compatible with the reference manual.
31618 In GNAT, we are constrained to be exactly compatible with the standard,
31619 and this means we cannot provide this capability.  In HP Ada 83, the
31620 point of this definition is to deal with a call like:
31621
31622 @smallexample @c ada
31623 TO_ADDRESS (16#12777#);
31624 @end smallexample
31625
31626 @noindent
31627 Normally, according to the Ada 83 standard, one would expect this to be
31628 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31629 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31630 definition using @i{universal_integer} takes precedence.
31631
31632 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31633 is not possible to be 100% compatible.  Since there are many programs using
31634 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31635 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31636 declarations provided in the GNAT version of AUX_Dec are:
31637
31638 @smallexample @c ada
31639 function To_Address (X : Integer) return Address;
31640 pragma Pure_Function (To_Address);
31641
31642 function To_Address_Long (X : Unsigned_Longword)
31643  return Address;
31644 pragma Pure_Function (To_Address_Long);
31645 @end smallexample
31646
31647 @noindent
31648 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31649 change the name to TO_ADDRESS_LONG@.
31650
31651 @item Task_Id values
31652 The Task_Id values assigned will be different in the two systems, and GNAT
31653 does not provide a specified value for the Task_Id of the environment task,
31654 which in GNAT is treated like any other declared task.
31655 @end table
31656
31657 @noindent
31658 For full details on these and other less significant compatibility issues,
31659 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31660 Overview and Comparison on HP Platforms}.
31661
31662 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31663 attributes are recognized, although only a subset of them can sensibly
31664 be implemented.  The description of pragmas in @ref{Implementation
31665 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31666 indicates whether or not they are applicable to non-VMS systems.
31667 @end ifclear
31668
31669 @ifset vms
31670 @node Transitioning to 64-Bit GNAT for OpenVMS
31671 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31672
31673 @noindent
31674 This section is meant to assist users of pre-2006 @value{EDITION}
31675 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31676 the version of the GNAT technology supplied in 2006 and later for
31677 OpenVMS on both Alpha and I64.
31678
31679 @menu
31680 * Introduction to transitioning::
31681 * Migration of 32 bit code::
31682 * Taking advantage of 64 bit addressing::
31683 * Technical details::
31684 @end menu
31685
31686 @node Introduction to transitioning
31687 @subsection Introduction
31688
31689 @noindent
31690 64-bit @value{EDITION} for Open VMS has been designed to meet
31691 three main goals:
31692
31693 @enumerate
31694 @item
31695 Providing a full conforming implementation of Ada 95 and Ada 2005
31696
31697 @item
31698 Allowing maximum backward compatibility, thus easing migration of existing
31699 Ada source code
31700
31701 @item
31702 Supplying a path for exploiting the full 64-bit address range
31703 @end enumerate
31704
31705 @noindent
31706 Ada's strong typing semantics has made it
31707 impractical to have different 32-bit and 64-bit modes. As soon as
31708 one object could possibly be outside the 32-bit address space, this
31709 would make it necessary for the @code{System.Address} type to be 64 bits.
31710 In particular, this would cause inconsistencies if 32-bit code is
31711 called from 64-bit code that raises an exception.
31712
31713 This issue has been resolved by always using 64-bit addressing
31714 at the system level, but allowing for automatic conversions between
31715 32-bit and 64-bit addresses where required. Thus users who
31716 do not currently require 64-bit addressing capabilities, can
31717 recompile their code with only minimal changes (and indeed
31718 if the code is written in portable Ada, with no assumptions about
31719 the size of the @code{Address} type, then no changes at all are necessary).
31720 At the same time,
31721 this approach provides a simple, gradual upgrade path to future
31722 use of larger memories than available for 32-bit systems.
31723 Also, newly written applications or libraries will by default
31724 be fully compatible with future systems exploiting 64-bit
31725 addressing capabilities.
31726
31727 @ref{Migration of 32 bit code}, will focus on porting applications
31728 that do not require more than 2 GB of
31729 addressable memory. This code will be referred to as
31730 @emph{32-bit code}.
31731 For applications intending to exploit the full 64-bit address space,
31732 @ref{Taking advantage of 64 bit addressing},
31733 will consider further changes that may be required.
31734 Such code will be referred to below as @emph{64-bit code}.
31735
31736 @node Migration of 32 bit code
31737 @subsection Migration of 32-bit code
31738
31739 @menu
31740 * Address types::
31741 * Access types::
31742 * Unchecked conversions::
31743 * Predefined constants::
31744 * Interfacing with C::
31745 * Experience with source compatibility::
31746 @end menu
31747
31748 @node Address types
31749 @subsubsection Address types
31750
31751 @noindent
31752 To solve the problem of mixing 64-bit and 32-bit addressing,
31753 while maintaining maximum backward compatibility, the following
31754 approach has been taken:
31755
31756 @itemize @bullet
31757 @item
31758 @code{System.Address} always has a size of 64 bits
31759
31760 @item
31761 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31762 @end itemize
31763
31764 @noindent
31765 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31766 a @code{Short_Address}
31767 may be used where an @code{Address} is required, and vice versa, without
31768 needing explicit type conversions.
31769 By virtue of the Open VMS parameter passing conventions,
31770 even imported
31771 and exported subprograms that have 32-bit address parameters are
31772 compatible with those that have 64-bit address parameters.
31773 (See @ref{Making code 64 bit clean} for details.)
31774
31775 The areas that may need attention are those where record types have
31776 been defined that contain components of the type @code{System.Address}, and
31777 where objects of this type are passed to code expecting a record layout with
31778 32-bit addresses.
31779
31780 Different compilers on different platforms cannot be
31781 expected to represent the same type in the same way,
31782 since alignment constraints
31783 and other system-dependent properties affect the compiler's decision.
31784 For that reason, Ada code
31785 generally uses representation clauses to specify the expected
31786 layout where required.
31787
31788 If such a representation clause uses 32 bits for a component having
31789 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31790 will detect that error and produce a specific diagnostic message.
31791 The developer should then determine whether the representation
31792 should be 64 bits or not and make either of two changes:
31793 change the size to 64 bits and leave the type as @code{System.Address}, or
31794 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31795 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31796 required in any code setting or accessing the field; the compiler will
31797 automatically perform any needed conversions between address
31798 formats.
31799
31800 @node Access types
31801 @subsubsection Access types
31802
31803 @noindent
31804 By default, objects designated by access values are always
31805 allocated in the 32-bit
31806 address space. Thus legacy code will never contain
31807 any objects that are not addressable with 32-bit addresses, and
31808 the compiler will never raise exceptions as result of mixing
31809 32-bit and 64-bit addresses.
31810
31811 However, the access values themselves are represented in 64 bits, for optimum
31812 performance and future compatibility with 64-bit code. As was
31813 the case with @code{System.Address}, the compiler will give an error message
31814 if an object or record component has a representation clause that
31815 requires the access value to fit in 32 bits. In such a situation,
31816 an explicit size clause for the access type, specifying 32 bits,
31817 will have the desired effect.
31818
31819 General access types (declared with @code{access all}) can never be
31820 32 bits, as values of such types must be able to refer to any object
31821 of the  designated type,
31822 including objects residing outside the 32-bit address range.
31823 Existing Ada 83 code will not contain such type definitions,
31824 however, since general access types were introduced in Ada 95.
31825
31826 @node Unchecked conversions
31827 @subsubsection Unchecked conversions
31828
31829 @noindent
31830 In the case of an @code{Unchecked_Conversion} where the source type is a
31831 64-bit access type or the type @code{System.Address}, and the target
31832 type is a 32-bit type, the compiler will generate a warning.
31833 Even though the generated code will still perform the required
31834 conversions, it is highly recommended in these cases to use
31835 respectively a 32-bit access type or @code{System.Short_Address}
31836 as the source type.
31837
31838 @node Predefined constants
31839 @subsubsection Predefined constants
31840
31841 @noindent
31842 The following table shows the correspondence between pre-2006 versions of
31843 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31844 (``New''):
31845
31846 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31847 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31848 @item   @code{System.Word_Size}          @tab 32      @tab 64
31849 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31850 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31851 @item   @code{System.Address_Size}       @tab 32      @tab 64
31852 @end multitable
31853
31854 @noindent
31855 If you need to refer to the specific
31856 memory size of a 32-bit implementation, instead of the
31857 actual memory size, use @code{System.Short_Memory_Size}
31858 rather than @code{System.Memory_Size}.
31859 Similarly, references to @code{System.Address_Size} may need
31860 to be replaced by @code{System.Short_Address'Size}.
31861 The program @command{gnatfind} may be useful for locating
31862 references to the above constants, so that you can verify that they
31863 are still correct.
31864
31865 @node Interfacing with C
31866 @subsubsection Interfacing with C
31867
31868 @noindent
31869 In order to minimize the impact of the transition to 64-bit addresses on
31870 legacy programs, some fundamental types in the @code{Interfaces.C}
31871 package hierarchy continue to be represented in 32 bits.
31872 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31873 This eases integration with the default HP C layout choices, for example
31874 as found in the system routines in @code{DECC$SHR.EXE}.
31875 Because of this implementation choice, the type fully compatible with
31876 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31877 Depending on the context the compiler will issue a
31878 warning or an error when type @code{Address} is used, alerting the user to a
31879 potential problem. Otherwise 32-bit programs that use
31880 @code{Interfaces.C} should normally not require code modifications
31881
31882 The other issue arising with C interfacing concerns pragma @code{Convention}.
31883 For VMS 64-bit systems, there is an issue of the appropriate default size
31884 of C convention pointers in the absence of an explicit size clause. The HP
31885 C compiler can choose either 32 or 64 bits depending on compiler options.
31886 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31887 clause is given. This proves a better choice for porting 32-bit legacy
31888 applications. In order to have a 64-bit representation, it is necessary to
31889 specify a size representation clause. For example:
31890
31891 @smallexample @c ada
31892 type int_star is access Interfaces.C.int;
31893 pragma Convention(C, int_star);
31894 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31895 @end smallexample
31896
31897 @node Experience with source compatibility
31898 @subsubsection Experience with source compatibility
31899
31900 @noindent
31901 The Security Server and STARLET on I64 provide an interesting ``test case''
31902 for source compatibility issues, since it is in such system code
31903 where assumptions about @code{Address} size might be expected to occur.
31904 Indeed, there were a small number of occasions in the Security Server
31905 file @file{jibdef.ads}
31906 where a representation clause for a record type specified
31907 32 bits for a component of type @code{Address}.
31908 All of these errors were detected by the compiler.
31909 The repair was obvious and immediate; to simply replace @code{Address} by
31910 @code{Short_Address}.
31911
31912 In the case of STARLET, there were several record types that should
31913 have had representation clauses but did not.  In these record types
31914 there was an implicit assumption that an @code{Address} value occupied
31915 32 bits.
31916 These compiled without error, but their usage resulted in run-time error
31917 returns from STARLET system calls.
31918 Future GNAT technology enhancements may include a tool that detects and flags
31919 these sorts of potential source code porting problems.
31920
31921 @c ****************************************
31922 @node Taking advantage of 64 bit addressing
31923 @subsection Taking advantage of 64-bit addressing
31924
31925 @menu
31926 * Making code 64 bit clean::
31927 * Allocating memory from the 64 bit storage pool::
31928 * Restrictions on use of 64 bit objects::
31929 * Using 64 bit storage pools by default::
31930 * General access types::
31931 * STARLET and other predefined libraries::
31932 @end menu
31933
31934 @node Making code 64 bit clean
31935 @subsubsection Making code 64-bit clean
31936
31937 @noindent
31938 In order to prevent problems that may occur when (parts of) a
31939 system start using memory outside the 32-bit address range,
31940 we recommend some additional guidelines:
31941
31942 @itemize @bullet
31943 @item
31944 For imported subprograms that take parameters of the
31945 type @code{System.Address}, ensure that these subprograms can
31946 indeed handle 64-bit addresses. If not, or when in doubt,
31947 change the subprogram declaration to specify
31948 @code{System.Short_Address} instead.
31949
31950 @item
31951 Resolve all warnings related to size mismatches in
31952 unchecked conversions. Failing to do so causes
31953 erroneous execution if the source object is outside
31954 the 32-bit address space.
31955
31956 @item
31957 (optional) Explicitly use the 32-bit storage pool
31958 for access types used in a 32-bit context, or use
31959 generic access types where possible
31960 (@pxref{Restrictions on use of 64 bit objects}).
31961 @end itemize
31962
31963 @noindent
31964 If these rules are followed, the compiler will automatically insert
31965 any necessary checks to ensure that no addresses or access values
31966 passed to 32-bit code ever refer to objects outside the 32-bit
31967 address range.
31968 Any attempt to do this will raise @code{Constraint_Error}.
31969
31970 @node Allocating memory from the 64 bit storage pool
31971 @subsubsection Allocating memory from the 64-bit storage pool
31972
31973 @noindent
31974 For any access type @code{T} that potentially requires memory allocations
31975 beyond the 32-bit address space,
31976 use the following representation clause:
31977
31978 @smallexample @c ada
31979    for T'Storage_Pool use System.Pool_64;
31980 @end smallexample
31981
31982 @node Restrictions on use of 64 bit objects
31983 @subsubsection Restrictions on use of 64-bit objects
31984
31985 @noindent
31986 Taking the address of an object allocated from a 64-bit storage pool,
31987 and then passing this address to a subprogram expecting
31988 @code{System.Short_Address},
31989 or assigning it to a variable of type @code{Short_Address}, will cause
31990 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31991 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31992 no exception is raised and execution
31993 will become erroneous.
31994
31995 @node Using 64 bit storage pools by default
31996 @subsubsection Using 64-bit storage pools by default
31997
31998 @noindent
31999 In some cases it may be desirable to have the compiler allocate
32000 from 64-bit storage pools by default. This may be the case for
32001 libraries that are 64-bit clean, but may be used in both 32-bit
32002 and 64-bit contexts. For these cases the following configuration
32003 pragma may be specified:
32004
32005 @smallexample @c ada
32006   pragma Pool_64_Default;
32007 @end smallexample
32008
32009 @noindent
32010 Any code compiled in the context of this pragma will by default
32011 use the @code{System.Pool_64} storage pool. This default may be overridden
32012 for a specific access type @code{T} by the representation clause:
32013
32014 @smallexample @c ada
32015    for T'Storage_Pool use System.Pool_32;
32016 @end smallexample
32017
32018 @noindent
32019 Any object whose address may be passed to a subprogram with a
32020 @code{Short_Address} argument, or assigned to a variable of type
32021 @code{Short_Address}, needs to be allocated from this pool.
32022
32023 @node General access types
32024 @subsubsection General access types
32025
32026 @noindent
32027 Objects designated by access values from a
32028 general access type (declared with @code{access all}) are never allocated
32029 from a 64-bit storage pool. Code that uses general access types will
32030 accept objects allocated in either 32-bit or 64-bit address spaces,
32031 but never allocate objects outside the 32-bit address space.
32032 Using general access types ensures maximum compatibility with both
32033 32-bit and 64-bit code.
32034
32035 @node STARLET and other predefined libraries
32036 @subsubsection STARLET and other predefined libraries
32037
32038 @noindent
32039 All code that comes as part of GNAT is 64-bit clean, but the
32040 restrictions given in @ref{Restrictions on use of 64 bit objects},
32041 still apply. Look at the package
32042 specs to see in which contexts objects allocated
32043 in 64-bit address space are acceptable.
32044
32045 @node Technical details
32046 @subsection Technical details
32047
32048 @noindent
32049 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
32050 Ada standard with respect to the type of @code{System.Address}. Previous
32051 versions of GNAT Pro have defined this type as private and implemented it as a
32052 modular type.
32053
32054 In order to allow defining @code{System.Short_Address} as a proper subtype,
32055 and to match the implicit sign extension in parameter passing,
32056 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
32057 visible (i.e., non-private) integer type.
32058 Standard operations on the type, such as the binary operators ``+'', ``-'',
32059 etc., that take @code{Address} operands and return an @code{Address} result,
32060 have been hidden by declaring these
32061 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
32062 ambiguities that would otherwise result from overloading.
32063 (Note that, although @code{Address} is a visible integer type,
32064 good programming practice dictates against exploiting the type's
32065 integer properties such as literals, since this will compromise
32066 code portability.)
32067
32068 Defining @code{Address} as a visible integer type helps achieve
32069 maximum compatibility for existing Ada code,
32070 without sacrificing the capabilities of the 64-bit architecture.
32071 @end ifset
32072
32073 @c ************************************************
32074 @ifset unw
32075 @node Microsoft Windows Topics
32076 @appendix Microsoft Windows Topics
32077 @cindex Windows NT
32078 @cindex Windows 95
32079 @cindex Windows 98
32080
32081 @noindent
32082 This chapter describes topics that are specific to the Microsoft Windows
32083 platforms (NT, 2000, and XP Professional).
32084
32085 @menu
32086 * Using GNAT on Windows::
32087 * Using a network installation of GNAT::
32088 * CONSOLE and WINDOWS subsystems::
32089 * Temporary Files::
32090 * Mixed-Language Programming on Windows::
32091 * Windows Calling Conventions::
32092 * Introduction to Dynamic Link Libraries (DLLs)::
32093 * Using DLLs with GNAT::
32094 * Building DLLs with GNAT::
32095 * Building DLLs with GNAT Project files::
32096 * Building DLLs with gnatdll::
32097 * GNAT and Windows Resources::
32098 * Debugging a DLL::
32099 * Setting Stack Size from gnatlink::
32100 * Setting Heap Size from gnatlink::
32101 @end menu
32102
32103 @node Using GNAT on Windows
32104 @section Using GNAT on Windows
32105
32106 @noindent
32107 One of the strengths of the GNAT technology is that its tool set
32108 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
32109 @code{gdb} debugger, etc.) is used in the same way regardless of the
32110 platform.
32111
32112 On Windows this tool set is complemented by a number of Microsoft-specific
32113 tools that have been provided to facilitate interoperability with Windows
32114 when this is required. With these tools:
32115
32116 @itemize @bullet
32117
32118 @item
32119 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
32120 subsystems.
32121
32122 @item
32123 You can use any Dynamically Linked Library (DLL) in your Ada code (both
32124 relocatable and non-relocatable DLLs are supported).
32125
32126 @item
32127 You can build Ada DLLs for use in other applications. These applications
32128 can be written in a language other than Ada (e.g., C, C++, etc). Again both
32129 relocatable and non-relocatable Ada DLLs are supported.
32130
32131 @item
32132 You can include Windows resources in your Ada application.
32133
32134 @item
32135 You can use or create COM/DCOM objects.
32136 @end itemize
32137
32138 @noindent
32139 Immediately below are listed all known general GNAT-for-Windows restrictions.
32140 Other restrictions about specific features like Windows Resources and DLLs
32141 are listed in separate sections below.
32142
32143 @itemize @bullet
32144
32145 @item
32146 It is not possible to use @code{GetLastError} and @code{SetLastError}
32147 when tasking, protected records, or exceptions are used. In these
32148 cases, in order to implement Ada semantics, the GNAT run-time system
32149 calls certain Win32 routines that set the last error variable to 0 upon
32150 success. It should be possible to use @code{GetLastError} and
32151 @code{SetLastError} when tasking, protected record, and exception
32152 features are not used, but it is not guaranteed to work.
32153
32154 @item
32155 It is not possible to link against Microsoft libraries except for
32156 import libraries. The library must be built to be compatible with
32157 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
32158 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
32159 not be compatible with the GNAT runtime. Even if the library is
32160 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
32161
32162 @item
32163 When the compilation environment is located on FAT32 drives, users may
32164 experience recompilations of the source files that have not changed if
32165 Daylight Saving Time (DST) state has changed since the last time files
32166 were compiled. NTFS drives do not have this problem.
32167
32168 @item
32169 No components of the GNAT toolset use any entries in the Windows
32170 registry. The only entries that can be created are file associations and
32171 PATH settings, provided the user has chosen to create them at installation
32172 time, as well as some minimal book-keeping information needed to correctly
32173 uninstall or integrate different GNAT products.
32174 @end itemize
32175
32176 @node Using a network installation of GNAT
32177 @section Using a network installation of GNAT
32178
32179 @noindent
32180 Make sure the system on which GNAT is installed is accessible from the
32181 current machine, i.e., the install location is shared over the network.
32182 Shared resources are accessed on Windows by means of UNC paths, which
32183 have the format @code{\\server\sharename\path}
32184
32185 In order to use such a network installation, simply add the UNC path of the
32186 @file{bin} directory of your GNAT installation in front of your PATH. For
32187 example, if GNAT is installed in @file{\GNAT} directory of a share location
32188 called @file{c-drive} on a machine @file{LOKI}, the following command will
32189 make it available:
32190
32191 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
32192
32193 Be aware that every compilation using the network installation results in the
32194 transfer of large amounts of data across the network and will likely cause
32195 serious performance penalty.
32196
32197 @node CONSOLE and WINDOWS subsystems
32198 @section CONSOLE and WINDOWS subsystems
32199 @cindex CONSOLE Subsystem
32200 @cindex WINDOWS Subsystem
32201 @cindex -mwindows
32202
32203 @noindent
32204 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
32205 (which is the default subsystem) will always create a console when
32206 launching the application. This is not something desirable when the
32207 application has a Windows GUI. To get rid of this console the
32208 application must be using the @code{WINDOWS} subsystem. To do so
32209 the @option{-mwindows} linker option must be specified.
32210
32211 @smallexample
32212 $ gnatmake winprog -largs -mwindows
32213 @end smallexample
32214
32215 @node Temporary Files
32216 @section Temporary Files
32217 @cindex Temporary files
32218
32219 @noindent
32220 It is possible to control where temporary files gets created by setting
32221 the @env{TMP} environment variable. The file will be created:
32222
32223 @itemize
32224 @item Under the directory pointed to by the @env{TMP} environment variable if
32225 this directory exists.
32226
32227 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
32228 set (or not pointing to a directory) and if this directory exists.
32229
32230 @item Under the current working directory otherwise.
32231 @end itemize
32232
32233 @noindent
32234 This allows you to determine exactly where the temporary
32235 file will be created. This is particularly useful in networked
32236 environments where you may not have write access to some
32237 directories.
32238
32239 @node Mixed-Language Programming on Windows
32240 @section Mixed-Language Programming on Windows
32241
32242 @noindent
32243 Developing pure Ada applications on Windows is no different than on
32244 other GNAT-supported platforms. However, when developing or porting an
32245 application that contains a mix of Ada and C/C++, the choice of your
32246 Windows C/C++ development environment conditions your overall
32247 interoperability strategy.
32248
32249 If you use @command{gcc} to compile the non-Ada part of your application,
32250 there are no Windows-specific restrictions that affect the overall
32251 interoperability with your Ada code. If you plan to use
32252 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32253 the following limitations:
32254
32255 @itemize @bullet
32256 @item
32257 You cannot link your Ada code with an object or library generated with
32258 Microsoft tools if these use the @code{.tls} section (Thread Local
32259 Storage section) since the GNAT linker does not yet support this section.
32260
32261 @item
32262 You cannot link your Ada code with an object or library generated with
32263 Microsoft tools if these use I/O routines other than those provided in
32264 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32265 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32266 libraries can cause a conflict with @code{msvcrt.dll} services. For
32267 instance Visual C++ I/O stream routines conflict with those in
32268 @code{msvcrt.dll}.
32269 @end itemize
32270
32271 @noindent
32272 If you do want to use the Microsoft tools for your non-Ada code and hit one
32273 of the above limitations, you have two choices:
32274
32275 @enumerate
32276 @item
32277 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32278 application. In this case, use the Microsoft or whatever environment to
32279 build the DLL and use GNAT to build your executable
32280 (@pxref{Using DLLs with GNAT}).
32281
32282 @item
32283 Or you can encapsulate your Ada code in a DLL to be linked with the
32284 other part of your application. In this case, use GNAT to build the DLL
32285 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32286 environment to build your executable.
32287 @end enumerate
32288
32289 @node Windows Calling Conventions
32290 @section Windows Calling Conventions
32291 @findex Stdcall
32292 @findex APIENTRY
32293
32294 @menu
32295 * C Calling Convention::
32296 * Stdcall Calling Convention::
32297 * Win32 Calling Convention::
32298 * DLL Calling Convention::
32299 @end menu
32300
32301 @noindent
32302 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32303 (callee), there are several ways to push @code{G}'s parameters on the
32304 stack and there are several possible scenarios to clean up the stack
32305 upon @code{G}'s return. A calling convention is an agreed upon software
32306 protocol whereby the responsibilities between the caller (@code{F}) and
32307 the callee (@code{G}) are clearly defined. Several calling conventions
32308 are available for Windows:
32309
32310 @itemize @bullet
32311 @item
32312 @code{C} (Microsoft defined)
32313
32314 @item
32315 @code{Stdcall} (Microsoft defined)
32316
32317 @item
32318 @code{Win32} (GNAT specific)
32319
32320 @item
32321 @code{DLL} (GNAT specific)
32322 @end itemize
32323
32324 @node C Calling Convention
32325 @subsection @code{C} Calling Convention
32326
32327 @noindent
32328 This is the default calling convention used when interfacing to C/C++
32329 routines compiled with either @command{gcc} or Microsoft Visual C++.
32330
32331 In the @code{C} calling convention subprogram parameters are pushed on the
32332 stack by the caller from right to left. The caller itself is in charge of
32333 cleaning up the stack after the call. In addition, the name of a routine
32334 with @code{C} calling convention is mangled by adding a leading underscore.
32335
32336 The name to use on the Ada side when importing (or exporting) a routine
32337 with @code{C} calling convention is the name of the routine. For
32338 instance the C function:
32339
32340 @smallexample
32341 int get_val (long);
32342 @end smallexample
32343
32344 @noindent
32345 should be imported from Ada as follows:
32346
32347 @smallexample @c ada
32348 @group
32349 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32350 pragma Import (C, Get_Val, External_Name => "get_val");
32351 @end group
32352 @end smallexample
32353
32354 @noindent
32355 Note that in this particular case the @code{External_Name} parameter could
32356 have been omitted since, when missing, this parameter is taken to be the
32357 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32358 is missing, as in the above example, this parameter is set to be the
32359 @code{External_Name} with a leading underscore.
32360
32361 When importing a variable defined in C, you should always use the @code{C}
32362 calling convention unless the object containing the variable is part of a
32363 DLL (in which case you should use the @code{Stdcall} calling
32364 convention, @pxref{Stdcall Calling Convention}).
32365
32366 @node Stdcall Calling Convention
32367 @subsection @code{Stdcall} Calling Convention
32368
32369 @noindent
32370 This convention, which was the calling convention used for Pascal
32371 programs, is used by Microsoft for all the routines in the Win32 API for
32372 efficiency reasons. It must be used to import any routine for which this
32373 convention was specified.
32374
32375 In the @code{Stdcall} calling convention subprogram parameters are pushed
32376 on the stack by the caller from right to left. The callee (and not the
32377 caller) is in charge of cleaning the stack on routine exit. In addition,
32378 the name of a routine with @code{Stdcall} calling convention is mangled by
32379 adding a leading underscore (as for the @code{C} calling convention) and a
32380 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32381 bytes) of the parameters passed to the routine.
32382
32383 The name to use on the Ada side when importing a C routine with a
32384 @code{Stdcall} calling convention is the name of the C routine. The leading
32385 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32386 the compiler. For instance the Win32 function:
32387
32388 @smallexample
32389 @b{APIENTRY} int get_val (long);
32390 @end smallexample
32391
32392 @noindent
32393 should be imported from Ada as follows:
32394
32395 @smallexample @c ada
32396 @group
32397 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32398 pragma Import (Stdcall, Get_Val);
32399 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32400 @end group
32401 @end smallexample
32402
32403 @noindent
32404 As for the @code{C} calling convention, when the @code{External_Name}
32405 parameter is missing, it is taken to be the name of the Ada entity in lower
32406 case. If instead of writing the above import pragma you write:
32407
32408 @smallexample @c ada
32409 @group
32410 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32411 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32412 @end group
32413 @end smallexample
32414
32415 @noindent
32416 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32417 of specifying the @code{External_Name} parameter you specify the
32418 @code{Link_Name} as in the following example:
32419
32420 @smallexample @c ada
32421 @group
32422 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32423 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32424 @end group
32425 @end smallexample
32426
32427 @noindent
32428 then the imported routine is @code{retrieve_val}, that is, there is no
32429 decoration at all. No leading underscore and no Stdcall suffix
32430 @code{@@}@code{@var{nn}}.
32431
32432 @noindent
32433 This is especially important as in some special cases a DLL's entry
32434 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32435 name generated for a call has it.
32436
32437 @noindent
32438 It is also possible to import variables defined in a DLL by using an
32439 import pragma for a variable. As an example, if a DLL contains a
32440 variable defined as:
32441
32442 @smallexample
32443 int my_var;
32444 @end smallexample
32445
32446 @noindent
32447 then, to access this variable from Ada you should write:
32448
32449 @smallexample @c ada
32450 @group
32451 My_Var : Interfaces.C.int;
32452 pragma Import (Stdcall, My_Var);
32453 @end group
32454 @end smallexample
32455
32456 @noindent
32457 Note that to ease building cross-platform bindings this convention
32458 will be handled as a @code{C} calling convention on non-Windows platforms.
32459
32460 @node Win32 Calling Convention
32461 @subsection @code{Win32} Calling Convention
32462
32463 @noindent
32464 This convention, which is GNAT-specific is fully equivalent to the
32465 @code{Stdcall} calling convention described above.
32466
32467 @node DLL Calling Convention
32468 @subsection @code{DLL} Calling Convention
32469
32470 @noindent
32471 This convention, which is GNAT-specific is fully equivalent to the
32472 @code{Stdcall} calling convention described above.
32473
32474 @node Introduction to Dynamic Link Libraries (DLLs)
32475 @section Introduction to Dynamic Link Libraries (DLLs)
32476 @findex DLL
32477
32478 @noindent
32479 A Dynamically Linked Library (DLL) is a library that can be shared by
32480 several applications running under Windows. A DLL can contain any number of
32481 routines and variables.
32482
32483 One advantage of DLLs is that you can change and enhance them without
32484 forcing all the applications that depend on them to be relinked or
32485 recompiled. However, you should be aware than all calls to DLL routines are
32486 slower since, as you will understand below, such calls are indirect.
32487
32488 To illustrate the remainder of this section, suppose that an application
32489 wants to use the services of a DLL @file{API.dll}. To use the services
32490 provided by @file{API.dll} you must statically link against the DLL or
32491 an import library which contains a jump table with an entry for each
32492 routine and variable exported by the DLL. In the Microsoft world this
32493 import library is called @file{API.lib}. When using GNAT this import
32494 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32495 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32496
32497 After you have linked your application with the DLL or the import library
32498 and you run your application, here is what happens:
32499
32500 @enumerate
32501 @item
32502 Your application is loaded into memory.
32503
32504 @item
32505 The DLL @file{API.dll} is mapped into the address space of your
32506 application. This means that:
32507
32508 @itemize @bullet
32509 @item
32510 The DLL will use the stack of the calling thread.
32511
32512 @item
32513 The DLL will use the virtual address space of the calling process.
32514
32515 @item
32516 The DLL will allocate memory from the virtual address space of the calling
32517 process.
32518
32519 @item
32520 Handles (pointers) can be safely exchanged between routines in the DLL
32521 routines and routines in the application using the DLL.
32522 @end itemize
32523
32524 @item
32525 The entries in the jump table (from the import library @file{libAPI.dll.a}
32526 or @file{API.lib} or automatically created when linking against a DLL)
32527 which is part of your application are initialized with the addresses
32528 of the routines and variables in @file{API.dll}.
32529
32530 @item
32531 If present in @file{API.dll}, routines @code{DllMain} or
32532 @code{DllMainCRTStartup} are invoked. These routines typically contain
32533 the initialization code needed for the well-being of the routines and
32534 variables exported by the DLL.
32535 @end enumerate
32536
32537 @noindent
32538 There is an additional point which is worth mentioning. In the Windows
32539 world there are two kind of DLLs: relocatable and non-relocatable
32540 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32541 in the target application address space. If the addresses of two
32542 non-relocatable DLLs overlap and these happen to be used by the same
32543 application, a conflict will occur and the application will run
32544 incorrectly. Hence, when possible, it is always preferable to use and
32545 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32546 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32547 User's Guide) removes the debugging symbols from the DLL but the DLL can
32548 still be relocated.
32549
32550 As a side note, an interesting difference between Microsoft DLLs and
32551 Unix shared libraries, is the fact that on most Unix systems all public
32552 routines are exported by default in a Unix shared library, while under
32553 Windows it is possible (but not required) to list exported routines in
32554 a definition file (@pxref{The Definition File}).
32555
32556 @node Using DLLs with GNAT
32557 @section Using DLLs with GNAT
32558
32559 @menu
32560 * Creating an Ada Spec for the DLL Services::
32561 * Creating an Import Library::
32562 @end menu
32563
32564 @noindent
32565 To use the services of a DLL, say @file{API.dll}, in your Ada application
32566 you must have:
32567
32568 @enumerate
32569 @item
32570 The Ada spec for the routines and/or variables you want to access in
32571 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32572 header files provided with the DLL.
32573
32574 @item
32575 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32576 mentioned an import library is a statically linked library containing the
32577 import table which will be filled at load time to point to the actual
32578 @file{API.dll} routines. Sometimes you don't have an import library for the
32579 DLL you want to use. The following sections will explain how to build
32580 one. Note that this is optional.
32581
32582 @item
32583 The actual DLL, @file{API.dll}.
32584 @end enumerate
32585
32586 @noindent
32587 Once you have all the above, to compile an Ada application that uses the
32588 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32589 you simply issue the command
32590
32591 @smallexample
32592 $ gnatmake my_ada_app -largs -lAPI
32593 @end smallexample
32594
32595 @noindent
32596 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32597 tells the GNAT linker to look first for a library named @file{API.lib}
32598 (Microsoft-style name) and if not found for a libraries named
32599 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32600 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32601 contains the following pragma
32602
32603 @smallexample @c ada
32604 pragma Linker_Options ("-lAPI");
32605 @end smallexample
32606
32607 @noindent
32608 you do not have to add @option{-largs -lAPI} at the end of the
32609 @command{gnatmake} command.
32610
32611 If any one of the items above is missing you will have to create it
32612 yourself. The following sections explain how to do so using as an
32613 example a fictitious DLL called @file{API.dll}.
32614
32615 @node Creating an Ada Spec for the DLL Services
32616 @subsection Creating an Ada Spec for the DLL Services
32617
32618 @noindent
32619 A DLL typically comes with a C/C++ header file which provides the
32620 definitions of the routines and variables exported by the DLL. The Ada
32621 equivalent of this header file is a package spec that contains definitions
32622 for the imported entities. If the DLL you intend to use does not come with
32623 an Ada spec you have to generate one such spec yourself. For example if
32624 the header file of @file{API.dll} is a file @file{api.h} containing the
32625 following two definitions:
32626
32627 @smallexample
32628 @group
32629 @cartouche
32630 int some_var;
32631 int get (char *);
32632 @end cartouche
32633 @end group
32634 @end smallexample
32635
32636 @noindent
32637 then the equivalent Ada spec could be:
32638
32639 @smallexample @c ada
32640 @group
32641 @cartouche
32642 with Interfaces.C.Strings;
32643 package API is
32644    use Interfaces;
32645
32646    Some_Var : C.int;
32647    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32648
32649 private
32650    pragma Import (C, Get);
32651    pragma Import (DLL, Some_Var);
32652 end API;
32653 @end cartouche
32654 @end group
32655 @end smallexample
32656
32657 @noindent
32658 Note that a variable is
32659 @strong{always imported with a Stdcall convention}. A function
32660 can have @code{C} or @code{Stdcall} convention.
32661 (@pxref{Windows Calling Conventions}).
32662
32663 @node Creating an Import Library
32664 @subsection Creating an Import Library
32665 @cindex Import library
32666
32667 @menu
32668 * The Definition File::
32669 * GNAT-Style Import Library::
32670 * Microsoft-Style Import Library::
32671 @end menu
32672
32673 @noindent
32674 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32675 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32676 with @file{API.dll} you can skip this section. You can also skip this
32677 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32678 as in this case it is possible to link directly against the
32679 DLL. Otherwise read on.
32680
32681 @node The Definition File
32682 @subsubsection The Definition File
32683 @cindex Definition file
32684 @findex .def
32685
32686 @noindent
32687 As previously mentioned, and unlike Unix systems, the list of symbols
32688 that are exported from a DLL must be provided explicitly in Windows.
32689 The main goal of a definition file is precisely that: list the symbols
32690 exported by a DLL. A definition file (usually a file with a @code{.def}
32691 suffix) has the following structure:
32692
32693 @smallexample
32694 @group
32695 @cartouche
32696 @r{[}LIBRARY @var{name}@r{]}
32697 @r{[}DESCRIPTION @var{string}@r{]}
32698 EXPORTS
32699    @var{symbol1}
32700    @var{symbol2}
32701    @dots{}
32702 @end cartouche
32703 @end group
32704 @end smallexample
32705
32706 @table @code
32707 @item LIBRARY @var{name}
32708 This section, which is optional, gives the name of the DLL.
32709
32710 @item DESCRIPTION @var{string}
32711 This section, which is optional, gives a description string that will be
32712 embedded in the import library.
32713
32714 @item EXPORTS
32715 This section gives the list of exported symbols (procedures, functions or
32716 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32717 section of @file{API.def} looks like:
32718
32719 @smallexample
32720 @group
32721 @cartouche
32722 EXPORTS
32723    some_var
32724    get
32725 @end cartouche
32726 @end group
32727 @end smallexample
32728 @end table
32729
32730 @noindent
32731 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32732 (@pxref{Windows Calling Conventions}) for a Stdcall
32733 calling convention function in the exported symbols list.
32734
32735 @noindent
32736 There can actually be other sections in a definition file, but these
32737 sections are not relevant to the discussion at hand.
32738
32739 @node GNAT-Style Import Library
32740 @subsubsection GNAT-Style Import Library
32741
32742 @noindent
32743 To create a static import library from @file{API.dll} with the GNAT tools
32744 you should proceed as follows:
32745
32746 @enumerate
32747 @item
32748 Create the definition file @file{API.def} (@pxref{The Definition File}).
32749 For that use the @code{dll2def} tool as follows:
32750
32751 @smallexample
32752 $ dll2def API.dll > API.def
32753 @end smallexample
32754
32755 @noindent
32756 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32757 to standard output the list of entry points in the DLL. Note that if
32758 some routines in the DLL have the @code{Stdcall} convention
32759 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32760 suffix then you'll have to edit @file{api.def} to add it, and specify
32761 @option{-k} to @command{gnatdll} when creating the import library.
32762
32763 @noindent
32764 Here are some hints to find the right @code{@@}@var{nn} suffix.
32765
32766 @enumerate
32767 @item
32768 If you have the Microsoft import library (.lib), it is possible to get
32769 the right symbols by using Microsoft @code{dumpbin} tool (see the
32770 corresponding Microsoft documentation for further details).
32771
32772 @smallexample
32773 $ dumpbin /exports api.lib
32774 @end smallexample
32775
32776 @item
32777 If you have a message about a missing symbol at link time the compiler
32778 tells you what symbol is expected. You just have to go back to the
32779 definition file and add the right suffix.
32780 @end enumerate
32781
32782 @item
32783 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32784 (@pxref{Using gnatdll}) as follows:
32785
32786 @smallexample
32787 $ gnatdll -e API.def -d API.dll
32788 @end smallexample
32789
32790 @noindent
32791 @code{gnatdll} takes as input a definition file @file{API.def} and the
32792 name of the DLL containing the services listed in the definition file
32793 @file{API.dll}. The name of the static import library generated is
32794 computed from the name of the definition file as follows: if the
32795 definition file name is @var{xyz}@code{.def}, the import library name will
32796 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32797 @option{-e} could have been removed because the name of the definition
32798 file (before the ``@code{.def}'' suffix) is the same as the name of the
32799 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32800 @end enumerate
32801
32802 @node Microsoft-Style Import Library
32803 @subsubsection Microsoft-Style Import Library
32804
32805 @noindent
32806 With GNAT you can either use a GNAT-style or Microsoft-style import
32807 library. A Microsoft import library is needed only if you plan to make an
32808 Ada DLL available to applications developed with Microsoft
32809 tools (@pxref{Mixed-Language Programming on Windows}).
32810
32811 To create a Microsoft-style import library for @file{API.dll} you
32812 should proceed as follows:
32813
32814 @enumerate
32815 @item
32816 Create the definition file @file{API.def} from the DLL. For this use either
32817 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32818 tool (see the corresponding Microsoft documentation for further details).
32819
32820 @item
32821 Build the actual import library using Microsoft's @code{lib} utility:
32822
32823 @smallexample
32824 $ lib -machine:IX86 -def:API.def -out:API.lib
32825 @end smallexample
32826
32827 @noindent
32828 If you use the above command the definition file @file{API.def} must
32829 contain a line giving the name of the DLL:
32830
32831 @smallexample
32832 LIBRARY      "API"
32833 @end smallexample
32834
32835 @noindent
32836 See the Microsoft documentation for further details about the usage of
32837 @code{lib}.
32838 @end enumerate
32839
32840 @node Building DLLs with GNAT
32841 @section Building DLLs with GNAT
32842 @cindex DLLs, building
32843
32844 @noindent
32845 This section explain how to build DLLs using the GNAT built-in DLL
32846 support. With the following procedure it is straight forward to build
32847 and use DLLs with GNAT.
32848
32849 @enumerate
32850
32851 @item building object files
32852
32853 The first step is to build all objects files that are to be included
32854 into the DLL. This is done by using the standard @command{gnatmake} tool.
32855
32856 @item building the DLL
32857
32858 To build the DLL you must use @command{gcc}'s @option{-shared}
32859 option. It is quite simple to use this method:
32860
32861 @smallexample
32862 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32863 @end smallexample
32864
32865 It is important to note that in this case all symbols found in the
32866 object files are automatically exported. It is possible to restrict
32867 the set of symbols to export by passing to @command{gcc} a definition
32868 file, @pxref{The Definition File}. For example:
32869
32870 @smallexample
32871 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32872 @end smallexample
32873
32874 If you use a definition file you must export the elaboration procedures
32875 for every package that required one. Elaboration procedures are named
32876 using the package name followed by "_E".
32877
32878 @item preparing DLL to be used
32879
32880 For the DLL to be used by client programs the bodies must be hidden
32881 from it and the .ali set with read-only attribute. This is very important
32882 otherwise GNAT will recompile all packages and will not actually use
32883 the code in the DLL. For example:
32884
32885 @smallexample
32886 $ mkdir apilib
32887 $ copy *.ads *.ali api.dll apilib
32888 $ attrib +R apilib\*.ali
32889 @end smallexample
32890
32891 @end enumerate
32892
32893 At this point it is possible to use the DLL by directly linking
32894 against it. Note that you must use the GNAT shared runtime when using
32895 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32896 option.
32897
32898 @smallexample
32899 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32900 @end smallexample
32901
32902 @node Building DLLs with GNAT Project files
32903 @section Building DLLs with GNAT Project files
32904 @cindex DLLs, building
32905
32906 @noindent
32907 There is nothing specific to Windows in the build process.
32908 @pxref{Library Projects}.
32909
32910 @noindent
32911 Due to a system limitation, it is not possible under Windows to create threads
32912 when inside the @code{DllMain} routine which is used for auto-initialization
32913 of shared libraries, so it is not possible to have library level tasks in SALs.
32914
32915 @node Building DLLs with gnatdll
32916 @section Building DLLs with gnatdll
32917 @cindex DLLs, building
32918
32919 @menu
32920 * Limitations When Using Ada DLLs from Ada::
32921 * Exporting Ada Entities::
32922 * Ada DLLs and Elaboration::
32923 * Ada DLLs and Finalization::
32924 * Creating a Spec for Ada DLLs::
32925 * Creating the Definition File::
32926 * Using gnatdll::
32927 @end menu
32928
32929 @noindent
32930 Note that it is preferred to use the built-in GNAT DLL support
32931 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32932 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32933
32934 This section explains how to build DLLs containing Ada code using
32935 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32936 remainder of this section.
32937
32938 The steps required to build an Ada DLL that is to be used by Ada as well as
32939 non-Ada applications are as follows:
32940
32941 @enumerate
32942 @item
32943 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32944 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32945 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32946 skip this step if you plan to use the Ada DLL only from Ada applications.
32947
32948 @item
32949 Your Ada code must export an initialization routine which calls the routine
32950 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32951 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32952 routine exported by the Ada DLL must be invoked by the clients of the DLL
32953 to initialize the DLL.
32954
32955 @item
32956 When useful, the DLL should also export a finalization routine which calls
32957 routine @code{adafinal} generated by @command{gnatbind} to perform the
32958 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32959 The finalization routine exported by the Ada DLL must be invoked by the
32960 clients of the DLL when the DLL services are no further needed.
32961
32962 @item
32963 You must provide a spec for the services exported by the Ada DLL in each
32964 of the programming languages to which you plan to make the DLL available.
32965
32966 @item
32967 You must provide a definition file listing the exported entities
32968 (@pxref{The Definition File}).
32969
32970 @item
32971 Finally you must use @code{gnatdll} to produce the DLL and the import
32972 library (@pxref{Using gnatdll}).
32973 @end enumerate
32974
32975 @noindent
32976 Note that a relocatable DLL stripped using the @code{strip}
32977 binutils tool will not be relocatable anymore. To build a DLL without
32978 debug information pass @code{-largs -s} to @code{gnatdll}. This
32979 restriction does not apply to a DLL built using a Library Project.
32980 @pxref{Library Projects}.
32981
32982 @node Limitations When Using Ada DLLs from Ada
32983 @subsection Limitations When Using Ada DLLs from Ada
32984
32985 @noindent
32986 When using Ada DLLs from Ada applications there is a limitation users
32987 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32988 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32989 each Ada DLL includes the services of the GNAT run time that are necessary
32990 to the Ada code inside the DLL. As a result, when an Ada program uses an
32991 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32992 one in the main program.
32993
32994 It is therefore not possible to exchange GNAT run-time objects between the
32995 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32996 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32997 types, etc.
32998
32999 It is completely safe to exchange plain elementary, array or record types,
33000 Windows object handles, etc.
33001
33002 @node Exporting Ada Entities
33003 @subsection Exporting Ada Entities
33004 @cindex Export table
33005
33006 @noindent
33007 Building a DLL is a way to encapsulate a set of services usable from any
33008 application. As a result, the Ada entities exported by a DLL should be
33009 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
33010 any Ada name mangling. As an example here is an Ada package
33011 @code{API}, spec and body, exporting two procedures, a function, and a
33012 variable:
33013
33014 @smallexample @c ada
33015 @group
33016 @cartouche
33017 with Interfaces.C; use Interfaces;
33018 package API is
33019    Count : C.int := 0;
33020    function Factorial (Val : C.int) return C.int;
33021
33022    procedure Initialize_API;
33023    procedure Finalize_API;
33024    --  Initialization & Finalization routines. More in the next section.
33025 private
33026    pragma Export (C, Initialize_API);
33027    pragma Export (C, Finalize_API);
33028    pragma Export (C, Count);
33029    pragma Export (C, Factorial);
33030 end API;
33031 @end cartouche
33032 @end group
33033 @end smallexample
33034
33035 @smallexample @c ada
33036 @group
33037 @cartouche
33038 package body API is
33039    function Factorial (Val : C.int) return C.int is
33040       Fact : C.int := 1;
33041    begin
33042       Count := Count + 1;
33043       for K in 1 .. Val loop
33044          Fact := Fact * K;
33045       end loop;
33046       return Fact;
33047    end Factorial;
33048
33049    procedure Initialize_API is
33050       procedure Adainit;
33051       pragma Import (C, Adainit);
33052    begin
33053       Adainit;
33054    end Initialize_API;
33055
33056    procedure Finalize_API is
33057       procedure Adafinal;
33058       pragma Import (C, Adafinal);
33059    begin
33060       Adafinal;
33061    end Finalize_API;
33062 end API;
33063 @end cartouche
33064 @end group
33065 @end smallexample
33066
33067 @noindent
33068 If the Ada DLL you are building will only be used by Ada applications
33069 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
33070 convention. As an example, the previous package could be written as
33071 follows:
33072
33073 @smallexample @c ada
33074 @group
33075 @cartouche
33076 package API is
33077    Count : Integer := 0;
33078    function Factorial (Val : Integer) return Integer;
33079
33080    procedure Initialize_API;
33081    procedure Finalize_API;
33082    --  Initialization and Finalization routines.
33083 end API;
33084 @end cartouche
33085 @end group
33086 @end smallexample
33087
33088 @smallexample @c ada
33089 @group
33090 @cartouche
33091 package body API is
33092    function Factorial (Val : Integer) return Integer is
33093       Fact : Integer := 1;
33094    begin
33095       Count := Count + 1;
33096       for K in 1 .. Val loop
33097          Fact := Fact * K;
33098       end loop;
33099       return Fact;
33100    end Factorial;
33101
33102    @dots{}
33103    --  The remainder of this package body is unchanged.
33104 end API;
33105 @end cartouche
33106 @end group
33107 @end smallexample
33108
33109 @noindent
33110 Note that if you do not export the Ada entities with a @code{C} or
33111 @code{Stdcall} convention you will have to provide the mangled Ada names
33112 in the definition file of the Ada DLL
33113 (@pxref{Creating the Definition File}).
33114
33115 @node Ada DLLs and Elaboration
33116 @subsection Ada DLLs and Elaboration
33117 @cindex DLLs and elaboration
33118
33119 @noindent
33120 The DLL that you are building contains your Ada code as well as all the
33121 routines in the Ada library that are needed by it. The first thing a
33122 user of your DLL must do is elaborate the Ada code
33123 (@pxref{Elaboration Order Handling in GNAT}).
33124
33125 To achieve this you must export an initialization routine
33126 (@code{Initialize_API} in the previous example), which must be invoked
33127 before using any of the DLL services. This elaboration routine must call
33128 the Ada elaboration routine @code{adainit} generated by the GNAT binder
33129 (@pxref{Binding with Non-Ada Main Programs}). See the body of
33130 @code{Initialize_Api} for an example. Note that the GNAT binder is
33131 automatically invoked during the DLL build process by the @code{gnatdll}
33132 tool (@pxref{Using gnatdll}).
33133
33134 When a DLL is loaded, Windows systematically invokes a routine called
33135 @code{DllMain}. It would therefore be possible to call @code{adainit}
33136 directly from @code{DllMain} without having to provide an explicit
33137 initialization routine. Unfortunately, it is not possible to call
33138 @code{adainit} from the @code{DllMain} if your program has library level
33139 tasks because access to the @code{DllMain} entry point is serialized by
33140 the system (that is, only a single thread can execute ``through'' it at a
33141 time), which means that the GNAT run time will deadlock waiting for the
33142 newly created task to complete its initialization.
33143
33144 @node Ada DLLs and Finalization
33145 @subsection Ada DLLs and Finalization
33146 @cindex DLLs and finalization
33147
33148 @noindent
33149 When the services of an Ada DLL are no longer needed, the client code should
33150 invoke the DLL finalization routine, if available. The DLL finalization
33151 routine is in charge of releasing all resources acquired by the DLL. In the
33152 case of the Ada code contained in the DLL, this is achieved by calling
33153 routine @code{adafinal} generated by the GNAT binder
33154 (@pxref{Binding with Non-Ada Main Programs}).
33155 See the body of @code{Finalize_Api} for an
33156 example. As already pointed out the GNAT binder is automatically invoked
33157 during the DLL build process by the @code{gnatdll} tool
33158 (@pxref{Using gnatdll}).
33159
33160 @node Creating a Spec for Ada DLLs
33161 @subsection Creating a Spec for Ada DLLs
33162
33163 @noindent
33164 To use the services exported by the Ada DLL from another programming
33165 language (e.g.@: C), you have to translate the specs of the exported Ada
33166 entities in that language. For instance in the case of @code{API.dll},
33167 the corresponding C header file could look like:
33168
33169 @smallexample
33170 @group
33171 @cartouche
33172 extern int *_imp__count;
33173 #define count (*_imp__count)
33174 int factorial (int);
33175 @end cartouche
33176 @end group
33177 @end smallexample
33178
33179 @noindent
33180 It is important to understand that when building an Ada DLL to be used by
33181 other Ada applications, you need two different specs for the packages
33182 contained in the DLL: one for building the DLL and the other for using
33183 the DLL. This is because the @code{DLL} calling convention is needed to
33184 use a variable defined in a DLL, but when building the DLL, the variable
33185 must have either the @code{Ada} or @code{C} calling convention. As an
33186 example consider a DLL comprising the following package @code{API}:
33187
33188 @smallexample @c ada
33189 @group
33190 @cartouche
33191 package API is
33192    Count : Integer := 0;
33193    @dots{}
33194    --  Remainder of the package omitted.
33195 end API;
33196 @end cartouche
33197 @end group
33198 @end smallexample
33199
33200 @noindent
33201 After producing a DLL containing package @code{API}, the spec that
33202 must be used to import @code{API.Count} from Ada code outside of the
33203 DLL is:
33204
33205 @smallexample @c ada
33206 @group
33207 @cartouche
33208 package API is
33209    Count : Integer;
33210    pragma Import (DLL, Count);
33211 end API;
33212 @end cartouche
33213 @end group
33214 @end smallexample
33215
33216 @node Creating the Definition File
33217 @subsection Creating the Definition File
33218
33219 @noindent
33220 The definition file is the last file needed to build the DLL. It lists
33221 the exported symbols. As an example, the definition file for a DLL
33222 containing only package @code{API} (where all the entities are exported
33223 with a @code{C} calling convention) is:
33224
33225 @smallexample
33226 @group
33227 @cartouche
33228 EXPORTS
33229     count
33230     factorial
33231     finalize_api
33232     initialize_api
33233 @end cartouche
33234 @end group
33235 @end smallexample
33236
33237 @noindent
33238 If the @code{C} calling convention is missing from package @code{API},
33239 then the definition file contains the mangled Ada names of the above
33240 entities, which in this case are:
33241
33242 @smallexample
33243 @group
33244 @cartouche
33245 EXPORTS
33246     api__count
33247     api__factorial
33248     api__finalize_api
33249     api__initialize_api
33250 @end cartouche
33251 @end group
33252 @end smallexample
33253
33254 @node Using gnatdll
33255 @subsection Using @code{gnatdll}
33256 @findex gnatdll
33257
33258 @menu
33259 * gnatdll Example::
33260 * gnatdll behind the Scenes::
33261 * Using dlltool::
33262 @end menu
33263
33264 @noindent
33265 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33266 and non-Ada sources that make up your DLL have been compiled.
33267 @code{gnatdll} is actually in charge of two distinct tasks: build the
33268 static import library for the DLL and the actual DLL. The form of the
33269 @code{gnatdll} command is
33270
33271 @smallexample
33272 @cartouche
33273 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33274 @end cartouche
33275 @end smallexample
33276
33277 @noindent
33278 where @var{list-of-files} is a list of ALI and object files. The object
33279 file list must be the exact list of objects corresponding to the non-Ada
33280 sources whose services are to be included in the DLL. The ALI file list
33281 must be the exact list of ALI files for the corresponding Ada sources
33282 whose services are to be included in the DLL. If @var{list-of-files} is
33283 missing, only the static import library is generated.
33284
33285 @noindent
33286 You may specify any of the following switches to @code{gnatdll}:
33287
33288 @table @code
33289 @item -a@ovar{address}
33290 @cindex @option{-a} (@code{gnatdll})
33291 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33292 specified the default address @var{0x11000000} will be used. By default,
33293 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33294 advise the reader to build relocatable DLL.
33295
33296 @item -b @var{address}
33297 @cindex @option{-b} (@code{gnatdll})
33298 Set the relocatable DLL base address. By default the address is
33299 @code{0x11000000}.
33300
33301 @item -bargs @var{opts}
33302 @cindex @option{-bargs} (@code{gnatdll})
33303 Binder options. Pass @var{opts} to the binder.
33304
33305 @item -d @var{dllfile}
33306 @cindex @option{-d} (@code{gnatdll})
33307 @var{dllfile} is the name of the DLL. This switch must be present for
33308 @code{gnatdll} to do anything. The name of the generated import library is
33309 obtained algorithmically from @var{dllfile} as shown in the following
33310 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33311 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33312 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33313 as shown in the following example:
33314 if @var{dllfile} is @code{xyz.dll}, the definition
33315 file used is @code{xyz.def}.
33316
33317 @item -e @var{deffile}
33318 @cindex @option{-e} (@code{gnatdll})
33319 @var{deffile} is the name of the definition file.
33320
33321 @item -g
33322 @cindex @option{-g} (@code{gnatdll})
33323 Generate debugging information. This information is stored in the object
33324 file and copied from there to the final DLL file by the linker,
33325 where it can be read by the debugger. You must use the
33326 @option{-g} switch if you plan on using the debugger or the symbolic
33327 stack traceback.
33328
33329 @item -h
33330 @cindex @option{-h} (@code{gnatdll})
33331 Help mode. Displays @code{gnatdll} switch usage information.
33332
33333 @item -Idir
33334 @cindex @option{-I} (@code{gnatdll})
33335 Direct @code{gnatdll} to search the @var{dir} directory for source and
33336 object files needed to build the DLL.
33337 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33338
33339 @item -k
33340 @cindex @option{-k} (@code{gnatdll})
33341 Removes the @code{@@}@var{nn} suffix from the import library's exported
33342 names, but keeps them for the link names. You must specify this
33343 option if you want to use a @code{Stdcall} function in a DLL for which
33344 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33345 of the Windows NT DLL for example. This option has no effect when
33346 @option{-n} option is specified.
33347
33348 @item -l @var{file}
33349 @cindex @option{-l} (@code{gnatdll})
33350 The list of ALI and object files used to build the DLL are listed in
33351 @var{file}, instead of being given in the command line. Each line in
33352 @var{file} contains the name of an ALI or object file.
33353
33354 @item -n
33355 @cindex @option{-n} (@code{gnatdll})
33356 No Import. Do not create the import library.
33357
33358 @item -q
33359 @cindex @option{-q} (@code{gnatdll})
33360 Quiet mode. Do not display unnecessary messages.
33361
33362 @item -v
33363 @cindex @option{-v} (@code{gnatdll})
33364 Verbose mode. Display extra information.
33365
33366 @item -largs @var{opts}
33367 @cindex @option{-largs} (@code{gnatdll})
33368 Linker options. Pass @var{opts} to the linker.
33369 @end table
33370
33371 @node gnatdll Example
33372 @subsubsection @code{gnatdll} Example
33373
33374 @noindent
33375 As an example the command to build a relocatable DLL from @file{api.adb}
33376 once @file{api.adb} has been compiled and @file{api.def} created is
33377
33378 @smallexample
33379 $ gnatdll -d api.dll api.ali
33380 @end smallexample
33381
33382 @noindent
33383 The above command creates two files: @file{libapi.dll.a} (the import
33384 library) and @file{api.dll} (the actual DLL). If you want to create
33385 only the DLL, just type:
33386
33387 @smallexample
33388 $ gnatdll -d api.dll -n api.ali
33389 @end smallexample
33390
33391 @noindent
33392 Alternatively if you want to create just the import library, type:
33393
33394 @smallexample
33395 $ gnatdll -d api.dll
33396 @end smallexample
33397
33398 @node gnatdll behind the Scenes
33399 @subsubsection @code{gnatdll} behind the Scenes
33400
33401 @noindent
33402 This section details the steps involved in creating a DLL. @code{gnatdll}
33403 does these steps for you. Unless you are interested in understanding what
33404 goes on behind the scenes, you should skip this section.
33405
33406 We use the previous example of a DLL containing the Ada package @code{API},
33407 to illustrate the steps necessary to build a DLL. The starting point is a
33408 set of objects that will make up the DLL and the corresponding ALI
33409 files. In the case of this example this means that @file{api.o} and
33410 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33411 the following:
33412
33413 @enumerate
33414 @item
33415 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33416 the information necessary to generate relocation information for the
33417 DLL.
33418
33419 @smallexample
33420 @group
33421 $ gnatbind -n api
33422 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33423 @end group
33424 @end smallexample
33425
33426 @noindent
33427 In addition to the base file, the @command{gnatlink} command generates an
33428 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33429 asks @command{gnatlink} to generate the routines @code{DllMain} and
33430 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33431 is loaded into memory.
33432
33433 @item
33434 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33435 export table (@file{api.exp}). The export table contains the relocation
33436 information in a form which can be used during the final link to ensure
33437 that the Windows loader is able to place the DLL anywhere in memory.
33438
33439 @smallexample
33440 @group
33441 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33442           --output-exp api.exp
33443 @end group
33444 @end smallexample
33445
33446 @item
33447 @code{gnatdll} builds the base file using the new export table. Note that
33448 @command{gnatbind} must be called once again since the binder generated file
33449 has been deleted during the previous call to @command{gnatlink}.
33450
33451 @smallexample
33452 @group
33453 $ gnatbind -n api
33454 $ gnatlink api -o api.jnk api.exp -mdll
33455       -Wl,--base-file,api.base
33456 @end group
33457 @end smallexample
33458
33459 @item
33460 @code{gnatdll} builds the new export table using the new base file and
33461 generates the DLL import library @file{libAPI.dll.a}.
33462
33463 @smallexample
33464 @group
33465 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33466           --output-exp api.exp --output-lib libAPI.a
33467 @end group
33468 @end smallexample
33469
33470 @item
33471 Finally @code{gnatdll} builds the relocatable DLL using the final export
33472 table.
33473
33474 @smallexample
33475 @group
33476 $ gnatbind -n api
33477 $ gnatlink api api.exp -o api.dll -mdll
33478 @end group
33479 @end smallexample
33480 @end enumerate
33481
33482 @node Using dlltool
33483 @subsubsection Using @code{dlltool}
33484
33485 @noindent
33486 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33487 DLLs and static import libraries. This section summarizes the most
33488 common @code{dlltool} switches. The form of the @code{dlltool} command
33489 is
33490
33491 @smallexample
33492 $ dlltool @ovar{switches}
33493 @end smallexample
33494
33495 @noindent
33496 @code{dlltool} switches include:
33497
33498 @table @option
33499 @item --base-file @var{basefile}
33500 @cindex @option{--base-file} (@command{dlltool})
33501 Read the base file @var{basefile} generated by the linker. This switch
33502 is used to create a relocatable DLL.
33503
33504 @item --def @var{deffile}
33505 @cindex @option{--def} (@command{dlltool})
33506 Read the definition file.
33507
33508 @item --dllname @var{name}
33509 @cindex @option{--dllname} (@command{dlltool})
33510 Gives the name of the DLL. This switch is used to embed the name of the
33511 DLL in the static import library generated by @code{dlltool} with switch
33512 @option{--output-lib}.
33513
33514 @item -k
33515 @cindex @option{-k} (@command{dlltool})
33516 Kill @code{@@}@var{nn} from exported names
33517 (@pxref{Windows Calling Conventions}
33518 for a discussion about @code{Stdcall}-style symbols.
33519
33520 @item --help
33521 @cindex @option{--help} (@command{dlltool})
33522 Prints the @code{dlltool} switches with a concise description.
33523
33524 @item --output-exp @var{exportfile}
33525 @cindex @option{--output-exp} (@command{dlltool})
33526 Generate an export file @var{exportfile}. The export file contains the
33527 export table (list of symbols in the DLL) and is used to create the DLL.
33528
33529 @item --output-lib @var{libfile}
33530 @cindex @option{--output-lib} (@command{dlltool})
33531 Generate a static import library @var{libfile}.
33532
33533 @item -v
33534 @cindex @option{-v} (@command{dlltool})
33535 Verbose mode.
33536
33537 @item --as @var{assembler-name}
33538 @cindex @option{--as} (@command{dlltool})
33539 Use @var{assembler-name} as the assembler. The default is @code{as}.
33540 @end table
33541
33542 @node GNAT and Windows Resources
33543 @section GNAT and Windows Resources
33544 @cindex Resources, windows
33545
33546 @menu
33547 * Building Resources::
33548 * Compiling Resources::
33549 * Using Resources::
33550 @end menu
33551
33552 @noindent
33553 Resources are an easy way to add Windows specific objects to your
33554 application. The objects that can be added as resources include:
33555
33556 @itemize @bullet
33557 @item
33558 menus
33559
33560 @item
33561 accelerators
33562
33563 @item
33564 dialog boxes
33565
33566 @item
33567 string tables
33568
33569 @item
33570 bitmaps
33571
33572 @item
33573 cursors
33574
33575 @item
33576 icons
33577
33578 @item
33579 fonts
33580 @end itemize
33581
33582 @noindent
33583 This section explains how to build, compile and use resources.
33584
33585 @node Building Resources
33586 @subsection Building Resources
33587 @cindex Resources, building
33588
33589 @noindent
33590 A resource file is an ASCII file. By convention resource files have an
33591 @file{.rc} extension.
33592 The easiest way to build a resource file is to use Microsoft tools
33593 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33594 @code{dlgedit.exe} to build dialogs.
33595 It is always possible to build an @file{.rc} file yourself by writing a
33596 resource script.
33597
33598 It is not our objective to explain how to write a resource file. A
33599 complete description of the resource script language can be found in the
33600 Microsoft documentation.
33601
33602 @node Compiling Resources
33603 @subsection Compiling Resources
33604 @findex rc
33605 @findex windres
33606 @cindex Resources, compiling
33607
33608 @noindent
33609 This section describes how to build a GNAT-compatible (COFF) object file
33610 containing the resources. This is done using the Resource Compiler
33611 @code{windres} as follows:
33612
33613 @smallexample
33614 $ windres -i myres.rc -o myres.o
33615 @end smallexample
33616
33617 @noindent
33618 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33619 file. You can specify an alternate preprocessor (usually named
33620 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33621 parameter. A list of all possible options may be obtained by entering
33622 the command @code{windres} @option{--help}.
33623
33624 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33625 to produce a @file{.res} file (binary resource file). See the
33626 corresponding Microsoft documentation for further details. In this case
33627 you need to use @code{windres} to translate the @file{.res} file to a
33628 GNAT-compatible object file as follows:
33629
33630 @smallexample
33631 $ windres -i myres.res -o myres.o
33632 @end smallexample
33633
33634 @node Using Resources
33635 @subsection Using Resources
33636 @cindex Resources, using
33637
33638 @noindent
33639 To include the resource file in your program just add the
33640 GNAT-compatible object file for the resource(s) to the linker
33641 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33642 option:
33643
33644 @smallexample
33645 $ gnatmake myprog -largs myres.o
33646 @end smallexample
33647
33648 @node Debugging a DLL
33649 @section Debugging a DLL
33650 @cindex DLL debugging
33651
33652 @menu
33653 * Program and DLL Both Built with GCC/GNAT::
33654 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33655 @end menu
33656
33657 @noindent
33658 Debugging a DLL is similar to debugging a standard program. But
33659 we have to deal with two different executable parts: the DLL and the
33660 program that uses it. We have the following four possibilities:
33661
33662 @enumerate 1
33663 @item
33664 The program and the DLL are built with @code{GCC/GNAT}.
33665 @item
33666 The program is built with foreign tools and the DLL is built with
33667 @code{GCC/GNAT}.
33668 @item
33669 The program is built with @code{GCC/GNAT} and the DLL is built with
33670 foreign tools.
33671 @item
33672 @end enumerate
33673
33674 @noindent
33675 In this section we address only cases one and two above.
33676 There is no point in trying to debug
33677 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33678 information in it. To do so you must use a debugger compatible with the
33679 tools suite used to build the DLL.
33680
33681 @node Program and DLL Both Built with GCC/GNAT
33682 @subsection Program and DLL Both Built with GCC/GNAT
33683
33684 @noindent
33685 This is the simplest case. Both the DLL and the program have @code{GDB}
33686 compatible debugging information. It is then possible to break anywhere in
33687 the process. Let's suppose here that the main procedure is named
33688 @code{ada_main} and that in the DLL there is an entry point named
33689 @code{ada_dll}.
33690
33691 @noindent
33692 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33693 program must have been built with the debugging information (see GNAT -g
33694 switch). Here are the step-by-step instructions for debugging it:
33695
33696 @enumerate 1
33697 @item Launch @code{GDB} on the main program.
33698
33699 @smallexample
33700 $ gdb -nw ada_main
33701 @end smallexample
33702
33703 @item Start the program and stop at the beginning of the main procedure
33704
33705 @smallexample
33706 (gdb) start
33707 @end smallexample
33708
33709 @noindent
33710 This step is required to be able to set a breakpoint inside the DLL. As long
33711 as the program is not run, the DLL is not loaded. This has the
33712 consequence that the DLL debugging information is also not loaded, so it is not
33713 possible to set a breakpoint in the DLL.
33714
33715 @item Set a breakpoint inside the DLL
33716
33717 @smallexample
33718 (gdb) break ada_dll
33719 (gdb) cont
33720 @end smallexample
33721
33722 @end enumerate
33723
33724 @noindent
33725 At this stage a breakpoint is set inside the DLL. From there on
33726 you can use the standard approach to debug the whole program
33727 (@pxref{Running and Debugging Ada Programs}).
33728
33729 @ignore
33730 @c This used to work, probably because the DLLs were non-relocatable
33731 @c keep this section around until the problem is sorted out.
33732
33733 To break on the @code{DllMain} routine it is not possible to follow
33734 the procedure above. At the time the program stop on @code{ada_main}
33735 the @code{DllMain} routine as already been called. Either you can use
33736 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33737
33738 @enumerate 1
33739 @item Launch @code{GDB} on the main program.
33740
33741 @smallexample
33742 $ gdb ada_main
33743 @end smallexample
33744
33745 @item Load DLL symbols
33746
33747 @smallexample
33748 (gdb) add-sym api.dll
33749 @end smallexample
33750
33751 @item Set a breakpoint inside the DLL
33752
33753 @smallexample
33754 (gdb) break ada_dll.adb:45
33755 @end smallexample
33756
33757 Note that at this point it is not possible to break using the routine symbol
33758 directly as the program is not yet running. The solution is to break
33759 on the proper line (break in @file{ada_dll.adb} line 45).
33760
33761 @item Start the program
33762
33763 @smallexample
33764 (gdb) run
33765 @end smallexample
33766
33767 @end enumerate
33768 @end ignore
33769
33770 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33771 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33772
33773 @menu
33774 * Debugging the DLL Directly::
33775 * Attaching to a Running Process::
33776 @end menu
33777
33778 @noindent
33779 In this case things are slightly more complex because it is not possible to
33780 start the main program and then break at the beginning to load the DLL and the
33781 associated DLL debugging information. It is not possible to break at the
33782 beginning of the program because there is no @code{GDB} debugging information,
33783 and therefore there is no direct way of getting initial control. This
33784 section addresses this issue by describing some methods that can be used
33785 to break somewhere in the DLL to debug it.
33786
33787 @noindent
33788 First suppose that the main procedure is named @code{main} (this is for
33789 example some C code built with Microsoft Visual C) and that there is a
33790 DLL named @code{test.dll} containing an Ada entry point named
33791 @code{ada_dll}.
33792
33793 @noindent
33794 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33795 been built with debugging information (see GNAT -g option).
33796
33797 @node Debugging the DLL Directly
33798 @subsubsection Debugging the DLL Directly
33799
33800 @enumerate 1
33801 @item
33802 Find out the executable starting address
33803
33804 @smallexample
33805 $ objdump --file-header main.exe
33806 @end smallexample
33807
33808 The starting address is reported on the last line. For example:
33809
33810 @smallexample
33811 main.exe:     file format pei-i386
33812 architecture: i386, flags 0x0000010a:
33813 EXEC_P, HAS_DEBUG, D_PAGED
33814 start address 0x00401010
33815 @end smallexample
33816
33817 @item
33818 Launch the debugger on the executable.
33819
33820 @smallexample
33821 $ gdb main.exe
33822 @end smallexample
33823
33824 @item
33825 Set a breakpoint at the starting address, and launch the program.
33826
33827 @smallexample
33828 $ (gdb) break *0x00401010
33829 $ (gdb) run
33830 @end smallexample
33831
33832 The program will stop at the given address.
33833
33834 @item
33835 Set a breakpoint on a DLL subroutine.
33836
33837 @smallexample
33838 (gdb) break ada_dll.adb:45
33839 @end smallexample
33840
33841 Or if you want to break using a symbol on the DLL, you need first to
33842 select the Ada language (language used by the DLL).
33843
33844 @smallexample
33845 (gdb) set language ada
33846 (gdb) break ada_dll
33847 @end smallexample
33848
33849 @item
33850 Continue the program.
33851
33852 @smallexample
33853 (gdb) cont
33854 @end smallexample
33855
33856 @noindent
33857 This will run the program until it reaches the breakpoint that has been
33858 set. From that point you can use the standard way to debug a program
33859 as described in (@pxref{Running and Debugging Ada Programs}).
33860
33861 @end enumerate
33862
33863 @noindent
33864 It is also possible to debug the DLL by attaching to a running process.
33865
33866 @node Attaching to a Running Process
33867 @subsubsection Attaching to a Running Process
33868 @cindex DLL debugging, attach to process
33869
33870 @noindent
33871 With @code{GDB} it is always possible to debug a running process by
33872 attaching to it. It is possible to debug a DLL this way. The limitation
33873 of this approach is that the DLL must run long enough to perform the
33874 attach operation. It may be useful for instance to insert a time wasting
33875 loop in the code of the DLL to meet this criterion.
33876
33877 @enumerate 1
33878
33879 @item Launch the main program @file{main.exe}.
33880
33881 @smallexample
33882 $ main
33883 @end smallexample
33884
33885 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33886 that the process PID for @file{main.exe} is 208.
33887
33888 @item Launch gdb.
33889
33890 @smallexample
33891 $ gdb
33892 @end smallexample
33893
33894 @item Attach to the running process to be debugged.
33895
33896 @smallexample
33897 (gdb) attach 208
33898 @end smallexample
33899
33900 @item Load the process debugging information.
33901
33902 @smallexample
33903 (gdb) symbol-file main.exe
33904 @end smallexample
33905
33906 @item Break somewhere in the DLL.
33907
33908 @smallexample
33909 (gdb) break ada_dll
33910 @end smallexample
33911
33912 @item Continue process execution.
33913
33914 @smallexample
33915 (gdb) cont
33916 @end smallexample
33917
33918 @end enumerate
33919
33920 @noindent
33921 This last step will resume the process execution, and stop at
33922 the breakpoint we have set. From there you can use the standard
33923 approach to debug a program as described in
33924 (@pxref{Running and Debugging Ada Programs}).
33925
33926 @node Setting Stack Size from gnatlink
33927 @section Setting Stack Size from @command{gnatlink}
33928
33929 @noindent
33930 It is possible to specify the program stack size at link time. On modern
33931 versions of Windows, starting with XP, this is mostly useful to set the size of
33932 the main stack (environment task). The other task stacks are set with pragma
33933 Storage_Size or with the @command{gnatbind -d} command.
33934
33935 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33936 reserve size of individual tasks, the link-time stack size applies to all
33937 tasks, and pragma Storage_Size has no effect.
33938 In particular, Stack Overflow checks are made against this
33939 link-time specified size.
33940
33941 This setting can be done with
33942 @command{gnatlink} using either:
33943
33944 @itemize @bullet
33945
33946 @item using @option{-Xlinker} linker option
33947
33948 @smallexample
33949 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33950 @end smallexample
33951
33952 This sets the stack reserve size to 0x10000 bytes and the stack commit
33953 size to 0x1000 bytes.
33954
33955 @item using @option{-Wl} linker option
33956
33957 @smallexample
33958 $ gnatlink hello -Wl,--stack=0x1000000
33959 @end smallexample
33960
33961 This sets the stack reserve size to 0x1000000 bytes. Note that with
33962 @option{-Wl} option it is not possible to set the stack commit size
33963 because the coma is a separator for this option.
33964
33965 @end itemize
33966
33967 @node Setting Heap Size from gnatlink
33968 @section Setting Heap Size from @command{gnatlink}
33969
33970 @noindent
33971 Under Windows systems, it is possible to specify the program heap size from
33972 @command{gnatlink} using either:
33973
33974 @itemize @bullet
33975
33976 @item using @option{-Xlinker} linker option
33977
33978 @smallexample
33979 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33980 @end smallexample
33981
33982 This sets the heap reserve size to 0x10000 bytes and the heap commit
33983 size to 0x1000 bytes.
33984
33985 @item using @option{-Wl} linker option
33986
33987 @smallexample
33988 $ gnatlink hello -Wl,--heap=0x1000000
33989 @end smallexample
33990
33991 This sets the heap reserve size to 0x1000000 bytes. Note that with
33992 @option{-Wl} option it is not possible to set the heap commit size
33993 because the coma is a separator for this option.
33994
33995 @end itemize
33996
33997 @end ifset
33998
33999 @c **********************************
34000 @c * GNU Free Documentation License *
34001 @c **********************************
34002 @include fdl.texi
34003 @c GNU Free Documentation License
34004
34005 @node Index,,GNU Free Documentation License, Top
34006 @unnumbered Index
34007
34008 @printindex cp
34009
34010 @contents
34011 @c Put table of contents at end, otherwise it precedes the "title page" in
34012 @c the .txt version
34013 @c Edit the pdf file to move the contents to the beginning, after the title
34014 @c page
34015
34016 @bye