OSDN Git Service

2010-06-17 Joel Brobecker <brobecker@adacore.com brobecker>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * The Cross-Referencing Tools gnatxref and gnatfind::
180 * The GNAT Pretty-Printer gnatpp::
181 * The GNAT Metric Tool gnatmetric::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
184 @ifset vms
185 * The GNAT Run-Time Library Builder gnatlbr::
186 @end ifset
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Stack Related Facilities::
195 * Verifying Properties Using gnatcheck::
196 * Creating Sample Bodies Using gnatstub::
197 * Generating Ada Bindings for C and C++ headers::
198 * Other Utility Programs::
199 * Running and Debugging Ada Programs::
200 @ifclear vms
201 * Code Coverage and Profiling::
202 @end ifclear
203 @ifset vms
204 * Compatibility with HP Ada::
205 @end ifset
206 * Platform-Specific Information for the Run-Time Libraries::
207 * Example of Binder Output File::
208 * Elaboration Order Handling in GNAT::
209 * Conditional Compilation::
210 * Inline Assembler::
211 * Compatibility and Porting Guide::
212 @ifset unw
213 * Microsoft Windows Topics::
214 @end ifset
215 * GNU Free Documentation License::
216 * Index::
217
218  --- The Detailed Node Listing ---
219
220 About This Guide
221
222 * What This Guide Contains::
223 * What You Should Know before Reading This Guide::
224 * Related Information::
225 * Conventions::
226
227 Getting Started with GNAT
228
229 * Running GNAT::
230 * Running a Simple Ada Program::
231 * Running a Program with Multiple Units::
232 * Using the gnatmake Utility::
233 @ifset vms
234 * Editing with Emacs::
235 @end ifset
236 @ifclear vms
237 * Introduction to GPS::
238 @end ifclear
239
240 The GNAT Compilation Model
241
242 * Source Representation::
243 * Foreign Language Representation::
244 * File Naming Rules::
245 * Using Other File Names::
246 * Alternative File Naming Schemes::
247 * Generating Object Files::
248 * Source Dependencies::
249 * The Ada Library Information Files::
250 * Binding an Ada Program::
251 * Mixed Language Programming::
252 @ifclear vms
253 * Building Mixed Ada & C++ Programs::
254 * Comparison between GNAT and C/C++ Compilation Models::
255 @end ifclear
256 * Comparison between GNAT and Conventional Ada Library Models::
257 @ifset vms
258 * Placement of temporary files::
259 @end ifset
260
261 Foreign Language Representation
262
263 * Latin-1::
264 * Other 8-Bit Codes::
265 * Wide Character Encodings::
266
267 Compiling Ada Programs With gcc
268
269 * Compiling Programs::
270 * Switches for gcc::
271 * Search Paths and the Run-Time Library (RTL)::
272 * Order of Compilation Issues::
273 * Examples::
274
275 Switches for gcc
276
277 * Output and Error Message Control::
278 * Warning Message Control::
279 * Debugging and Assertion Control::
280 * Validity Checking::
281 * Style Checking::
282 * Run-Time Checks::
283 * Using gcc for Syntax Checking::
284 * Using gcc for Semantic Checking::
285 * Compiling Different Versions of Ada::
286 * Character Set Control::
287 * File Naming Control::
288 * Subprogram Inlining Control::
289 * Auxiliary Output Control::
290 * Debugging Control::
291 * Exception Handling Control::
292 * Units to Sources Mapping Files::
293 * Integrated Preprocessing::
294 @ifset vms
295 * Return Codes::
296 @end ifset
297
298 Binding Ada Programs With gnatbind
299
300 * Running gnatbind::
301 * Switches for gnatbind::
302 * Command-Line Access::
303 * Search Paths for gnatbind::
304 * Examples of gnatbind Usage::
305
306 Switches for gnatbind
307
308 * Consistency-Checking Modes::
309 * Binder Error Message Control::
310 * Elaboration Control::
311 * Output Control::
312 * Binding with Non-Ada Main Programs::
313 * Binding Programs with No Main Subprogram::
314
315 Linking Using gnatlink
316
317 * Running gnatlink::
318 * Switches for gnatlink::
319
320 The GNAT Make Program gnatmake
321
322 * Running gnatmake::
323 * Switches for gnatmake::
324 * Mode Switches for gnatmake::
325 * Notes on the Command Line::
326 * How gnatmake Works::
327 * Examples of gnatmake Usage::
328
329 Improving Performance
330 * Performance Considerations::
331 * Text_IO Suggestions::
332 * Reducing Size of Ada Executables with gnatelim::
333 * Reducing Size of Executables with unused subprogram/data elimination::
334
335 Performance Considerations
336 * Controlling Run-Time Checks::
337 * Use of Restrictions::
338 * Optimization Levels::
339 * Debugging Optimized Code::
340 * Inlining of Subprograms::
341 * Other Optimization Switches::
342 * Optimization and Strict Aliasing::
343 @ifset vms
344 * Coverage Analysis::
345 @end ifset
346
347 Reducing Size of Ada Executables with gnatelim
348 * About gnatelim::
349 * Running gnatelim::
350 * Processing Precompiled Libraries::
351 * Correcting the List of Eliminate Pragmas::
352 * Making Your Executables Smaller::
353 * Summary of the gnatelim Usage Cycle::
354
355 Reducing Size of Executables with unused subprogram/data elimination
356 * About unused subprogram/data elimination::
357 * Compilation options::
358
359 Renaming Files Using gnatchop
360
361 * Handling Files with Multiple Units::
362 * Operating gnatchop in Compilation Mode::
363 * Command Line for gnatchop::
364 * Switches for gnatchop::
365 * Examples of gnatchop Usage::
366
367 Configuration Pragmas
368
369 * Handling of Configuration Pragmas::
370 * The Configuration Pragmas Files::
371
372 Handling Arbitrary File Naming Conventions Using gnatname
373
374 * Arbitrary File Naming Conventions::
375 * Running gnatname::
376 * Switches for gnatname::
377 * Examples of gnatname Usage::
378
379 GNAT Project Manager
380
381 * Introduction::
382 * Examples of Project Files::
383 * Project File Syntax::
384 * Objects and Sources in Project Files::
385 * Importing Projects::
386 * Project Extension::
387 * Project Hierarchy Extension::
388 * External References in Project Files::
389 * Packages in Project Files::
390 * Variables from Imported Projects::
391 * Naming Schemes::
392 * Library Projects::
393 * Stand-alone Library Projects::
394 * Switches Related to Project Files::
395 * Tools Supporting Project Files::
396 * An Extended Example::
397 * Project File Complete Syntax::
398
399 The Cross-Referencing Tools gnatxref and gnatfind
400
401 * Switches for gnatxref::
402 * Switches for gnatfind::
403 * Project Files for gnatxref and gnatfind::
404 * Regular Expressions in gnatfind and gnatxref::
405 * Examples of gnatxref Usage::
406 * Examples of gnatfind Usage::
407
408 The GNAT Pretty-Printer gnatpp
409
410 * Switches for gnatpp::
411 * Formatting Rules::
412
413 The GNAT Metrics Tool gnatmetric
414
415 * Switches for gnatmetric::
416
417 File Name Krunching Using gnatkr
418
419 * About gnatkr::
420 * Using gnatkr::
421 * Krunching Method::
422 * Examples of gnatkr Usage::
423
424 Preprocessing Using gnatprep
425 * Preprocessing Symbols::
426 * Using gnatprep::
427 * Switches for gnatprep::
428 * Form of Definitions File::
429 * Form of Input Text for gnatprep::
430
431 @ifset vms
432 The GNAT Run-Time Library Builder gnatlbr
433
434 * Running gnatlbr::
435 * Switches for gnatlbr::
436 * Examples of gnatlbr Usage::
437 @end ifset
438
439 The GNAT Library Browser gnatls
440
441 * Running gnatls::
442 * Switches for gnatls::
443 * Examples of gnatls Usage::
444
445 Cleaning Up Using gnatclean
446
447 * Running gnatclean::
448 * Switches for gnatclean::
449 @c * Examples of gnatclean Usage::
450
451 @ifclear vms
452
453 GNAT and Libraries
454
455 * Introduction to Libraries in GNAT::
456 * General Ada Libraries::
457 * Stand-alone Ada Libraries::
458 * Rebuilding the GNAT Run-Time Library::
459
460 Using the GNU make Utility
461
462 * Using gnatmake in a Makefile::
463 * Automatically Creating a List of Directories::
464 * Generating the Command Line Switches::
465 * Overcoming Command Line Length Limits::
466 @end ifclear
467
468 Memory Management Issues
469
470 * Some Useful Memory Pools::
471 * The GNAT Debug Pool Facility::
472 @ifclear vms
473 * The gnatmem Tool::
474 @end ifclear
475
476 Stack Related Facilities
477
478 * Stack Overflow Checking::
479 * Static Stack Usage Analysis::
480 * Dynamic Stack Usage Analysis::
481
482 Some Useful Memory Pools
483
484 The GNAT Debug Pool Facility
485
486 @ifclear vms
487 The gnatmem Tool
488
489 * Running gnatmem::
490 * Switches for gnatmem::
491 * Example of gnatmem Usage::
492 @end ifclear
493
494 Verifying Properties Using gnatcheck
495
496 * Format of the Report File::
497 * General gnatcheck Switches::
498 * gnatcheck Rule Options::
499 * Adding the Results of Compiler Checks to gnatcheck Output::
500 * Project-Wide Checks::
501 * Rule exemption::
502 * Predefined Rules::
503 * Example of gnatcheck Usage::
504
505 Sample Bodies Using gnatstub
506
507 * Running gnatstub::
508 * Switches for gnatstub::
509
510 Other Utility Programs
511
512 * Using Other Utility Programs with GNAT::
513 * The External Symbol Naming Scheme of GNAT::
514 * Converting Ada Files to html with gnathtml::
515
516 @ifclear vms
517 Code Coverage and Profiling
518
519 * Code Coverage of Ada Programs using gcov::
520 * Profiling an Ada Program using gprof::
521 @end ifclear
522
523 Running and Debugging Ada Programs
524
525 * The GNAT Debugger GDB::
526 * Running GDB::
527 * Introduction to GDB Commands::
528 * Using Ada Expressions::
529 * Calling User-Defined Subprograms::
530 * Using the Next Command in a Function::
531 * Ada Exceptions::
532 * Ada Tasks::
533 * Debugging Generic Units::
534 * Remote Debugging using gdbserver::
535 * GNAT Abnormal Termination or Failure to Terminate::
536 * Naming Conventions for GNAT Source Files::
537 * Getting Internal Debugging Information::
538 * Stack Traceback::
539
540 @ifset vms
541 * LSE::
542 @end ifset
543
544 @ifset vms
545 Compatibility with HP Ada
546
547 * Ada Language Compatibility::
548 * Differences in the Definition of Package System::
549 * Language-Related Features::
550 * The Package STANDARD::
551 * The Package SYSTEM::
552 * Tasking and Task-Related Features::
553 * Pragmas and Pragma-Related Features::
554 * Library of Predefined Units::
555 * Bindings::
556 * Main Program Definition::
557 * Implementation-Defined Attributes::
558 * Compiler and Run-Time Interfacing::
559 * Program Compilation and Library Management::
560 * Input-Output::
561 * Implementation Limits::
562 * Tools and Utilities::
563
564 Language-Related Features
565
566 * Integer Types and Representations::
567 * Floating-Point Types and Representations::
568 * Pragmas Float_Representation and Long_Float::
569 * Fixed-Point Types and Representations::
570 * Record and Array Component Alignment::
571 * Address Clauses::
572 * Other Representation Clauses::
573
574 Tasking and Task-Related Features
575
576 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
577 * Assigning Task IDs::
578 * Task IDs and Delays::
579 * Task-Related Pragmas::
580 * Scheduling and Task Priority::
581 * The Task Stack::
582 * External Interrupts::
583
584 Pragmas and Pragma-Related Features
585
586 * Restrictions on the Pragma INLINE::
587 * Restrictions on the Pragma INTERFACE::
588 * Restrictions on the Pragma SYSTEM_NAME::
589
590 Library of Predefined Units
591
592 * Changes to DECLIB::
593
594 Bindings
595
596 * Shared Libraries and Options Files::
597 * Interfaces to C::
598 @end ifset
599
600 Platform-Specific Information for the Run-Time Libraries
601
602 * Summary of Run-Time Configurations::
603 * Specifying a Run-Time Library::
604 * Choosing the Scheduling Policy::
605 * Solaris-Specific Considerations::
606 * Linux-Specific Considerations::
607 * AIX-Specific Considerations::
608 * Irix-Specific Considerations::
609 * RTX-Specific Considerations::
610 * HP-UX-Specific Considerations::
611
612 Example of Binder Output File
613
614 Elaboration Order Handling in GNAT
615
616 * Elaboration Code::
617 * Checking the Elaboration Order::
618 * Controlling the Elaboration Order::
619 * Controlling Elaboration in GNAT - Internal Calls::
620 * Controlling Elaboration in GNAT - External Calls::
621 * Default Behavior in GNAT - Ensuring Safety::
622 * Treatment of Pragma Elaborate::
623 * Elaboration Issues for Library Tasks::
624 * Mixing Elaboration Models::
625 * What to Do If the Default Elaboration Behavior Fails::
626 * Elaboration for Access-to-Subprogram Values::
627 * Summary of Procedures for Elaboration Control::
628 * Other Elaboration Order Considerations::
629
630 Conditional Compilation
631 * Use of Boolean Constants::
632 * Debugging - A Special Case::
633 * Conditionalizing Declarations::
634 * Use of Alternative Implementations::
635 * Preprocessing::
636
637 Inline Assembler
638
639 * Basic Assembler Syntax::
640 * A Simple Example of Inline Assembler::
641 * Output Variables in Inline Assembler::
642 * Input Variables in Inline Assembler::
643 * Inlining Inline Assembler Code::
644 * Other Asm Functionality::
645
646 Compatibility and Porting Guide
647
648 * Compatibility with Ada 83::
649 * Compatibility between Ada 95 and Ada 2005::
650 * Implementation-dependent characteristics::
651 @ifclear vms
652 @c This brief section is only in the non-VMS version
653 @c The complete chapter on HP Ada issues is in the VMS version
654 * Compatibility with HP Ada 83::
655 @end ifclear
656 * Compatibility with Other Ada Systems::
657 * Representation Clauses::
658 @ifset vms
659 * Transitioning to 64-Bit GNAT for OpenVMS::
660 @end ifset
661
662 @ifset unw
663 Microsoft Windows Topics
664
665 * Using GNAT on Windows::
666 * CONSOLE and WINDOWS subsystems::
667 * Temporary Files::
668 * Mixed-Language Programming on Windows::
669 * Windows Calling Conventions::
670 * Introduction to Dynamic Link Libraries (DLLs)::
671 * Using DLLs with GNAT::
672 * Building DLLs with GNAT::
673 * GNAT and Windows Resources::
674 * Debugging a DLL::
675 * Setting Stack Size from gnatlink::
676 * Setting Heap Size from gnatlink::
677 @end ifset
678
679 * Index::
680 @end menu
681 @end ifnottex
682
683 @node About This Guide
684 @unnumbered About This Guide
685
686 @noindent
687 @ifset vms
688 This guide describes the use of @value{EDITION},
689 a compiler and software development toolset for the full Ada
690 programming language, implemented on OpenVMS for HP's Alpha and
691 Integrity server (I64) platforms.
692 @end ifset
693 @ifclear vms
694 This guide describes the use of @value{EDITION},
695 a compiler and software development
696 toolset for the full Ada programming language.
697 @end ifclear
698 It documents the features of the compiler and tools, and explains
699 how to use them to build Ada applications.
700
701 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
702 Ada 83 compatibility mode.
703 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
704 but you can override with a compiler switch
705 (@pxref{Compiling Different Versions of Ada})
706 to explicitly specify the language version.
707 Throughout this manual, references to ``Ada'' without a year suffix
708 apply to both the Ada 95 and Ada 2005 versions of the language.
709
710
711 @ifclear FSFEDITION
712 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
713 ``GNAT'' in the remainder of this document.
714 @end ifclear
715
716
717
718
719 @menu
720 * What This Guide Contains::
721 * What You Should Know before Reading This Guide::
722 * Related Information::
723 * Conventions::
724 @end menu
725
726 @node What This Guide Contains
727 @unnumberedsec What This Guide Contains
728
729 @noindent
730 This guide contains the following chapters:
731 @itemize @bullet
732
733 @item
734 @ref{Getting Started with GNAT}, describes how to get started compiling
735 and running Ada programs with the GNAT Ada programming environment.
736 @item
737 @ref{The GNAT Compilation Model}, describes the compilation model used
738 by GNAT.
739
740 @item
741 @ref{Compiling Using gcc}, describes how to compile
742 Ada programs with @command{gcc}, the Ada compiler.
743
744 @item
745 @ref{Binding Using gnatbind}, describes how to
746 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
747 utility.
748
749 @item
750 @ref{Linking Using gnatlink},
751 describes @command{gnatlink}, a
752 program that provides for linking using the GNAT run-time library to
753 construct a program. @command{gnatlink} can also incorporate foreign language
754 object units into the executable.
755
756 @item
757 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
758 utility that automatically determines the set of sources
759 needed by an Ada compilation unit, and executes the necessary compilations
760 binding and link.
761
762 @item
763 @ref{Improving Performance}, shows various techniques for making your
764 Ada program run faster or take less space.
765 It discusses the effect of the compiler's optimization switch and
766 also describes the @command{gnatelim} tool and unused subprogram/data
767 elimination.
768
769 @item
770 @ref{Renaming Files Using gnatchop}, describes
771 @code{gnatchop}, a utility that allows you to preprocess a file that
772 contains Ada source code, and split it into one or more new files, one
773 for each compilation unit.
774
775 @item
776 @ref{Configuration Pragmas}, describes the configuration pragmas
777 handled by GNAT.
778
779 @item
780 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
781 shows how to override the default GNAT file naming conventions,
782 either for an individual unit or globally.
783
784 @item
785 @ref{GNAT Project Manager}, describes how to use project files
786 to organize large projects.
787
788 @item
789 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
790 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
791 way to navigate through sources.
792
793 @item
794 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
795 version of an Ada source file with control over casing, indentation,
796 comment placement, and other elements of program presentation style.
797
798 @item
799 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
800 metrics for an Ada source file, such as the number of types and subprograms,
801 and assorted complexity measures.
802
803 @item
804 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
805 file name krunching utility, used to handle shortened
806 file names on operating systems with a limit on the length of names.
807
808 @item
809 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
810 preprocessor utility that allows a single source file to be used to
811 generate multiple or parameterized source files by means of macro
812 substitution.
813
814 @ifset vms
815 @item
816 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
817 a tool for rebuilding the GNAT run time with user-supplied
818 configuration pragmas.
819 @end ifset
820
821 @item
822 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
823 utility that displays information about compiled units, including dependences
824 on the corresponding sources files, and consistency of compilations.
825
826 @item
827 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
828 to delete files that are produced by the compiler, binder and linker.
829
830 @ifclear vms
831 @item
832 @ref{GNAT and Libraries}, describes the process of creating and using
833 Libraries with GNAT. It also describes how to recompile the GNAT run-time
834 library.
835
836 @item
837 @ref{Using the GNU make Utility}, describes some techniques for using
838 the GNAT toolset in Makefiles.
839 @end ifclear
840
841 @item
842 @ref{Memory Management Issues}, describes some useful predefined storage pools
843 and in particular the GNAT Debug Pool facility, which helps detect incorrect
844 memory references.
845 @ifclear vms
846 It also describes @command{gnatmem}, a utility that monitors dynamic
847 allocation and deallocation and helps detect ``memory leaks''.
848 @end ifclear
849
850 @item
851 @ref{Stack Related Facilities}, describes some useful tools associated with
852 stack checking and analysis.
853
854 @item
855 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
856 a utility that checks Ada code against a set of rules.
857
858 @item
859 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
860 a utility that generates empty but compilable bodies for library units.
861
862 @item
863 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
864 generate automatically Ada bindings from C and C++ headers.
865
866 @item
867 @ref{Other Utility Programs}, discusses several other GNAT utilities,
868 including @code{gnathtml}.
869
870 @ifclear vms
871 @item
872 @ref{Code Coverage and Profiling}, describes how to perform a structural
873 coverage and profile the execution of Ada programs.
874 @end ifclear
875
876 @item
877 @ref{Running and Debugging Ada Programs}, describes how to run and debug
878 Ada programs.
879
880 @ifset vms
881 @item
882 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
883 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
884 developed by Digital Equipment Corporation and currently supported by HP.}
885 for OpenVMS Alpha. This product was formerly known as DEC Ada,
886 @cindex DEC Ada
887 and for
888 historical compatibility reasons, the relevant libraries still use the
889 DEC prefix.
890 @end ifset
891
892 @item
893 @ref{Platform-Specific Information for the Run-Time Libraries},
894 describes the various run-time
895 libraries supported by GNAT on various platforms and explains how to
896 choose a particular library.
897
898 @item
899 @ref{Example of Binder Output File}, shows the source code for the binder
900 output file for a sample program.
901
902 @item
903 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
904 you deal with elaboration order issues.
905
906 @item
907 @ref{Conditional Compilation}, describes how to model conditional compilation,
908 both with Ada in general and with GNAT facilities in particular.
909
910 @item
911 @ref{Inline Assembler}, shows how to use the inline assembly facility
912 in an Ada program.
913
914 @item
915 @ref{Compatibility and Porting Guide}, contains sections on compatibility
916 of GNAT with other Ada development environments (including Ada 83 systems),
917 to assist in porting code from those environments.
918
919 @ifset unw
920 @item
921 @ref{Microsoft Windows Topics}, presents information relevant to the
922 Microsoft Windows platform.
923 @end ifset
924 @end itemize
925
926 @c *************************************************
927 @node What You Should Know before Reading This Guide
928 @c *************************************************
929 @unnumberedsec What You Should Know before Reading This Guide
930
931 @cindex Ada 95 Language Reference Manual
932 @cindex Ada 2005 Language Reference Manual
933 @noindent
934 This guide assumes a basic familiarity with the Ada 95 language, as
935 described in the International Standard ANSI/ISO/IEC-8652:1995, January
936 1995.
937 It does not require knowledge of the new features introduced by Ada 2005,
938 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
939 and Amendment 1).
940 Both reference manuals are included in the GNAT documentation
941 package.
942
943 @node Related Information
944 @unnumberedsec Related Information
945
946 @noindent
947 For further information about related tools, refer to the following
948 documents:
949
950 @itemize @bullet
951 @item
952 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
953 Reference Manual}, which contains all reference material for the GNAT
954 implementation of Ada.
955
956 @ifset unw
957 @item
958 @cite{Using the GNAT Programming Studio}, which describes the GPS
959 Integrated Development Environment.
960
961 @item
962 @cite{GNAT Programming Studio Tutorial}, which introduces the
963 main GPS features through examples.
964 @end ifset
965
966 @item
967 @cite{Ada 95 Reference Manual}, which contains reference
968 material for the Ada 95 programming language.
969
970 @item
971 @cite{Ada 2005 Reference Manual}, which contains reference
972 material for the Ada 2005 programming language.
973
974 @item
975 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
976 @ifset vms
977 in the GNU:[DOCS] directory,
978 @end ifset
979 for all details on the use of the GNU source-level debugger.
980
981 @item
982 @xref{Top,, The extensible self-documenting text editor, emacs,
983 GNU Emacs Manual},
984 @ifset vms
985 located in the GNU:[DOCS] directory if the EMACS kit is installed,
986 @end ifset
987 for full information on the extensible editor and programming
988 environment Emacs.
989
990 @end itemize
991
992 @c **************
993 @node Conventions
994 @unnumberedsec Conventions
995 @cindex Conventions
996 @cindex Typographical conventions
997
998 @noindent
999 Following are examples of the typographical and graphic conventions used
1000 in this guide:
1001
1002 @itemize @bullet
1003 @item
1004 @code{Functions}, @command{utility program names}, @code{standard names},
1005 and @code{classes}.
1006
1007 @item
1008 @option{Option flags}
1009
1010 @item
1011 @file{File names}, @samp{button names}, and @samp{field names}.
1012
1013 @item
1014 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1015 variables}.
1016
1017 @item
1018 @emph{Emphasis}.
1019
1020 @item
1021 @r{[}optional information or parameters@r{]}
1022
1023 @item
1024 Examples are described by text
1025 @smallexample
1026 and then shown this way.
1027 @end smallexample
1028 @end itemize
1029
1030 @noindent
1031 Commands that are entered by the user are preceded in this manual by the
1032 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1033 uses this sequence as a prompt, then the commands will appear exactly as
1034 you see them in the manual. If your system uses some other prompt, then
1035 the command will appear with the @code{$} replaced by whatever prompt
1036 character you are using.
1037
1038 @ifset unw
1039 Full file names are shown with the ``@code{/}'' character
1040 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1041 If you are using GNAT on a Windows platform, please note that
1042 the ``@code{\}'' character should be used instead.
1043 @end ifset
1044
1045 @c ****************************
1046 @node Getting Started with GNAT
1047 @chapter Getting Started with GNAT
1048
1049 @noindent
1050 This chapter describes some simple ways of using GNAT to build
1051 executable Ada programs.
1052 @ifset unw
1053 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1054 show how to use the command line environment.
1055 @ref{Introduction to GPS}, provides a brief
1056 introduction to the GNAT Programming Studio, a visually-oriented
1057 Integrated Development Environment for GNAT.
1058 GPS offers a graphical ``look and feel'', support for development in
1059 other programming languages, comprehensive browsing features, and
1060 many other capabilities.
1061 For information on GPS please refer to
1062 @cite{Using the GNAT Programming Studio}.
1063 @end ifset
1064
1065 @menu
1066 * Running GNAT::
1067 * Running a Simple Ada Program::
1068 * Running a Program with Multiple Units::
1069 * Using the gnatmake Utility::
1070 @ifset vms
1071 * Editing with Emacs::
1072 @end ifset
1073 @ifclear vms
1074 * Introduction to GPS::
1075 @end ifclear
1076 @end menu
1077
1078 @node Running GNAT
1079 @section Running GNAT
1080
1081 @noindent
1082 Three steps are needed to create an executable file from an Ada source
1083 file:
1084
1085 @enumerate
1086 @item
1087 The source file(s) must be compiled.
1088 @item
1089 The file(s) must be bound using the GNAT binder.
1090 @item
1091 All appropriate object files must be linked to produce an executable.
1092 @end enumerate
1093
1094 @noindent
1095 All three steps are most commonly handled by using the @command{gnatmake}
1096 utility program that, given the name of the main program, automatically
1097 performs the necessary compilation, binding and linking steps.
1098
1099 @node Running a Simple Ada Program
1100 @section Running a Simple Ada Program
1101
1102 @noindent
1103 Any text editor may be used to prepare an Ada program.
1104 (If @code{Emacs} is
1105 used, the optional Ada mode may be helpful in laying out the program.)
1106 The
1107 program text is a normal text file. We will assume in our initial
1108 example that you have used your editor to prepare the following
1109 standard format text file:
1110
1111 @smallexample @c ada
1112 @cartouche
1113 with Ada.Text_IO; use Ada.Text_IO;
1114 procedure Hello is
1115 begin
1116    Put_Line ("Hello WORLD!");
1117 end Hello;
1118 @end cartouche
1119 @end smallexample
1120
1121 @noindent
1122 This file should be named @file{hello.adb}.
1123 With the normal default file naming conventions, GNAT requires
1124 that each file
1125 contain a single compilation unit whose file name is the
1126 unit name,
1127 with periods replaced by hyphens; the
1128 extension is @file{ads} for a
1129 spec and @file{adb} for a body.
1130 You can override this default file naming convention by use of the
1131 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1132 Alternatively, if you want to rename your files according to this default
1133 convention, which is probably more convenient if you will be using GNAT
1134 for all your compilations, then the @code{gnatchop} utility
1135 can be used to generate correctly-named source files
1136 (@pxref{Renaming Files Using gnatchop}).
1137
1138 You can compile the program using the following command (@code{$} is used
1139 as the command prompt in the examples in this document):
1140
1141 @smallexample
1142 $ gcc -c hello.adb
1143 @end smallexample
1144
1145 @noindent
1146 @command{gcc} is the command used to run the compiler. This compiler is
1147 capable of compiling programs in several languages, including Ada and
1148 C. It assumes that you have given it an Ada program if the file extension is
1149 either @file{.ads} or @file{.adb}, and it will then call
1150 the GNAT compiler to compile the specified file.
1151
1152 @ifclear vms
1153 The @option{-c} switch is required. It tells @command{gcc} to only do a
1154 compilation. (For C programs, @command{gcc} can also do linking, but this
1155 capability is not used directly for Ada programs, so the @option{-c}
1156 switch must always be present.)
1157 @end ifclear
1158
1159 This compile command generates a file
1160 @file{hello.o}, which is the object
1161 file corresponding to your Ada program. It also generates
1162 an ``Ada Library Information'' file @file{hello.ali},
1163 which contains additional information used to check
1164 that an Ada program is consistent.
1165 To build an executable file,
1166 use @code{gnatbind} to bind the program
1167 and @command{gnatlink} to link it. The
1168 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1169 @file{ALI} file, but the default extension of @file{.ali} can
1170 be omitted. This means that in the most common case, the argument
1171 is simply the name of the main program:
1172
1173 @smallexample
1174 $ gnatbind hello
1175 $ gnatlink hello
1176 @end smallexample
1177
1178 @noindent
1179 A simpler method of carrying out these steps is to use
1180 @command{gnatmake},
1181 a master program that invokes all the required
1182 compilation, binding and linking tools in the correct order. In particular,
1183 @command{gnatmake} automatically recompiles any sources that have been
1184 modified since they were last compiled, or sources that depend
1185 on such modified sources, so that ``version skew'' is avoided.
1186 @cindex Version skew (avoided by @command{gnatmake})
1187
1188 @smallexample
1189 $ gnatmake hello.adb
1190 @end smallexample
1191
1192 @noindent
1193 The result is an executable program called @file{hello}, which can be
1194 run by entering:
1195
1196 @smallexample
1197 $ ^hello^RUN HELLO^
1198 @end smallexample
1199
1200 @noindent
1201 assuming that the current directory is on the search path
1202 for executable programs.
1203
1204 @noindent
1205 and, if all has gone well, you will see
1206
1207 @smallexample
1208 Hello WORLD!
1209 @end smallexample
1210
1211 @noindent
1212 appear in response to this command.
1213
1214 @c ****************************************
1215 @node Running a Program with Multiple Units
1216 @section Running a Program with Multiple Units
1217
1218 @noindent
1219 Consider a slightly more complicated example that has three files: a
1220 main program, and the spec and body of a package:
1221
1222 @smallexample @c ada
1223 @cartouche
1224 @group
1225 package Greetings is
1226    procedure Hello;
1227    procedure Goodbye;
1228 end Greetings;
1229
1230 with Ada.Text_IO; use Ada.Text_IO;
1231 package body Greetings is
1232    procedure Hello is
1233    begin
1234       Put_Line ("Hello WORLD!");
1235    end Hello;
1236
1237    procedure Goodbye is
1238    begin
1239       Put_Line ("Goodbye WORLD!");
1240    end Goodbye;
1241 end Greetings;
1242 @end group
1243
1244 @group
1245 with Greetings;
1246 procedure Gmain is
1247 begin
1248    Greetings.Hello;
1249    Greetings.Goodbye;
1250 end Gmain;
1251 @end group
1252 @end cartouche
1253 @end smallexample
1254
1255 @noindent
1256 Following the one-unit-per-file rule, place this program in the
1257 following three separate files:
1258
1259 @table @file
1260 @item greetings.ads
1261 spec of package @code{Greetings}
1262
1263 @item greetings.adb
1264 body of package @code{Greetings}
1265
1266 @item gmain.adb
1267 body of main program
1268 @end table
1269
1270 @noindent
1271 To build an executable version of
1272 this program, we could use four separate steps to compile, bind, and link
1273 the program, as follows:
1274
1275 @smallexample
1276 $ gcc -c gmain.adb
1277 $ gcc -c greetings.adb
1278 $ gnatbind gmain
1279 $ gnatlink gmain
1280 @end smallexample
1281
1282 @noindent
1283 Note that there is no required order of compilation when using GNAT.
1284 In particular it is perfectly fine to compile the main program first.
1285 Also, it is not necessary to compile package specs in the case where
1286 there is an accompanying body; you only need to compile the body. If you want
1287 to submit these files to the compiler for semantic checking and not code
1288 generation, then use the
1289 @option{-gnatc} switch:
1290
1291 @smallexample
1292 $ gcc -c greetings.ads -gnatc
1293 @end smallexample
1294
1295 @noindent
1296 Although the compilation can be done in separate steps as in the
1297 above example, in practice it is almost always more convenient
1298 to use the @command{gnatmake} tool. All you need to know in this case
1299 is the name of the main program's source file. The effect of the above four
1300 commands can be achieved with a single one:
1301
1302 @smallexample
1303 $ gnatmake gmain.adb
1304 @end smallexample
1305
1306 @noindent
1307 In the next section we discuss the advantages of using @command{gnatmake} in
1308 more detail.
1309
1310 @c *****************************
1311 @node Using the gnatmake Utility
1312 @section Using the @command{gnatmake} Utility
1313
1314 @noindent
1315 If you work on a program by compiling single components at a time using
1316 @command{gcc}, you typically keep track of the units you modify. In order to
1317 build a consistent system, you compile not only these units, but also any
1318 units that depend on the units you have modified.
1319 For example, in the preceding case,
1320 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1321 you edit @file{greetings.ads}, you must recompile both
1322 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1323 units that depend on @file{greetings.ads}.
1324
1325 @code{gnatbind} will warn you if you forget one of these compilation
1326 steps, so that it is impossible to generate an inconsistent program as a
1327 result of forgetting to do a compilation. Nevertheless it is tedious and
1328 error-prone to keep track of dependencies among units.
1329 One approach to handle the dependency-bookkeeping is to use a
1330 makefile. However, makefiles present maintenance problems of their own:
1331 if the dependencies change as you change the program, you must make
1332 sure that the makefile is kept up-to-date manually, which is also an
1333 error-prone process.
1334
1335 The @command{gnatmake} utility takes care of these details automatically.
1336 Invoke it using either one of the following forms:
1337
1338 @smallexample
1339 $ gnatmake gmain.adb
1340 $ gnatmake ^gmain^GMAIN^
1341 @end smallexample
1342
1343 @noindent
1344 The argument is the name of the file containing the main program;
1345 you may omit the extension. @command{gnatmake}
1346 examines the environment, automatically recompiles any files that need
1347 recompiling, and binds and links the resulting set of object files,
1348 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1349 In a large program, it
1350 can be extremely helpful to use @command{gnatmake}, because working out by hand
1351 what needs to be recompiled can be difficult.
1352
1353 Note that @command{gnatmake}
1354 takes into account all the Ada rules that
1355 establish dependencies among units. These include dependencies that result
1356 from inlining subprogram bodies, and from
1357 generic instantiation. Unlike some other
1358 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1359 found by the compiler on a previous compilation, which may possibly
1360 be wrong when sources change. @command{gnatmake} determines the exact set of
1361 dependencies from scratch each time it is run.
1362
1363 @ifset vms
1364 @node Editing with Emacs
1365 @section Editing with Emacs
1366 @cindex Emacs
1367
1368 @noindent
1369 Emacs is an extensible self-documenting text editor that is available in a
1370 separate VMSINSTAL kit.
1371
1372 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1373 click on the Emacs Help menu and run the Emacs Tutorial.
1374 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1375 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1376
1377 Documentation on Emacs and other tools is available in Emacs under the
1378 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1379 use the middle mouse button to select a topic (e.g.@: Emacs).
1380
1381 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1382 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1383 get to the Emacs manual.
1384 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1385 prompt.
1386
1387 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1388 which is sufficiently extensible to provide for a complete programming
1389 environment and shell for the sophisticated user.
1390 @end ifset
1391
1392 @ifclear vms
1393 @node Introduction to GPS
1394 @section Introduction to GPS
1395 @cindex GPS (GNAT Programming Studio)
1396 @cindex GNAT Programming Studio (GPS)
1397 @noindent
1398 Although the command line interface (@command{gnatmake}, etc.) alone
1399 is sufficient, a graphical Interactive Development
1400 Environment can make it easier for you to compose, navigate, and debug
1401 programs.  This section describes the main features of GPS
1402 (``GNAT Programming Studio''), the GNAT graphical IDE.
1403 You will see how to use GPS to build and debug an executable, and
1404 you will also learn some of the basics of the GNAT ``project'' facility.
1405
1406 GPS enables you to do much more than is presented here;
1407 e.g., you can produce a call graph, interface to a third-party
1408 Version Control System, and inspect the generated assembly language
1409 for a program.
1410 Indeed, GPS also supports languages other than Ada.
1411 Such additional information, and an explanation of all of the GPS menu
1412 items. may be found in the on-line help, which includes
1413 a user's guide and a tutorial (these are also accessible from the GNAT
1414 startup menu).
1415
1416 @menu
1417 * Building a New Program with GPS::
1418 * Simple Debugging with GPS::
1419 @end menu
1420
1421 @node Building a New Program with GPS
1422 @subsection Building a New Program with GPS
1423 @noindent
1424 GPS invokes the GNAT compilation tools using information
1425 contained in a @emph{project} (also known as a @emph{project file}):
1426 a collection of properties such
1427 as source directories, identities of main subprograms, tool switches, etc.,
1428 and their associated values.
1429 See @ref{GNAT Project Manager} for details.
1430 In order to run GPS, you will need to either create a new project
1431 or else open an existing one.
1432
1433 This section will explain how you can use GPS to create a project,
1434 to associate Ada source files with a project, and to build and run
1435 programs.
1436
1437 @enumerate
1438 @item @emph{Creating a project}
1439
1440 Invoke GPS, either from the command line or the platform's IDE.
1441 After it starts, GPS will display a ``Welcome'' screen with three
1442 radio buttons:
1443
1444 @itemize @bullet
1445 @item
1446 @code{Start with default project in directory}
1447
1448 @item
1449 @code{Create new project with wizard}
1450
1451 @item
1452 @code{Open existing project}
1453 @end itemize
1454
1455 @noindent
1456 Select @code{Create new project with wizard} and press @code{OK}.
1457 A new window will appear.  In the text box labeled with
1458 @code{Enter the name of the project to create}, type @file{sample}
1459 as the project name.
1460 In the next box, browse to choose the directory in which you
1461 would like to create the project file.
1462 After selecting an appropriate directory, press @code{Forward}.
1463
1464 A window will appear with the title
1465 @code{Version Control System Configuration}.
1466 Simply press @code{Forward}.
1467
1468 A window will appear with the title
1469 @code{Please select the source directories for this project}.
1470 The directory that you specified for the project file will be selected
1471 by default as the one to use for sources; simply press @code{Forward}.
1472
1473 A window will appear with the title
1474 @code{Please select the build directory for this project}.
1475 The directory that you specified for the project file will be selected
1476 by default for object files and executables;
1477 simply press @code{Forward}.
1478
1479 A window will appear with the title
1480 @code{Please select the main units for this project}.
1481 You will supply this information later, after creating the source file.
1482 Simply press @code{Forward} for now.
1483
1484 A window will appear with the title
1485 @code{Please select the switches to build the project}.
1486 Press @code{Apply}.  This will create a project file named
1487 @file{sample.prj} in the directory that you had specified.
1488
1489 @item @emph{Creating and saving the source file}
1490
1491 After you create the new project, a GPS window will appear, which is
1492 partitioned into two main sections:
1493
1494 @itemize @bullet
1495 @item
1496 A @emph{Workspace area}, initially greyed out, which you will use for
1497 creating and editing source files
1498
1499 @item
1500 Directly below, a @emph{Messages area}, which initially displays a
1501 ``Welcome'' message.
1502 (If the Messages area is not visible, drag its border upward to expand it.)
1503 @end itemize
1504
1505 @noindent
1506 Select @code{File} on the menu bar, and then the @code{New} command.
1507 The Workspace area will become white, and you can now
1508 enter the source program explicitly.
1509 Type the following text
1510
1511 @smallexample @c ada
1512 @group
1513 with Ada.Text_IO; use Ada.Text_IO;
1514 procedure Hello is
1515 begin
1516   Put_Line("Hello from GPS!");
1517 end Hello;
1518 @end group
1519 @end smallexample
1520
1521 @noindent
1522 Select @code{File}, then @code{Save As}, and enter the source file name
1523 @file{hello.adb}.
1524 The file will be saved in the same directory you specified as the
1525 location of the default project file.
1526
1527 @item @emph{Updating the project file}
1528
1529 You need to add the new source file to the project.
1530 To do this, select
1531 the @code{Project} menu and then @code{Edit project properties}.
1532 Click the @code{Main files} tab on the left, and then the
1533 @code{Add} button.
1534 Choose @file{hello.adb} from the list, and press @code{Open}.
1535 The project settings window will reflect this action.
1536 Click @code{OK}.
1537
1538 @item @emph{Building and running the program}
1539
1540 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1541 and select @file{hello.adb}.
1542 The Messages window will display the resulting invocations of @command{gcc},
1543 @command{gnatbind}, and @command{gnatlink}
1544 (reflecting the default switch settings from the
1545 project file that you created) and then a ``successful compilation/build''
1546 message.
1547
1548 To run the program, choose the @code{Build} menu, then @code{Run}, and
1549 select @command{hello}.
1550 An @emph{Arguments Selection} window will appear.
1551 There are no command line arguments, so just click @code{OK}.
1552
1553 The Messages window will now display the program's output (the string
1554 @code{Hello from GPS}), and at the bottom of the GPS window a status
1555 update is displayed (@code{Run: hello}).
1556 Close the GPS window (or select @code{File}, then @code{Exit}) to
1557 terminate this GPS session.
1558 @end enumerate
1559
1560 @node Simple Debugging with GPS
1561 @subsection Simple Debugging with GPS
1562 @noindent
1563 This section illustrates basic debugging techniques (setting breakpoints,
1564 examining/modifying variables, single stepping).
1565
1566 @enumerate
1567 @item @emph{Opening a project}
1568
1569 Start GPS and select @code{Open existing project}; browse to
1570 specify the project file @file{sample.prj} that you had created in the
1571 earlier example.
1572
1573 @item @emph{Creating a source file}
1574
1575 Select @code{File}, then @code{New}, and type in the following program:
1576
1577 @smallexample @c ada
1578 @group
1579 with Ada.Text_IO; use Ada.Text_IO;
1580 procedure Example is
1581    Line : String (1..80);
1582    N    : Natural;
1583 begin
1584    Put_Line("Type a line of text at each prompt; an empty line to exit");
1585    loop
1586       Put(": ");
1587       Get_Line (Line, N);
1588       Put_Line (Line (1..N) );
1589       exit when N=0;
1590    end loop;
1591 end Example;
1592 @end group
1593 @end smallexample
1594
1595 @noindent
1596 Select @code{File}, then @code{Save as}, and enter the file name
1597 @file{example.adb}.
1598
1599 @item @emph{Updating the project file}
1600
1601 Add @code{Example} as a new main unit for the project:
1602 @enumerate a
1603 @item
1604 Select @code{Project}, then @code{Edit Project Properties}.
1605
1606 @item
1607 Select the @code{Main files} tab, click @code{Add}, then
1608 select the file @file{example.adb} from the list, and
1609 click @code{Open}.
1610 You will see the file name appear in the list of main units
1611
1612 @item
1613 Click @code{OK}
1614 @end enumerate
1615
1616 @item @emph{Building/running the executable}
1617
1618 To build the executable
1619 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1620
1621 Run the program to see its effect (in the Messages area).
1622 Each line that you enter is displayed; an empty line will
1623 cause the loop to exit and the program to terminate.
1624
1625 @item @emph{Debugging the program}
1626
1627 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1628 which are required for debugging, are on by default when you create
1629 a new project.
1630 Thus unless you intentionally remove these settings, you will be able
1631 to debug any program that you develop using GPS.
1632
1633 @enumerate a
1634 @item @emph{Initializing}
1635
1636 Select @code{Debug}, then @code{Initialize}, then @file{example}
1637
1638 @item @emph{Setting a breakpoint}
1639
1640 After performing the initialization step, you will observe a small
1641 icon to the right of each line number.
1642 This serves as a toggle for breakpoints; clicking the icon will
1643 set a breakpoint at the corresponding line (the icon will change to
1644 a red circle with an ``x''), and clicking it again
1645 will remove the breakpoint / reset the icon.
1646
1647 For purposes of this example, set a breakpoint at line 10 (the
1648 statement @code{Put_Line@ (Line@ (1..N));}
1649
1650 @item @emph{Starting program execution}
1651
1652 Select @code{Debug}, then @code{Run}.  When the
1653 @code{Program Arguments} window appears, click @code{OK}.
1654 A console window will appear; enter some line of text,
1655 e.g.@: @code{abcde}, at the prompt.
1656 The program will pause execution when it gets to the
1657 breakpoint, and the corresponding line is highlighted.
1658
1659 @item @emph{Examining a variable}
1660
1661 Move the mouse over one of the occurrences of the variable @code{N}.
1662 You will see the value (5) displayed, in ``tool tip'' fashion.
1663 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1664 You will see information about @code{N} appear in the @code{Debugger Data}
1665 pane, showing the value as 5.
1666
1667 @item @emph{Assigning a new value to a variable}
1668
1669 Right click on the @code{N} in the @code{Debugger Data} pane, and
1670 select @code{Set value of N}.
1671 When the input window appears, enter the value @code{4} and click
1672 @code{OK}.
1673 This value does not automatically appear in the @code{Debugger Data}
1674 pane; to see it, right click again on the @code{N} in the
1675 @code{Debugger Data} pane and select @code{Update value}.
1676 The new value, 4, will appear in red.
1677
1678 @item @emph{Single stepping}
1679
1680 Select @code{Debug}, then @code{Next}.
1681 This will cause the next statement to be executed, in this case the
1682 call of @code{Put_Line} with the string slice.
1683 Notice in the console window that the displayed string is simply
1684 @code{abcd} and not @code{abcde} which you had entered.
1685 This is because the upper bound of the slice is now 4 rather than 5.
1686
1687 @item @emph{Removing a breakpoint}
1688
1689 Toggle the breakpoint icon at line 10.
1690
1691 @item @emph{Resuming execution from a breakpoint}
1692
1693 Select @code{Debug}, then @code{Continue}.
1694 The program will reach the next iteration of the loop, and
1695 wait for input after displaying the prompt.
1696 This time, just hit the @kbd{Enter} key.
1697 The value of @code{N} will be 0, and the program will terminate.
1698 The console window will disappear.
1699 @end enumerate
1700 @end enumerate
1701 @end ifclear
1702
1703 @node The GNAT Compilation Model
1704 @chapter The GNAT Compilation Model
1705 @cindex GNAT compilation model
1706 @cindex Compilation model
1707
1708 @menu
1709 * Source Representation::
1710 * Foreign Language Representation::
1711 * File Naming Rules::
1712 * Using Other File Names::
1713 * Alternative File Naming Schemes::
1714 * Generating Object Files::
1715 * Source Dependencies::
1716 * The Ada Library Information Files::
1717 * Binding an Ada Program::
1718 * Mixed Language Programming::
1719 @ifclear vms
1720 * Building Mixed Ada & C++ Programs::
1721 * Comparison between GNAT and C/C++ Compilation Models::
1722 @end ifclear
1723 * Comparison between GNAT and Conventional Ada Library Models::
1724 @ifset vms
1725 * Placement of temporary files::
1726 @end ifset
1727 @end menu
1728
1729 @noindent
1730 This chapter describes the compilation model used by GNAT. Although
1731 similar to that used by other languages, such as C and C++, this model
1732 is substantially different from the traditional Ada compilation models,
1733 which are based on a library. The model is initially described without
1734 reference to the library-based model. If you have not previously used an
1735 Ada compiler, you need only read the first part of this chapter. The
1736 last section describes and discusses the differences between the GNAT
1737 model and the traditional Ada compiler models. If you have used other
1738 Ada compilers, this section will help you to understand those
1739 differences, and the advantages of the GNAT model.
1740
1741 @node Source Representation
1742 @section Source Representation
1743 @cindex Latin-1
1744
1745 @noindent
1746 Ada source programs are represented in standard text files, using
1747 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1748 7-bit ASCII set, plus additional characters used for
1749 representing foreign languages (@pxref{Foreign Language Representation}
1750 for support of non-USA character sets). The format effector characters
1751 are represented using their standard ASCII encodings, as follows:
1752
1753 @table @code
1754 @item VT
1755 @findex VT
1756 Vertical tab, @code{16#0B#}
1757
1758 @item HT
1759 @findex HT
1760 Horizontal tab, @code{16#09#}
1761
1762 @item CR
1763 @findex CR
1764 Carriage return, @code{16#0D#}
1765
1766 @item LF
1767 @findex LF
1768 Line feed, @code{16#0A#}
1769
1770 @item FF
1771 @findex FF
1772 Form feed, @code{16#0C#}
1773 @end table
1774
1775 @noindent
1776 Source files are in standard text file format. In addition, GNAT will
1777 recognize a wide variety of stream formats, in which the end of
1778 physical lines is marked by any of the following sequences:
1779 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1780 in accommodating files that are imported from other operating systems.
1781
1782 @cindex End of source file
1783 @cindex Source file, end
1784 @findex SUB
1785 The end of a source file is normally represented by the physical end of
1786 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1787 recognized as signalling the end of the source file. Again, this is
1788 provided for compatibility with other operating systems where this
1789 code is used to represent the end of file.
1790
1791 Each file contains a single Ada compilation unit, including any pragmas
1792 associated with the unit. For example, this means you must place a
1793 package declaration (a package @dfn{spec}) and the corresponding body in
1794 separate files. An Ada @dfn{compilation} (which is a sequence of
1795 compilation units) is represented using a sequence of files. Similarly,
1796 you will place each subunit or child unit in a separate file.
1797
1798 @node Foreign Language Representation
1799 @section Foreign Language Representation
1800
1801 @noindent
1802 GNAT supports the standard character sets defined in Ada as well as
1803 several other non-standard character sets for use in localized versions
1804 of the compiler (@pxref{Character Set Control}).
1805 @menu
1806 * Latin-1::
1807 * Other 8-Bit Codes::
1808 * Wide Character Encodings::
1809 @end menu
1810
1811 @node Latin-1
1812 @subsection Latin-1
1813 @cindex Latin-1
1814
1815 @noindent
1816 The basic character set is Latin-1. This character set is defined by ISO
1817 standard 8859, part 1. The lower half (character codes @code{16#00#}
1818 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1819 is used to represent additional characters. These include extended letters
1820 used by European languages, such as French accents, the vowels with umlauts
1821 used in German, and the extra letter A-ring used in Swedish.
1822
1823 @findex Ada.Characters.Latin_1
1824 For a complete list of Latin-1 codes and their encodings, see the source
1825 file of library unit @code{Ada.Characters.Latin_1} in file
1826 @file{a-chlat1.ads}.
1827 You may use any of these extended characters freely in character or
1828 string literals. In addition, the extended characters that represent
1829 letters can be used in identifiers.
1830
1831 @node Other 8-Bit Codes
1832 @subsection Other 8-Bit Codes
1833
1834 @noindent
1835 GNAT also supports several other 8-bit coding schemes:
1836
1837 @table @asis
1838 @item ISO 8859-2 (Latin-2)
1839 @cindex Latin-2
1840 @cindex ISO 8859-2
1841 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1842 equivalence.
1843
1844 @item ISO 8859-3 (Latin-3)
1845 @cindex Latin-3
1846 @cindex ISO 8859-3
1847 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1848 equivalence.
1849
1850 @item ISO 8859-4 (Latin-4)
1851 @cindex Latin-4
1852 @cindex ISO 8859-4
1853 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1854 equivalence.
1855
1856 @item ISO 8859-5 (Cyrillic)
1857 @cindex ISO 8859-5
1858 @cindex Cyrillic
1859 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1860 lowercase equivalence.
1861
1862 @item ISO 8859-15 (Latin-9)
1863 @cindex ISO 8859-15
1864 @cindex Latin-9
1865 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1866 lowercase equivalence
1867
1868 @item IBM PC (code page 437)
1869 @cindex code page 437
1870 This code page is the normal default for PCs in the U.S. It corresponds
1871 to the original IBM PC character set. This set has some, but not all, of
1872 the extended Latin-1 letters, but these letters do not have the same
1873 encoding as Latin-1. In this mode, these letters are allowed in
1874 identifiers with uppercase and lowercase equivalence.
1875
1876 @item IBM PC (code page 850)
1877 @cindex code page 850
1878 This code page is a modification of 437 extended to include all the
1879 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1880 mode, all these letters are allowed in identifiers with uppercase and
1881 lowercase equivalence.
1882
1883 @item Full Upper 8-bit
1884 Any character in the range 80-FF allowed in identifiers, and all are
1885 considered distinct. In other words, there are no uppercase and lowercase
1886 equivalences in this range. This is useful in conjunction with
1887 certain encoding schemes used for some foreign character sets (e.g.,
1888 the typical method of representing Chinese characters on the PC).
1889
1890 @item No Upper-Half
1891 No upper-half characters in the range 80-FF are allowed in identifiers.
1892 This gives Ada 83 compatibility for identifier names.
1893 @end table
1894
1895 @noindent
1896 For precise data on the encodings permitted, and the uppercase and lowercase
1897 equivalences that are recognized, see the file @file{csets.adb} in
1898 the GNAT compiler sources. You will need to obtain a full source release
1899 of GNAT to obtain this file.
1900
1901 @node Wide Character Encodings
1902 @subsection Wide Character Encodings
1903
1904 @noindent
1905 GNAT allows wide character codes to appear in character and string
1906 literals, and also optionally in identifiers, by means of the following
1907 possible encoding schemes:
1908
1909 @table @asis
1910
1911 @item Hex Coding
1912 In this encoding, a wide character is represented by the following five
1913 character sequence:
1914
1915 @smallexample
1916 ESC a b c d
1917 @end smallexample
1918
1919 @noindent
1920 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1921 characters (using uppercase letters) of the wide character code. For
1922 example, ESC A345 is used to represent the wide character with code
1923 @code{16#A345#}.
1924 This scheme is compatible with use of the full Wide_Character set.
1925
1926 @item Upper-Half Coding
1927 @cindex Upper-Half Coding
1928 The wide character with encoding @code{16#abcd#} where the upper bit is on
1929 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1930 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1931 character, but is not required to be in the upper half. This method can
1932 be also used for shift-JIS or EUC, where the internal coding matches the
1933 external coding.
1934
1935 @item Shift JIS Coding
1936 @cindex Shift JIS Coding
1937 A wide character is represented by a two-character sequence,
1938 @code{16#ab#} and
1939 @code{16#cd#}, with the restrictions described for upper-half encoding as
1940 described above. The internal character code is the corresponding JIS
1941 character according to the standard algorithm for Shift-JIS
1942 conversion. Only characters defined in the JIS code set table can be
1943 used with this encoding method.
1944
1945 @item EUC Coding
1946 @cindex EUC Coding
1947 A wide character is represented by a two-character sequence
1948 @code{16#ab#} and
1949 @code{16#cd#}, with both characters being in the upper half. The internal
1950 character code is the corresponding JIS character according to the EUC
1951 encoding algorithm. Only characters defined in the JIS code set table
1952 can be used with this encoding method.
1953
1954 @item UTF-8 Coding
1955 A wide character is represented using
1956 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1957 10646-1/Am.2. Depending on the character value, the representation
1958 is a one, two, or three byte sequence:
1959 @smallexample
1960 @iftex
1961 @leftskip=.7cm
1962 @end iftex
1963 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1964 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1965 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1966
1967 @end smallexample
1968
1969 @noindent
1970 where the @var{xxx} bits correspond to the left-padded bits of the
1971 16-bit character value. Note that all lower half ASCII characters
1972 are represented as ASCII bytes and all upper half characters and
1973 other wide characters are represented as sequences of upper-half
1974 (The full UTF-8 scheme allows for encoding 31-bit characters as
1975 6-byte sequences, but in this implementation, all UTF-8 sequences
1976 of four or more bytes length will be treated as illegal).
1977 @item Brackets Coding
1978 In this encoding, a wide character is represented by the following eight
1979 character sequence:
1980
1981 @smallexample
1982 [ " a b c d " ]
1983 @end smallexample
1984
1985 @noindent
1986 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1987 characters (using uppercase letters) of the wide character code. For
1988 example, [``A345''] is used to represent the wide character with code
1989 @code{16#A345#}. It is also possible (though not required) to use the
1990 Brackets coding for upper half characters. For example, the code
1991 @code{16#A3#} can be represented as @code{[``A3'']}.
1992
1993 This scheme is compatible with use of the full Wide_Character set,
1994 and is also the method used for wide character encoding in the standard
1995 ACVC (Ada Compiler Validation Capability) test suite distributions.
1996
1997 @end table
1998
1999 @noindent
2000 Note: Some of these coding schemes do not permit the full use of the
2001 Ada character set. For example, neither Shift JIS, nor EUC allow the
2002 use of the upper half of the Latin-1 set.
2003
2004 @node File Naming Rules
2005 @section File Naming Rules
2006
2007 @noindent
2008 The default file name is determined by the name of the unit that the
2009 file contains. The name is formed by taking the full expanded name of
2010 the unit and replacing the separating dots with hyphens and using
2011 ^lowercase^uppercase^ for all letters.
2012
2013 An exception arises if the file name generated by the above rules starts
2014 with one of the characters
2015 @ifset vms
2016 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2017 @end ifset
2018 @ifclear vms
2019 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2020 @end ifclear
2021 and the second character is a
2022 minus. In this case, the character ^tilde^dollar sign^ is used in place
2023 of the minus. The reason for this special rule is to avoid clashes with
2024 the standard names for child units of the packages System, Ada,
2025 Interfaces, and GNAT, which use the prefixes
2026 @ifset vms
2027 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2028 @end ifset
2029 @ifclear vms
2030 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2031 @end ifclear
2032 respectively.
2033
2034 The file extension is @file{.ads} for a spec and
2035 @file{.adb} for a body. The following list shows some
2036 examples of these rules.
2037
2038 @table @file
2039 @item main.ads
2040 Main (spec)
2041 @item main.adb
2042 Main (body)
2043 @item arith_functions.ads
2044 Arith_Functions (package spec)
2045 @item arith_functions.adb
2046 Arith_Functions (package body)
2047 @item func-spec.ads
2048 Func.Spec (child package spec)
2049 @item func-spec.adb
2050 Func.Spec (child package body)
2051 @item main-sub.adb
2052 Sub (subunit of Main)
2053 @item ^a~bad.adb^A$BAD.ADB^
2054 A.Bad (child package body)
2055 @end table
2056
2057 @noindent
2058 Following these rules can result in excessively long
2059 file names if corresponding
2060 unit names are long (for example, if child units or subunits are
2061 heavily nested). An option is available to shorten such long file names
2062 (called file name ``krunching''). This may be particularly useful when
2063 programs being developed with GNAT are to be used on operating systems
2064 with limited file name lengths. @xref{Using gnatkr}.
2065
2066 Of course, no file shortening algorithm can guarantee uniqueness over
2067 all possible unit names; if file name krunching is used, it is your
2068 responsibility to ensure no name clashes occur. Alternatively you
2069 can specify the exact file names that you want used, as described
2070 in the next section. Finally, if your Ada programs are migrating from a
2071 compiler with a different naming convention, you can use the gnatchop
2072 utility to produce source files that follow the GNAT naming conventions.
2073 (For details @pxref{Renaming Files Using gnatchop}.)
2074
2075 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2076 systems, case is not significant. So for example on @code{Windows XP}
2077 if the canonical name is @code{main-sub.adb}, you can use the file name
2078 @code{Main-Sub.adb} instead. However, case is significant for other
2079 operating systems, so for example, if you want to use other than
2080 canonically cased file names on a Unix system, you need to follow
2081 the procedures described in the next section.
2082
2083 @node Using Other File Names
2084 @section Using Other File Names
2085 @cindex File names
2086
2087 @noindent
2088 In the previous section, we have described the default rules used by
2089 GNAT to determine the file name in which a given unit resides. It is
2090 often convenient to follow these default rules, and if you follow them,
2091 the compiler knows without being explicitly told where to find all
2092 the files it needs.
2093
2094 However, in some cases, particularly when a program is imported from
2095 another Ada compiler environment, it may be more convenient for the
2096 programmer to specify which file names contain which units. GNAT allows
2097 arbitrary file names to be used by means of the Source_File_Name pragma.
2098 The form of this pragma is as shown in the following examples:
2099 @cindex Source_File_Name pragma
2100
2101 @smallexample @c ada
2102 @cartouche
2103 pragma Source_File_Name (My_Utilities.Stacks,
2104   Spec_File_Name => "myutilst_a.ada");
2105 pragma Source_File_name (My_Utilities.Stacks,
2106   Body_File_Name => "myutilst.ada");
2107 @end cartouche
2108 @end smallexample
2109
2110 @noindent
2111 As shown in this example, the first argument for the pragma is the unit
2112 name (in this example a child unit). The second argument has the form
2113 of a named association. The identifier
2114 indicates whether the file name is for a spec or a body;
2115 the file name itself is given by a string literal.
2116
2117 The source file name pragma is a configuration pragma, which means that
2118 normally it will be placed in the @file{gnat.adc}
2119 file used to hold configuration
2120 pragmas that apply to a complete compilation environment.
2121 For more details on how the @file{gnat.adc} file is created and used
2122 see @ref{Handling of Configuration Pragmas}.
2123 @cindex @file{gnat.adc}
2124
2125 @ifclear vms
2126 GNAT allows completely arbitrary file names to be specified using the
2127 source file name pragma. However, if the file name specified has an
2128 extension other than @file{.ads} or @file{.adb} it is necessary to use
2129 a special syntax when compiling the file. The name in this case must be
2130 preceded by the special sequence @option{-x} followed by a space and the name
2131 of the language, here @code{ada}, as in:
2132
2133 @smallexample
2134 $ gcc -c -x ada peculiar_file_name.sim
2135 @end smallexample
2136 @end ifclear
2137
2138 @noindent
2139 @command{gnatmake} handles non-standard file names in the usual manner (the
2140 non-standard file name for the main program is simply used as the
2141 argument to gnatmake). Note that if the extension is also non-standard,
2142 then it must be included in the @command{gnatmake} command, it may not
2143 be omitted.
2144
2145 @node Alternative File Naming Schemes
2146 @section Alternative File Naming Schemes
2147 @cindex File naming schemes, alternative
2148 @cindex File names
2149
2150 In the previous section, we described the use of the @code{Source_File_Name}
2151 pragma to allow arbitrary names to be assigned to individual source files.
2152 However, this approach requires one pragma for each file, and especially in
2153 large systems can result in very long @file{gnat.adc} files, and also create
2154 a maintenance problem.
2155
2156 GNAT also provides a facility for specifying systematic file naming schemes
2157 other than the standard default naming scheme previously described. An
2158 alternative scheme for naming is specified by the use of
2159 @code{Source_File_Name} pragmas having the following format:
2160 @cindex Source_File_Name pragma
2161
2162 @smallexample @c ada
2163 pragma Source_File_Name (
2164    Spec_File_Name  => FILE_NAME_PATTERN
2165  @r{[},Casing          => CASING_SPEC@r{]}
2166  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2167
2168 pragma Source_File_Name (
2169    Body_File_Name  => FILE_NAME_PATTERN
2170  @r{[},Casing          => CASING_SPEC@r{]}
2171  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2172
2173 pragma Source_File_Name (
2174    Subunit_File_Name  => FILE_NAME_PATTERN
2175  @r{[},Casing             => CASING_SPEC@r{]}
2176  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2177
2178 FILE_NAME_PATTERN ::= STRING_LITERAL
2179 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2180 @end smallexample
2181
2182 @noindent
2183 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2184 It contains a single asterisk character, and the unit name is substituted
2185 systematically for this asterisk. The optional parameter
2186 @code{Casing} indicates
2187 whether the unit name is to be all upper-case letters, all lower-case letters,
2188 or mixed-case. If no
2189 @code{Casing} parameter is used, then the default is all
2190 ^lower-case^upper-case^.
2191
2192 The optional @code{Dot_Replacement} string is used to replace any periods
2193 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2194 argument is used then separating dots appear unchanged in the resulting
2195 file name.
2196 Although the above syntax indicates that the
2197 @code{Casing} argument must appear
2198 before the @code{Dot_Replacement} argument, but it
2199 is also permissible to write these arguments in the opposite order.
2200
2201 As indicated, it is possible to specify different naming schemes for
2202 bodies, specs, and subunits. Quite often the rule for subunits is the
2203 same as the rule for bodies, in which case, there is no need to give
2204 a separate @code{Subunit_File_Name} rule, and in this case the
2205 @code{Body_File_name} rule is used for subunits as well.
2206
2207 The separate rule for subunits can also be used to implement the rather
2208 unusual case of a compilation environment (e.g.@: a single directory) which
2209 contains a subunit and a child unit with the same unit name. Although
2210 both units cannot appear in the same partition, the Ada Reference Manual
2211 allows (but does not require) the possibility of the two units coexisting
2212 in the same environment.
2213
2214 The file name translation works in the following steps:
2215
2216 @itemize @bullet
2217
2218 @item
2219 If there is a specific @code{Source_File_Name} pragma for the given unit,
2220 then this is always used, and any general pattern rules are ignored.
2221
2222 @item
2223 If there is a pattern type @code{Source_File_Name} pragma that applies to
2224 the unit, then the resulting file name will be used if the file exists. If
2225 more than one pattern matches, the latest one will be tried first, and the
2226 first attempt resulting in a reference to a file that exists will be used.
2227
2228 @item
2229 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2230 for which the corresponding file exists, then the standard GNAT default
2231 naming rules are used.
2232
2233 @end itemize
2234
2235 @noindent
2236 As an example of the use of this mechanism, consider a commonly used scheme
2237 in which file names are all lower case, with separating periods copied
2238 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2239 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2240 two pragmas appear:
2241
2242 @smallexample @c ada
2243 pragma Source_File_Name
2244   (Spec_File_Name => "*.1.ada");
2245 pragma Source_File_Name
2246   (Body_File_Name => "*.2.ada");
2247 @end smallexample
2248
2249 @noindent
2250 The default GNAT scheme is actually implemented by providing the following
2251 default pragmas internally:
2252
2253 @smallexample @c ada
2254 pragma Source_File_Name
2255   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2256 pragma Source_File_Name
2257   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2258 @end smallexample
2259
2260 @noindent
2261 Our final example implements a scheme typically used with one of the
2262 Ada 83 compilers, where the separator character for subunits was ``__''
2263 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2264 by adding @file{.ADA}, and subunits by
2265 adding @file{.SEP}. All file names were
2266 upper case. Child units were not present of course since this was an
2267 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2268 the same double underscore separator for child units.
2269
2270 @smallexample @c ada
2271 pragma Source_File_Name
2272   (Spec_File_Name => "*_.ADA",
2273    Dot_Replacement => "__",
2274    Casing = Uppercase);
2275 pragma Source_File_Name
2276   (Body_File_Name => "*.ADA",
2277    Dot_Replacement => "__",
2278    Casing = Uppercase);
2279 pragma Source_File_Name
2280   (Subunit_File_Name => "*.SEP",
2281    Dot_Replacement => "__",
2282    Casing = Uppercase);
2283 @end smallexample
2284
2285 @node Generating Object Files
2286 @section Generating Object Files
2287
2288 @noindent
2289 An Ada program consists of a set of source files, and the first step in
2290 compiling the program is to generate the corresponding object files.
2291 These are generated by compiling a subset of these source files.
2292 The files you need to compile are the following:
2293
2294 @itemize @bullet
2295 @item
2296 If a package spec has no body, compile the package spec to produce the
2297 object file for the package.
2298
2299 @item
2300 If a package has both a spec and a body, compile the body to produce the
2301 object file for the package. The source file for the package spec need
2302 not be compiled in this case because there is only one object file, which
2303 contains the code for both the spec and body of the package.
2304
2305 @item
2306 For a subprogram, compile the subprogram body to produce the object file
2307 for the subprogram. The spec, if one is present, is as usual in a
2308 separate file, and need not be compiled.
2309
2310 @item
2311 @cindex Subunits
2312 In the case of subunits, only compile the parent unit. A single object
2313 file is generated for the entire subunit tree, which includes all the
2314 subunits.
2315
2316 @item
2317 Compile child units independently of their parent units
2318 (though, of course, the spec of all the ancestor unit must be present in order
2319 to compile a child unit).
2320
2321 @item
2322 @cindex Generics
2323 Compile generic units in the same manner as any other units. The object
2324 files in this case are small dummy files that contain at most the
2325 flag used for elaboration checking. This is because GNAT always handles generic
2326 instantiation by means of macro expansion. However, it is still necessary to
2327 compile generic units, for dependency checking and elaboration purposes.
2328 @end itemize
2329
2330 @noindent
2331 The preceding rules describe the set of files that must be compiled to
2332 generate the object files for a program. Each object file has the same
2333 name as the corresponding source file, except that the extension is
2334 @file{.o} as usual.
2335
2336 You may wish to compile other files for the purpose of checking their
2337 syntactic and semantic correctness. For example, in the case where a
2338 package has a separate spec and body, you would not normally compile the
2339 spec. However, it is convenient in practice to compile the spec to make
2340 sure it is error-free before compiling clients of this spec, because such
2341 compilations will fail if there is an error in the spec.
2342
2343 GNAT provides an option for compiling such files purely for the
2344 purposes of checking correctness; such compilations are not required as
2345 part of the process of building a program. To compile a file in this
2346 checking mode, use the @option{-gnatc} switch.
2347
2348 @node Source Dependencies
2349 @section Source Dependencies
2350
2351 @noindent
2352 A given object file clearly depends on the source file which is compiled
2353 to produce it. Here we are using @dfn{depends} in the sense of a typical
2354 @code{make} utility; in other words, an object file depends on a source
2355 file if changes to the source file require the object file to be
2356 recompiled.
2357 In addition to this basic dependency, a given object may depend on
2358 additional source files as follows:
2359
2360 @itemize @bullet
2361 @item
2362 If a file being compiled @code{with}'s a unit @var{X}, the object file
2363 depends on the file containing the spec of unit @var{X}. This includes
2364 files that are @code{with}'ed implicitly either because they are parents
2365 of @code{with}'ed child units or they are run-time units required by the
2366 language constructs used in a particular unit.
2367
2368 @item
2369 If a file being compiled instantiates a library level generic unit, the
2370 object file depends on both the spec and body files for this generic
2371 unit.
2372
2373 @item
2374 If a file being compiled instantiates a generic unit defined within a
2375 package, the object file depends on the body file for the package as
2376 well as the spec file.
2377
2378 @item
2379 @findex Inline
2380 @cindex @option{-gnatn} switch
2381 If a file being compiled contains a call to a subprogram for which
2382 pragma @code{Inline} applies and inlining is activated with the
2383 @option{-gnatn} switch, the object file depends on the file containing the
2384 body of this subprogram as well as on the file containing the spec. Note
2385 that for inlining to actually occur as a result of the use of this switch,
2386 it is necessary to compile in optimizing mode.
2387
2388 @cindex @option{-gnatN} switch
2389 The use of @option{-gnatN} activates  inlining optimization
2390 that is performed by the front end of the compiler. This inlining does
2391 not require that the code generation be optimized. Like @option{-gnatn},
2392 the use of this switch generates additional dependencies.
2393
2394 When using a gcc-based back end (in practice this means using any version
2395 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2396 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2397 Historically front end inlining was more extensive than the gcc back end
2398 inlining, but that is no longer the case.
2399
2400 @item
2401 If an object file @file{O} depends on the proper body of a subunit through
2402 inlining or instantiation, it depends on the parent unit of the subunit.
2403 This means that any modification of the parent unit or one of its subunits
2404 affects the compilation of @file{O}.
2405
2406 @item
2407 The object file for a parent unit depends on all its subunit body files.
2408
2409 @item
2410 The previous two rules meant that for purposes of computing dependencies and
2411 recompilation, a body and all its subunits are treated as an indivisible whole.
2412
2413 @noindent
2414 These rules are applied transitively: if unit @code{A} @code{with}'s
2415 unit @code{B}, whose elaboration calls an inlined procedure in package
2416 @code{C}, the object file for unit @code{A} will depend on the body of
2417 @code{C}, in file @file{c.adb}.
2418
2419 The set of dependent files described by these rules includes all the
2420 files on which the unit is semantically dependent, as dictated by the
2421 Ada language standard. However, it is a superset of what the
2422 standard describes, because it includes generic, inline, and subunit
2423 dependencies.
2424
2425 An object file must be recreated by recompiling the corresponding source
2426 file if any of the source files on which it depends are modified. For
2427 example, if the @code{make} utility is used to control compilation,
2428 the rule for an Ada object file must mention all the source files on
2429 which the object file depends, according to the above definition.
2430 The determination of the necessary
2431 recompilations is done automatically when one uses @command{gnatmake}.
2432 @end itemize
2433
2434 @node The Ada Library Information Files
2435 @section The Ada Library Information Files
2436 @cindex Ada Library Information files
2437 @cindex @file{ALI} files
2438
2439 @noindent
2440 Each compilation actually generates two output files. The first of these
2441 is the normal object file that has a @file{.o} extension. The second is a
2442 text file containing full dependency information. It has the same
2443 name as the source file, but an @file{.ali} extension.
2444 This file is known as the Ada Library Information (@file{ALI}) file.
2445 The following information is contained in the @file{ALI} file.
2446
2447 @itemize @bullet
2448 @item
2449 Version information (indicates which version of GNAT was used to compile
2450 the unit(s) in question)
2451
2452 @item
2453 Main program information (including priority and time slice settings,
2454 as well as the wide character encoding used during compilation).
2455
2456 @item
2457 List of arguments used in the @command{gcc} command for the compilation
2458
2459 @item
2460 Attributes of the unit, including configuration pragmas used, an indication
2461 of whether the compilation was successful, exception model used etc.
2462
2463 @item
2464 A list of relevant restrictions applying to the unit (used for consistency)
2465 checking.
2466
2467 @item
2468 Categorization information (e.g.@: use of pragma @code{Pure}).
2469
2470 @item
2471 Information on all @code{with}'ed units, including presence of
2472 @code{Elaborate} or @code{Elaborate_All} pragmas.
2473
2474 @item
2475 Information from any @code{Linker_Options} pragmas used in the unit
2476
2477 @item
2478 Information on the use of @code{Body_Version} or @code{Version}
2479 attributes in the unit.
2480
2481 @item
2482 Dependency information. This is a list of files, together with
2483 time stamp and checksum information. These are files on which
2484 the unit depends in the sense that recompilation is required
2485 if any of these units are modified.
2486
2487 @item
2488 Cross-reference data. Contains information on all entities referenced
2489 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2490 provide cross-reference information.
2491
2492 @end itemize
2493
2494 @noindent
2495 For a full detailed description of the format of the @file{ALI} file,
2496 see the source of the body of unit @code{Lib.Writ}, contained in file
2497 @file{lib-writ.adb} in the GNAT compiler sources.
2498
2499 @node Binding an Ada Program
2500 @section Binding an Ada Program
2501
2502 @noindent
2503 When using languages such as C and C++, once the source files have been
2504 compiled the only remaining step in building an executable program
2505 is linking the object modules together. This means that it is possible to
2506 link an inconsistent version of a program, in which two units have
2507 included different versions of the same header.
2508
2509 The rules of Ada do not permit such an inconsistent program to be built.
2510 For example, if two clients have different versions of the same package,
2511 it is illegal to build a program containing these two clients.
2512 These rules are enforced by the GNAT binder, which also determines an
2513 elaboration order consistent with the Ada rules.
2514
2515 The GNAT binder is run after all the object files for a program have
2516 been created. It is given the name of the main program unit, and from
2517 this it determines the set of units required by the program, by reading the
2518 corresponding ALI files. It generates error messages if the program is
2519 inconsistent or if no valid order of elaboration exists.
2520
2521 If no errors are detected, the binder produces a main program, in Ada by
2522 default, that contains calls to the elaboration procedures of those
2523 compilation unit that require them, followed by
2524 a call to the main program. This Ada program is compiled to generate the
2525 object file for the main program. The name of
2526 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2527 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2528 main program unit.
2529
2530 Finally, the linker is used to build the resulting executable program,
2531 using the object from the main program from the bind step as well as the
2532 object files for the Ada units of the program.
2533
2534 @node Mixed Language Programming
2535 @section Mixed Language Programming
2536 @cindex Mixed Language Programming
2537
2538 @noindent
2539 This section describes how to develop a mixed-language program,
2540 specifically one that comprises units in both Ada and C.
2541
2542 @menu
2543 * Interfacing to C::
2544 * Calling Conventions::
2545 @end menu
2546
2547 @node Interfacing to C
2548 @subsection Interfacing to C
2549 @noindent
2550 Interfacing Ada with a foreign language such as C involves using
2551 compiler directives to import and/or export entity definitions in each
2552 language---using @code{extern} statements in C, for instance, and the
2553 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2554 A full treatment of these topics is provided in Appendix B, section 1
2555 of the Ada Reference Manual.
2556
2557 There are two ways to build a program using GNAT that contains some Ada
2558 sources and some foreign language sources, depending on whether or not
2559 the main subprogram is written in Ada.  Here is a source example with
2560 the main subprogram in Ada:
2561
2562 @smallexample
2563 /* file1.c */
2564 #include <stdio.h>
2565
2566 void print_num (int num)
2567 @{
2568   printf ("num is %d.\n", num);
2569   return;
2570 @}
2571
2572 /* file2.c */
2573
2574 /* num_from_Ada is declared in my_main.adb */
2575 extern int num_from_Ada;
2576
2577 int get_num (void)
2578 @{
2579   return num_from_Ada;
2580 @}
2581 @end smallexample
2582
2583 @smallexample @c ada
2584 --  my_main.adb
2585 procedure My_Main is
2586
2587    --  Declare then export an Integer entity called num_from_Ada
2588    My_Num : Integer := 10;
2589    pragma Export (C, My_Num, "num_from_Ada");
2590
2591    --  Declare an Ada function spec for Get_Num, then use
2592    --  C function get_num for the implementation.
2593    function Get_Num return Integer;
2594    pragma Import (C, Get_Num, "get_num");
2595
2596    --  Declare an Ada procedure spec for Print_Num, then use
2597    --  C function print_num for the implementation.
2598    procedure Print_Num (Num : Integer);
2599    pragma Import (C, Print_Num, "print_num");
2600
2601 begin
2602    Print_Num (Get_Num);
2603 end My_Main;
2604 @end smallexample
2605
2606 @enumerate
2607 @item
2608 To build this example, first compile the foreign language files to
2609 generate object files:
2610 @smallexample
2611 ^gcc -c file1.c^gcc -c FILE1.C^
2612 ^gcc -c file2.c^gcc -c FILE2.C^
2613 @end smallexample
2614
2615 @item
2616 Then, compile the Ada units to produce a set of object files and ALI
2617 files:
2618 @smallexample
2619 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2620 @end smallexample
2621
2622 @item
2623 Run the Ada binder on the Ada main program:
2624 @smallexample
2625 gnatbind my_main.ali
2626 @end smallexample
2627
2628 @item
2629 Link the Ada main program, the Ada objects and the other language
2630 objects:
2631 @smallexample
2632 gnatlink my_main.ali file1.o file2.o
2633 @end smallexample
2634 @end enumerate
2635
2636 The last three steps can be grouped in a single command:
2637 @smallexample
2638 gnatmake my_main.adb -largs file1.o file2.o
2639 @end smallexample
2640
2641 @cindex Binder output file
2642 @noindent
2643 If the main program is in a language other than Ada, then you may have
2644 more than one entry point into the Ada subsystem. You must use a special
2645 binder option to generate callable routines that initialize and
2646 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2647 Calls to the initialization and finalization routines must be inserted
2648 in the main program, or some other appropriate point in the code. The
2649 call to initialize the Ada units must occur before the first Ada
2650 subprogram is called, and the call to finalize the Ada units must occur
2651 after the last Ada subprogram returns. The binder will place the
2652 initialization and finalization subprograms into the
2653 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2654 sources.  To illustrate, we have the following example:
2655
2656 @smallexample
2657 /* main.c */
2658 extern void adainit (void);
2659 extern void adafinal (void);
2660 extern int add (int, int);
2661 extern int sub (int, int);
2662
2663 int main (int argc, char *argv[])
2664 @{
2665   int a = 21, b = 7;
2666
2667   adainit();
2668
2669   /* Should print "21 + 7 = 28" */
2670   printf ("%d + %d = %d\n", a, b, add (a, b));
2671   /* Should print "21 - 7 = 14" */
2672   printf ("%d - %d = %d\n", a, b, sub (a, b));
2673
2674   adafinal();
2675 @}
2676 @end smallexample
2677
2678 @smallexample @c ada
2679 --  unit1.ads
2680 package Unit1 is
2681    function Add (A, B : Integer) return Integer;
2682    pragma Export (C, Add, "add");
2683 end Unit1;
2684
2685 --  unit1.adb
2686 package body Unit1 is
2687    function Add (A, B : Integer) return Integer is
2688    begin
2689       return A + B;
2690    end Add;
2691 end Unit1;
2692
2693 --  unit2.ads
2694 package Unit2 is
2695    function Sub (A, B : Integer) return Integer;
2696    pragma Export (C, Sub, "sub");
2697 end Unit2;
2698
2699 --  unit2.adb
2700 package body Unit2 is
2701    function Sub (A, B : Integer) return Integer is
2702    begin
2703       return A - B;
2704    end Sub;
2705 end Unit2;
2706 @end smallexample
2707
2708 @enumerate
2709 @item
2710 The build procedure for this application is similar to the last
2711 example's.  First, compile the foreign language files to generate object
2712 files:
2713 @smallexample
2714 ^gcc -c main.c^gcc -c main.c^
2715 @end smallexample
2716
2717 @item
2718 Next, compile the Ada units to produce a set of object files and ALI
2719 files:
2720 @smallexample
2721 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2722 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2723 @end smallexample
2724
2725 @item
2726 Run the Ada binder on every generated ALI file.  Make sure to use the
2727 @option{-n} option to specify a foreign main program:
2728 @smallexample
2729 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2730 @end smallexample
2731
2732 @item
2733 Link the Ada main program, the Ada objects and the foreign language
2734 objects. You need only list the last ALI file here:
2735 @smallexample
2736 gnatlink unit2.ali main.o -o exec_file
2737 @end smallexample
2738
2739 This procedure yields a binary executable called @file{exec_file}.
2740 @end enumerate
2741
2742 @noindent
2743 Depending on the circumstances (for example when your non-Ada main object
2744 does not provide symbol @code{main}), you may also need to instruct the
2745 GNAT linker not to include the standard startup objects by passing the
2746 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2747
2748 @node Calling Conventions
2749 @subsection Calling Conventions
2750 @cindex Foreign Languages
2751 @cindex Calling Conventions
2752 GNAT follows standard calling sequence conventions and will thus interface
2753 to any other language that also follows these conventions. The following
2754 Convention identifiers are recognized by GNAT:
2755
2756 @table @code
2757 @cindex Interfacing to Ada
2758 @cindex Other Ada compilers
2759 @cindex Convention Ada
2760 @item Ada
2761 This indicates that the standard Ada calling sequence will be
2762 used and all Ada data items may be passed without any limitations in the
2763 case where GNAT is used to generate both the caller and callee. It is also
2764 possible to mix GNAT generated code and code generated by another Ada
2765 compiler. In this case, the data types should be restricted to simple
2766 cases, including primitive types. Whether complex data types can be passed
2767 depends on the situation. Probably it is safe to pass simple arrays, such
2768 as arrays of integers or floats. Records may or may not work, depending
2769 on whether both compilers lay them out identically. Complex structures
2770 involving variant records, access parameters, tasks, or protected types,
2771 are unlikely to be able to be passed.
2772
2773 Note that in the case of GNAT running
2774 on a platform that supports HP Ada 83, a higher degree of compatibility
2775 can be guaranteed, and in particular records are layed out in an identical
2776 manner in the two compilers. Note also that if output from two different
2777 compilers is mixed, the program is responsible for dealing with elaboration
2778 issues. Probably the safest approach is to write the main program in the
2779 version of Ada other than GNAT, so that it takes care of its own elaboration
2780 requirements, and then call the GNAT-generated adainit procedure to ensure
2781 elaboration of the GNAT components. Consult the documentation of the other
2782 Ada compiler for further details on elaboration.
2783
2784 However, it is not possible to mix the tasking run time of GNAT and
2785 HP Ada 83, All the tasking operations must either be entirely within
2786 GNAT compiled sections of the program, or entirely within HP Ada 83
2787 compiled sections of the program.
2788
2789 @cindex Interfacing to Assembly
2790 @cindex Convention Assembler
2791 @item Assembler
2792 Specifies assembler as the convention. In practice this has the
2793 same effect as convention Ada (but is not equivalent in the sense of being
2794 considered the same convention).
2795
2796 @cindex Convention Asm
2797 @findex Asm
2798 @item Asm
2799 Equivalent to Assembler.
2800
2801 @cindex Interfacing to COBOL
2802 @cindex Convention COBOL
2803 @findex COBOL
2804 @item COBOL
2805 Data will be passed according to the conventions described
2806 in section B.4 of the Ada Reference Manual.
2807
2808 @findex C
2809 @cindex Interfacing to C
2810 @cindex Convention C
2811 @item C
2812 Data will be passed according to the conventions described
2813 in section B.3 of the Ada Reference Manual.
2814
2815 A note on interfacing to a C ``varargs'' function:
2816 @findex C varargs function
2817 @cindex Interfacing to C varargs function
2818 @cindex varargs function interfaces
2819
2820 @itemize @bullet
2821 @item
2822 In C, @code{varargs} allows a function to take a variable number of
2823 arguments. There is no direct equivalent in this to Ada. One
2824 approach that can be used is to create a C wrapper for each
2825 different profile and then interface to this C wrapper. For
2826 example, to print an @code{int} value using @code{printf},
2827 create a C function @code{printfi} that takes two arguments, a
2828 pointer to a string and an int, and calls @code{printf}.
2829 Then in the Ada program, use pragma @code{Import} to
2830 interface to @code{printfi}.
2831
2832 @item
2833 It may work on some platforms to directly interface to
2834 a @code{varargs} function by providing a specific Ada profile
2835 for a particular call. However, this does not work on
2836 all platforms, since there is no guarantee that the
2837 calling sequence for a two argument normal C function
2838 is the same as for calling a @code{varargs} C function with
2839 the same two arguments.
2840 @end itemize
2841
2842 @cindex Convention Default
2843 @findex Default
2844 @item Default
2845 Equivalent to C.
2846
2847 @cindex Convention External
2848 @findex External
2849 @item External
2850 Equivalent to C.
2851
2852 @ifclear vms
2853 @findex C++
2854 @cindex Interfacing to C++
2855 @cindex Convention C++
2856 @item C_Plus_Plus (or CPP)
2857 This stands for C++. For most purposes this is identical to C.
2858 See the separate description of the specialized GNAT pragmas relating to
2859 C++ interfacing for further details.
2860 @end ifclear
2861
2862 @findex Fortran
2863 @cindex Interfacing to Fortran
2864 @cindex Convention Fortran
2865 @item Fortran
2866 Data will be passed according to the conventions described
2867 in section B.5 of the Ada Reference Manual.
2868
2869 @item Intrinsic
2870 This applies to an intrinsic operation, as defined in the Ada
2871 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2872 this means that the body of the subprogram is provided by the compiler itself,
2873 usually by means of an efficient code sequence, and that the user does not
2874 supply an explicit body for it. In an application program, the pragma may
2875 be applied to the following sets of names:
2876
2877 @itemize @bullet
2878 @item
2879 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2880 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2881 two formal parameters. The
2882 first one must be a signed integer type or a modular type with a binary
2883 modulus, and the second parameter must be of type Natural.
2884 The return type must be the same as the type of the first argument. The size
2885 of this type can only be 8, 16, 32, or 64.
2886
2887 @item
2888 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2889 The corresponding operator declaration must have parameters and result type
2890 that have the same root numeric type (for example, all three are long_float
2891 types). This simplifies the definition of operations that use type checking
2892 to perform dimensional checks:
2893
2894 @smallexample @c ada
2895 type Distance is new Long_Float;
2896 type Time     is new Long_Float;
2897 type Velocity is new Long_Float;
2898 function "/" (D : Distance; T : Time)
2899   return Velocity;
2900 pragma Import (Intrinsic, "/");
2901 @end smallexample
2902
2903 @noindent
2904 This common idiom is often programmed with a generic definition and an
2905 explicit body. The pragma makes it simpler to introduce such declarations.
2906 It incurs no overhead in compilation time or code size, because it is
2907 implemented as a single machine instruction.
2908
2909 @item
2910 General subprogram entities, to bind an Ada subprogram declaration to
2911 a compiler builtin by name with back-ends where such interfaces are
2912 available. A typical example is the set of ``__builtin'' functions
2913 exposed by the GCC back-end, as in the following example:
2914
2915 @smallexample @c ada
2916    function builtin_sqrt (F : Float) return Float;
2917    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2918 @end smallexample
2919
2920 Most of the GCC builtins are accessible this way, and as for other
2921 import conventions (e.g. C), it is the user's responsibility to ensure
2922 that the Ada subprogram profile matches the underlying builtin
2923 expectations.
2924 @end itemize
2925
2926 @noindent
2927
2928 @ifset unw
2929 @findex Stdcall
2930 @cindex Convention Stdcall
2931 @item Stdcall
2932 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2933 and specifies that the @code{Stdcall} calling sequence will be used,
2934 as defined by the NT API. Nevertheless, to ease building
2935 cross-platform bindings this convention will be handled as a @code{C} calling
2936 convention on non-Windows platforms.
2937
2938 @findex DLL
2939 @cindex Convention DLL
2940 @item DLL
2941 This is equivalent to @code{Stdcall}.
2942
2943 @findex Win32
2944 @cindex Convention Win32
2945 @item Win32
2946 This is equivalent to @code{Stdcall}.
2947 @end ifset
2948
2949 @findex Stubbed
2950 @cindex Convention Stubbed
2951 @item Stubbed
2952 This is a special convention that indicates that the compiler
2953 should provide a stub body that raises @code{Program_Error}.
2954 @end table
2955
2956 @noindent
2957 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2958 that can be used to parametrize conventions and allow additional synonyms
2959 to be specified. For example if you have legacy code in which the convention
2960 identifier Fortran77 was used for Fortran, you can use the configuration
2961 pragma:
2962
2963 @smallexample @c ada
2964 pragma Convention_Identifier (Fortran77, Fortran);
2965 @end smallexample
2966
2967 @noindent
2968 And from now on the identifier Fortran77 may be used as a convention
2969 identifier (for example in an @code{Import} pragma) with the same
2970 meaning as Fortran.
2971
2972 @ifclear vms
2973 @node Building Mixed Ada & C++ Programs
2974 @section Building Mixed Ada and C++ Programs
2975
2976 @noindent
2977 A programmer inexperienced with mixed-language development may find that
2978 building an application containing both Ada and C++ code can be a
2979 challenge.  This section gives a few
2980 hints that should make this task easier. The first section addresses
2981 the differences between interfacing with C and interfacing with C++.
2982 The second section
2983 looks into the delicate problem of linking the complete application from
2984 its Ada and C++ parts. The last section gives some hints on how the GNAT
2985 run-time library can be adapted in order to allow inter-language dispatching
2986 with a new C++ compiler.
2987
2988 @menu
2989 * Interfacing to C++::
2990 * Linking a Mixed C++ & Ada Program::
2991 * A Simple Example::
2992 * Interfacing with C++ constructors::
2993 * Interfacing with C++ at the Class Level::
2994 @end menu
2995
2996 @node Interfacing to C++
2997 @subsection Interfacing to C++
2998
2999 @noindent
3000 GNAT supports interfacing with the G++ compiler (or any C++ compiler
3001 generating code that is compatible with the G++ Application Binary
3002 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3003
3004 @noindent
3005 Interfacing can be done at 3 levels: simple data, subprograms, and
3006 classes. In the first two cases, GNAT offers a specific @code{Convention
3007 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
3008 Usually, C++ mangles the names of subprograms. To generate proper mangled
3009 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
3010 This problem can also be addressed manually in two ways:
3011
3012 @itemize @bullet
3013 @item
3014 by modifying the C++ code in order to force a C convention using
3015 the @code{extern "C"} syntax.
3016
3017 @item
3018 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3019 Link_Name argument of the pragma import.
3020 @end itemize
3021
3022 @noindent
3023 Interfacing at the class level can be achieved by using the GNAT specific
3024 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3025 gnat_rm, GNAT Reference Manual}, for additional information.
3026
3027 @node Linking a Mixed C++ & Ada Program
3028 @subsection Linking a Mixed C++ & Ada Program
3029
3030 @noindent
3031 Usually the linker of the C++ development system must be used to link
3032 mixed applications because most C++ systems will resolve elaboration
3033 issues (such as calling constructors on global class instances)
3034 transparently during the link phase. GNAT has been adapted to ease the
3035 use of a foreign linker for the last phase. Three cases can be
3036 considered:
3037 @enumerate
3038
3039 @item
3040 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3041 The C++ linker can simply be called by using the C++ specific driver
3042 called @code{g++}.
3043
3044 Note that if the C++ code uses inline functions, you will need to
3045 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3046 order to provide an existing function implementation that the Ada code can
3047 link with.
3048
3049 @smallexample
3050 $ g++ -c -fkeep-inline-functions file1.C
3051 $ g++ -c -fkeep-inline-functions file2.C
3052 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3053 @end smallexample
3054
3055 @item
3056 Using GNAT and G++ from two different GCC installations: If both
3057 compilers are on the @env{PATH}, the previous method may be used. It is
3058 important to note that environment variables such as
3059 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3060 @env{GCC_ROOT} will affect both compilers
3061 at the same time and may make one of the two compilers operate
3062 improperly if set during invocation of the wrong compiler.  It is also
3063 very important that the linker uses the proper @file{libgcc.a} GCC
3064 library -- that is, the one from the C++ compiler installation. The
3065 implicit link command as suggested in the @command{gnatmake} command
3066 from the former example can be replaced by an explicit link command with
3067 the full-verbosity option in order to verify which library is used:
3068 @smallexample
3069 $ gnatbind ada_unit
3070 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3071 @end smallexample
3072 If there is a problem due to interfering environment variables, it can
3073 be worked around by using an intermediate script. The following example
3074 shows the proper script to use when GNAT has not been installed at its
3075 default location and g++ has been installed at its default location:
3076
3077 @smallexample
3078 $ cat ./my_script
3079 #!/bin/sh
3080 unset BINUTILS_ROOT
3081 unset GCC_ROOT
3082 c++ $*
3083 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3084 @end smallexample
3085
3086 @item
3087 Using a non-GNU C++ compiler: The commands previously described can be
3088 used to insure that the C++ linker is used. Nonetheless, you need to add
3089 a few more parameters to the link command line, depending on the exception
3090 mechanism used.
3091
3092 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3093 to the libgcc libraries are required:
3094
3095 @smallexample
3096 $ cat ./my_script
3097 #!/bin/sh
3098 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3099 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3100 @end smallexample
3101
3102 Where CC is the name of the non-GNU C++ compiler.
3103
3104 If the @code{zero cost} exception mechanism is used, and the platform
3105 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3106 paths to more objects are required:
3107
3108 @smallexample
3109 $ cat ./my_script
3110 #!/bin/sh
3111 CC `gcc -print-file-name=crtbegin.o` $* \
3112 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3113 `gcc -print-file-name=crtend.o`
3114 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3115 @end smallexample
3116
3117 If the @code{zero cost} exception mechanism is used, and the platform
3118 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3119 Tru64 or AIX), the simple approach described above will not work and
3120 a pre-linking phase using GNAT will be necessary.
3121
3122 @end enumerate
3123
3124 Another alternative is to use the @command{gprbuild} multi-language builder
3125 which has a large knowledge base and knows how to link Ada and C++ code
3126 together automatically in most cases.
3127
3128 @node A Simple Example
3129 @subsection  A Simple Example
3130 @noindent
3131 The following example, provided as part of the GNAT examples, shows how
3132 to achieve procedural interfacing between Ada and C++ in both
3133 directions. The C++ class A has two methods. The first method is exported
3134 to Ada by the means of an extern C wrapper function. The second method
3135 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3136 a limited record with a layout comparable to the C++ class. The Ada
3137 subprogram, in turn, calls the C++ method. So, starting from the C++
3138 main program, the process passes back and forth between the two
3139 languages.
3140
3141 @noindent
3142 Here are the compilation commands:
3143 @smallexample
3144 $ gnatmake -c simple_cpp_interface
3145 $ g++ -c cpp_main.C
3146 $ g++ -c ex7.C
3147 $ gnatbind -n simple_cpp_interface
3148 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3149       -lstdc++ ex7.o cpp_main.o
3150 @end smallexample
3151
3152 @noindent
3153 Here are the corresponding sources:
3154 @smallexample
3155
3156 //cpp_main.C
3157
3158 #include "ex7.h"
3159
3160 extern "C" @{
3161   void adainit (void);
3162   void adafinal (void);
3163   void method1 (A *t);
3164 @}
3165
3166 void method1 (A *t)
3167 @{
3168   t->method1 ();
3169 @}
3170
3171 int main ()
3172 @{
3173   A obj;
3174   adainit ();
3175   obj.method2 (3030);
3176   adafinal ();
3177 @}
3178
3179 //ex7.h
3180
3181 class Origin @{
3182  public:
3183   int o_value;
3184 @};
3185 class A : public Origin @{
3186  public:
3187   void method1 (void);
3188   void method2 (int v);
3189   A();
3190   int   a_value;
3191 @};
3192
3193 //ex7.C
3194
3195 #include "ex7.h"
3196 #include <stdio.h>
3197
3198 extern "C" @{ void ada_method2 (A *t, int v);@}
3199
3200 void A::method1 (void)
3201 @{
3202   a_value = 2020;
3203   printf ("in A::method1, a_value = %d \n",a_value);
3204
3205 @}
3206
3207 void A::method2 (int v)
3208 @{
3209    ada_method2 (this, v);
3210    printf ("in A::method2, a_value = %d \n",a_value);
3211
3212 @}
3213
3214 A::A(void)
3215 @{
3216    a_value = 1010;
3217   printf ("in A::A, a_value = %d \n",a_value);
3218 @}
3219 @end smallexample
3220
3221 @smallexample @c ada
3222 -- Ada sources
3223 package body Simple_Cpp_Interface is
3224
3225    procedure Ada_Method2 (This : in out A; V : Integer) is
3226    begin
3227       Method1 (This);
3228       This.A_Value := V;
3229    end Ada_Method2;
3230
3231 end Simple_Cpp_Interface;
3232
3233 with System;
3234 package Simple_Cpp_Interface is
3235    type A is limited
3236       record
3237          Vptr    : System.Address;
3238          O_Value : Integer;
3239          A_Value : Integer;
3240       end record;
3241    pragma Convention (C, A);
3242
3243    procedure Method1 (This : in out A);
3244    pragma Import (C, Method1);
3245
3246    procedure Ada_Method2 (This : in out A; V : Integer);
3247    pragma Export (C, Ada_Method2);
3248
3249 end Simple_Cpp_Interface;
3250 @end smallexample
3251
3252 @node Interfacing with C++ constructors
3253 @subsection Interfacing with C++ constructors
3254 @noindent
3255
3256 In order to interface with C++ constructors GNAT provides the
3257 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3258 gnat_rm, GNAT Reference Manual}, for additional information).
3259 In this section we present some common uses of C++ constructors
3260 in mixed-languages programs in GNAT.
3261
3262 Let us assume that we need to interface with the following
3263 C++ class:
3264
3265 @smallexample
3266 @b{class} Root @{
3267 @b{public}:
3268   int  a_value;
3269   int  b_value;
3270   @b{virtual} int Get_Value ();
3271   Root();              // Default constructor
3272   Root(int v);         // 1st non-default constructor
3273   Root(int v, int w);  // 2nd non-default constructor
3274 @};
3275 @end smallexample
3276
3277 For this purpose we can write the following package spec (further
3278 information on how to build this spec is available in
3279 @ref{Interfacing with C++ at the Class Level} and
3280 @ref{Generating Ada Bindings for C and C++ headers}).
3281
3282 @smallexample @c ada
3283 with Interfaces.C; use Interfaces.C;
3284 package Pkg_Root is
3285   type Root is tagged limited record
3286      A_Value : int;
3287      B_Value : int;
3288   end record;
3289   pragma Import (CPP, Root);
3290
3291   function Get_Value (Obj : Root) return int;
3292   pragma Import (CPP, Get_Value);
3293
3294   function Constructor return Root;
3295   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3296
3297   function Constructor (v : Integer) return Root;
3298   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3299
3300   function Constructor (v, w : Integer) return Root;
3301   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3302 end Pkg_Root;
3303 @end smallexample
3304
3305 On the Ada side the constructor is represented by a function (whose
3306 name is arbitrary) that returns the classwide type corresponding to
3307 the imported C++ class. Although the constructor is described as a
3308 function, it is typically a procedure with an extra implicit argument
3309 (the object being initialized) at the implementation level. GNAT
3310 issues the appropriate call, whatever it is, to get the object
3311 properly initialized.
3312
3313 Constructors can only appear in the following contexts:
3314
3315 @itemize @bullet
3316 @item
3317 On the right side of an initialization of an object of type @var{T}.
3318 @item
3319 On the right side of an initialization of a record component of type @var{T}.
3320 @item
3321 In an Ada 2005 limited aggregate.
3322 @item
3323 In an Ada 2005 nested limited aggregate.
3324 @item
3325 In an Ada 2005 limited aggregate that initializes an object built in
3326 place by an extended return statement.
3327 @end itemize
3328
3329 @noindent
3330 In a declaration of an object whose type is a class imported from C++,
3331 either the default C++ constructor is implicitly called by GNAT, or
3332 else the required C++ constructor must be explicitly called in the
3333 expression that initializes the object. For example:
3334
3335 @smallexample @c ada
3336   Obj1 : Root;
3337   Obj2 : Root := Constructor;
3338   Obj3 : Root := Constructor (v => 10);
3339   Obj4 : Root := Constructor (30, 40);
3340 @end smallexample
3341
3342 The first two declarations are equivalent: in both cases the default C++
3343 constructor is invoked (in the former case the call to the constructor is
3344 implicit, and in the latter case the call is explicit in the object
3345 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3346 that takes an integer argument, and @code{Obj4} is initialized by the
3347 non-default C++ constructor that takes two integers.
3348
3349 Let us derive the imported C++ class in the Ada side. For example:
3350
3351 @smallexample @c ada
3352   type DT is new Root with record
3353      C_Value : Natural := 2009;
3354   end record;
3355 @end smallexample
3356
3357 In this case the components DT inherited from the C++ side must be
3358 initialized by a C++ constructor, and the additional Ada components
3359 of type DT are initialized by GNAT. The initialization of such an
3360 object is done either by default, or by means of a function returning
3361 an aggregate of type DT, or by means of an extension aggregate.
3362
3363 @smallexample @c ada
3364   Obj5 : DT;
3365   Obj6 : DT := Function_Returning_DT (50);
3366   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3367 @end smallexample
3368
3369 The declaration of @code{Obj5} invokes the default constructors: the
3370 C++ default constructor of the parent type takes care of the initialization
3371 of the components inherited from Root, and GNAT takes care of the default
3372 initialization of the additional Ada components of type DT (that is,
3373 @code{C_Value} is initialized to value 2009). The order of invocation of
3374 the constructors is consistent with the order of elaboration required by
3375 Ada and C++. That is, the constructor of the parent type is always called
3376 before the constructor of the derived type.
3377
3378 Let us now consider a record that has components whose type is imported
3379 from C++. For example:
3380
3381 @smallexample @c ada
3382   type Rec1 is limited record
3383      Data1 : Root := Constructor (10);
3384      Value : Natural := 1000;
3385   end record;
3386
3387   type Rec2 (D : Integer := 20) is limited record
3388      Rec   : Rec1;
3389      Data2 : Root := Constructor (D, 30);
3390   end record;
3391 @end smallexample
3392
3393 The initialization of an object of type @code{Rec2} will call the
3394 non-default C++ constructors specified for the imported components.
3395 For example:
3396
3397 @smallexample @c ada
3398   Obj8 : Rec2 (40);
3399 @end smallexample
3400
3401 Using Ada 2005 we can use limited aggregates to initialize an object
3402 invoking C++ constructors that differ from those specified in the type
3403 declarations. For example:
3404
3405 @smallexample @c ada
3406   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3407                           others => <>),
3408                   others => <>);
3409 @end smallexample
3410
3411 The above declaration uses an Ada 2005 limited aggregate to
3412 initialize @code{Obj9}, and the C++ constructor that has two integer
3413 arguments is invoked to initialize the @code{Data1} component instead
3414 of the constructor specified in the declaration of type @code{Rec1}. In
3415 Ada 2005 the box in the aggregate indicates that unspecified components
3416 are initialized using the expression (if any) available in the component
3417 declaration. That is, in this case discriminant @code{D} is initialized
3418 to value @code{20}, @code{Value} is initialized to value 1000, and the
3419 non-default C++ constructor that handles two integers takes care of
3420 initializing component @code{Data2} with values @code{20,30}.
3421
3422 In Ada 2005 we can use the extended return statement to build the Ada
3423 equivalent to C++ non-default constructors. For example:
3424
3425 @smallexample @c ada
3426   function Constructor (V : Integer) return Rec2 is
3427   begin
3428      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3429                                    others => <>),
3430                            others => <>) do
3431         --  Further actions required for construction of
3432         --  objects of type Rec2
3433         ...
3434      end record;
3435   end Constructor;
3436 @end smallexample
3437
3438 In this example the extended return statement construct is used to
3439 build in place the returned object whose components are initialized
3440 by means of a limited aggregate. Any further action associated with
3441 the constructor can be placed inside the construct.
3442
3443 @node Interfacing with C++ at the Class Level
3444 @subsection Interfacing with C++ at the Class Level
3445 @noindent
3446 In this section we demonstrate the GNAT features for interfacing with
3447 C++ by means of an example making use of Ada 2005 abstract interface
3448 types. This example consists of a classification of animals; classes
3449 have been used to model our main classification of animals, and
3450 interfaces provide support for the management of secondary
3451 classifications. We first demonstrate a case in which the types and
3452 constructors are defined on the C++ side and imported from the Ada
3453 side, and latter the reverse case.
3454
3455 The root of our derivation will be the @code{Animal} class, with a
3456 single private attribute (the @code{Age} of the animal) and two public
3457 primitives to set and get the value of this attribute.
3458
3459 @smallexample
3460 @b{class} Animal @{
3461  @b{public}:
3462    @b{virtual} void Set_Age (int New_Age);
3463    @b{virtual} int Age ();
3464  @b{private}:
3465    int Age_Count;
3466 @};
3467 @end smallexample
3468
3469 Abstract interface types are defined in C++ by means of classes with pure
3470 virtual functions and no data members. In our example we will use two
3471 interfaces that provide support for the common management of @code{Carnivore}
3472 and @code{Domestic} animals:
3473
3474 @smallexample
3475 @b{class} Carnivore @{
3476 @b{public}:
3477    @b{virtual} int Number_Of_Teeth () = 0;
3478 @};
3479
3480 @b{class} Domestic @{
3481 @b{public}:
3482    @b{virtual void} Set_Owner (char* Name) = 0;
3483 @};
3484 @end smallexample
3485
3486 Using these declarations, we can now say that a @code{Dog} is an animal that is
3487 both Carnivore and Domestic, that is:
3488
3489 @smallexample
3490 @b{class} Dog : Animal, Carnivore, Domestic @{
3491  @b{public}:
3492    @b{virtual} int  Number_Of_Teeth ();
3493    @b{virtual} void Set_Owner (char* Name);
3494
3495    Dog(); // Constructor
3496  @b{private}:
3497    int  Tooth_Count;
3498    char *Owner;
3499 @};
3500 @end smallexample
3501
3502 In the following examples we will assume that the previous declarations are
3503 located in a file named @code{animals.h}. The following package demonstrates
3504 how to import these C++ declarations from the Ada side:
3505
3506 @smallexample @c ada
3507 with Interfaces.C.Strings; use Interfaces.C.Strings;
3508 package Animals is
3509   type Carnivore is interface;
3510   pragma Convention (C_Plus_Plus, Carnivore);
3511   function Number_Of_Teeth (X : Carnivore)
3512      return Natural is abstract;
3513
3514   type Domestic is interface;
3515   pragma Convention (C_Plus_Plus, Set_Owner);
3516   procedure Set_Owner
3517     (X    : in out Domestic;
3518      Name : Chars_Ptr) is abstract;
3519
3520   type Animal is tagged record
3521     Age : Natural := 0;
3522   end record;
3523   pragma Import (C_Plus_Plus, Animal);
3524
3525   procedure Set_Age (X : in out Animal; Age : Integer);
3526   pragma Import (C_Plus_Plus, Set_Age);
3527
3528   function Age (X : Animal) return Integer;
3529   pragma Import (C_Plus_Plus, Age);
3530
3531   type Dog is new Animal and Carnivore and Domestic with record
3532     Tooth_Count : Natural;
3533     Owner       : String (1 .. 30);
3534   end record;
3535   pragma Import (C_Plus_Plus, Dog);
3536
3537   function Number_Of_Teeth (A : Dog) return Integer;
3538   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3539
3540   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3541   pragma Import (C_Plus_Plus, Set_Owner);
3542
3543   function New_Dog return Dog;
3544   pragma CPP_Constructor (New_Dog);
3545   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3546 end Animals;
3547 @end smallexample
3548
3549 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3550 interfacing with these C++ classes is easy. The only requirement is that all
3551 the primitives and components must be declared exactly in the same order in
3552 the two languages.
3553
3554 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3555 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3556 the arguments to the called primitives will be the same as for C++. For the
3557 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3558 to indicate that they have been defined on the C++ side; this is required
3559 because the dispatch table associated with these tagged types will be built
3560 in the C++ side and therefore will not contain the predefined Ada primitives
3561 which Ada would otherwise expect.
3562
3563 As the reader can see there is no need to indicate the C++ mangled names
3564 associated with each subprogram because it is assumed that all the calls to
3565 these primitives will be dispatching calls. The only exception is the
3566 constructor, which must be registered with the compiler by means of
3567 @code{pragma CPP_Constructor} and needs to provide its associated C++
3568 mangled name because the Ada compiler generates direct calls to it.
3569
3570 With the above packages we can now declare objects of type Dog on the Ada side
3571 and dispatch calls to the corresponding subprograms on the C++ side. We can
3572 also extend the tagged type Dog with further fields and primitives, and
3573 override some of its C++ primitives on the Ada side. For example, here we have
3574 a type derivation defined on the Ada side that inherits all the dispatching
3575 primitives of the ancestor from the C++ side.
3576
3577 @smallexample
3578 @b{with} Animals; @b{use} Animals;
3579 @b{package} Vaccinated_Animals @b{is}
3580   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3581   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3582 @b{end} Vaccinated_Animals;
3583 @end smallexample
3584
3585 It is important to note that, because of the ABI compatibility, the programmer
3586 does not need to add any further information to indicate either the object
3587 layout or the dispatch table entry associated with each dispatching operation.
3588
3589 Now let us define all the types and constructors on the Ada side and export
3590 them to C++, using the same hierarchy of our previous example:
3591
3592 @smallexample @c ada
3593 with Interfaces.C.Strings;
3594 use Interfaces.C.Strings;
3595 package Animals is
3596   type Carnivore is interface;
3597   pragma Convention (C_Plus_Plus, Carnivore);
3598   function Number_Of_Teeth (X : Carnivore)
3599      return Natural is abstract;
3600
3601   type Domestic is interface;
3602   pragma Convention (C_Plus_Plus, Set_Owner);
3603   procedure Set_Owner
3604     (X    : in out Domestic;
3605      Name : Chars_Ptr) is abstract;
3606
3607   type Animal is tagged record
3608     Age : Natural := 0;
3609   end record;
3610   pragma Convention (C_Plus_Plus, Animal);
3611
3612   procedure Set_Age (X : in out Animal; Age : Integer);
3613   pragma Export (C_Plus_Plus, Set_Age);
3614
3615   function Age (X : Animal) return Integer;
3616   pragma Export (C_Plus_Plus, Age);
3617
3618   type Dog is new Animal and Carnivore and Domestic with record
3619     Tooth_Count : Natural;
3620     Owner       : String (1 .. 30);
3621   end record;
3622   pragma Convention (C_Plus_Plus, Dog);
3623
3624   function Number_Of_Teeth (A : Dog) return Integer;
3625   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3626
3627   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3628   pragma Export (C_Plus_Plus, Set_Owner);
3629
3630   function New_Dog return Dog'Class;
3631   pragma Export (C_Plus_Plus, New_Dog);
3632 end Animals;
3633 @end smallexample
3634
3635 Compared with our previous example the only difference is the use of
3636 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3637 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3638 nothing else to be done; as explained above, the only requirement is that all
3639 the primitives and components are declared in exactly the same order.
3640
3641 For completeness, let us see a brief C++ main program that uses the
3642 declarations available in @code{animals.h} (presented in our first example) to
3643 import and use the declarations from the Ada side, properly initializing and
3644 finalizing the Ada run-time system along the way:
3645
3646 @smallexample
3647 @b{#include} "animals.h"
3648 @b{#include} <iostream>
3649 @b{using namespace} std;
3650
3651 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3652 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3653 void Check_Animal (Animal *obj)       @{@dots{}@}
3654 void Check_Dog (Dog *obj)             @{@dots{}@}
3655
3656 @b{extern} "C" @{
3657   void adainit (void);
3658   void adafinal (void);
3659   Dog* new_dog ();
3660 @}
3661
3662 void test ()
3663 @{
3664   Dog *obj = new_dog();  // Ada constructor
3665   Check_Carnivore (obj); // Check secondary DT
3666   Check_Domestic (obj);  // Check secondary DT
3667   Check_Animal (obj);    // Check primary DT
3668   Check_Dog (obj);       // Check primary DT
3669 @}
3670
3671 int main ()
3672 @{
3673   adainit ();  test();  adafinal ();
3674   return 0;
3675 @}
3676 @end smallexample
3677
3678 @node Comparison between GNAT and C/C++ Compilation Models
3679 @section Comparison between GNAT and C/C++ Compilation Models
3680
3681 @noindent
3682 The GNAT model of compilation is close to the C and C++ models. You can
3683 think of Ada specs as corresponding to header files in C. As in C, you
3684 don't need to compile specs; they are compiled when they are used. The
3685 Ada @code{with} is similar in effect to the @code{#include} of a C
3686 header.
3687
3688 One notable difference is that, in Ada, you may compile specs separately
3689 to check them for semantic and syntactic accuracy. This is not always
3690 possible with C headers because they are fragments of programs that have
3691 less specific syntactic or semantic rules.
3692
3693 The other major difference is the requirement for running the binder,
3694 which performs two important functions. First, it checks for
3695 consistency. In C or C++, the only defense against assembling
3696 inconsistent programs lies outside the compiler, in a makefile, for
3697 example. The binder satisfies the Ada requirement that it be impossible
3698 to construct an inconsistent program when the compiler is used in normal
3699 mode.
3700
3701 @cindex Elaboration order control
3702 The other important function of the binder is to deal with elaboration
3703 issues. There are also elaboration issues in C++ that are handled
3704 automatically. This automatic handling has the advantage of being
3705 simpler to use, but the C++ programmer has no control over elaboration.
3706 Where @code{gnatbind} might complain there was no valid order of
3707 elaboration, a C++ compiler would simply construct a program that
3708 malfunctioned at run time.
3709 @end ifclear
3710
3711 @node Comparison between GNAT and Conventional Ada Library Models
3712 @section Comparison between GNAT and Conventional Ada Library Models
3713
3714 @noindent
3715 This section is intended for Ada programmers who have
3716 used an Ada compiler implementing the traditional Ada library
3717 model, as described in the Ada Reference Manual.
3718
3719 @cindex GNAT library
3720 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3721 source files themselves acts as the library. Compiling Ada programs does
3722 not generate any centralized information, but rather an object file and
3723 a ALI file, which are of interest only to the binder and linker.
3724 In a traditional system, the compiler reads information not only from
3725 the source file being compiled, but also from the centralized library.
3726 This means that the effect of a compilation depends on what has been
3727 previously compiled. In particular:
3728
3729 @itemize @bullet
3730 @item
3731 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3732 to the version of the unit most recently compiled into the library.
3733
3734 @item
3735 Inlining is effective only if the necessary body has already been
3736 compiled into the library.
3737
3738 @item
3739 Compiling a unit may obsolete other units in the library.
3740 @end itemize
3741
3742 @noindent
3743 In GNAT, compiling one unit never affects the compilation of any other
3744 units because the compiler reads only source files. Only changes to source
3745 files can affect the results of a compilation. In particular:
3746
3747 @itemize @bullet
3748 @item
3749 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3750 to the source version of the unit that is currently accessible to the
3751 compiler.
3752
3753 @item
3754 @cindex Inlining
3755 Inlining requires the appropriate source files for the package or
3756 subprogram bodies to be available to the compiler. Inlining is always
3757 effective, independent of the order in which units are complied.
3758
3759 @item
3760 Compiling a unit never affects any other compilations. The editing of
3761 sources may cause previous compilations to be out of date if they
3762 depended on the source file being modified.
3763 @end itemize
3764
3765 @noindent
3766 The most important result of these differences is that order of compilation
3767 is never significant in GNAT. There is no situation in which one is
3768 required to do one compilation before another. What shows up as order of
3769 compilation requirements in the traditional Ada library becomes, in
3770 GNAT, simple source dependencies; in other words, there is only a set
3771 of rules saying what source files must be present when a file is
3772 compiled.
3773
3774 @ifset vms
3775 @node Placement of temporary files
3776 @section Placement of temporary files
3777 @cindex Temporary files (user control over placement)
3778
3779 @noindent
3780 GNAT creates temporary files in the directory designated by the environment
3781 variable @env{TMPDIR}.
3782 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3783 for detailed information on how environment variables are resolved.
3784 For most users the easiest way to make use of this feature is to simply
3785 define @env{TMPDIR} as a job level logical name).
3786 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3787 for compiler temporary files, then you can include something like the
3788 following command in your @file{LOGIN.COM} file:
3789
3790 @smallexample
3791 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3792 @end smallexample
3793
3794 @noindent
3795 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3796 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3797 designated by @env{TEMP}.
3798 If none of these environment variables are defined then GNAT uses the
3799 directory designated by the logical name @code{SYS$SCRATCH:}
3800 (by default the user's home directory). If all else fails
3801 GNAT uses the current directory for temporary files.
3802 @end ifset
3803
3804 @c *************************
3805 @node Compiling Using gcc
3806 @chapter Compiling Using @command{gcc}
3807
3808 @noindent
3809 This chapter discusses how to compile Ada programs using the @command{gcc}
3810 command. It also describes the set of switches
3811 that can be used to control the behavior of the compiler.
3812 @menu
3813 * Compiling Programs::
3814 * Switches for gcc::
3815 * Search Paths and the Run-Time Library (RTL)::
3816 * Order of Compilation Issues::
3817 * Examples::
3818 @end menu
3819
3820 @node Compiling Programs
3821 @section Compiling Programs
3822
3823 @noindent
3824 The first step in creating an executable program is to compile the units
3825 of the program using the @command{gcc} command. You must compile the
3826 following files:
3827
3828 @itemize @bullet
3829 @item
3830 the body file (@file{.adb}) for a library level subprogram or generic
3831 subprogram
3832
3833 @item
3834 the spec file (@file{.ads}) for a library level package or generic
3835 package that has no body
3836
3837 @item
3838 the body file (@file{.adb}) for a library level package
3839 or generic package that has a body
3840
3841 @end itemize
3842
3843 @noindent
3844 You need @emph{not} compile the following files
3845
3846 @itemize @bullet
3847
3848 @item
3849 the spec of a library unit which has a body
3850
3851 @item
3852 subunits
3853 @end itemize
3854
3855 @noindent
3856 because they are compiled as part of compiling related units. GNAT
3857 package specs
3858 when the corresponding body is compiled, and subunits when the parent is
3859 compiled.
3860
3861 @cindex cannot generate code
3862 If you attempt to compile any of these files, you will get one of the
3863 following error messages (where @var{fff} is the name of the file you compiled):
3864
3865 @smallexample
3866 cannot generate code for file @var{fff} (package spec)
3867 to check package spec, use -gnatc
3868
3869 cannot generate code for file @var{fff} (missing subunits)
3870 to check parent unit, use -gnatc
3871
3872 cannot generate code for file @var{fff} (subprogram spec)
3873 to check subprogram spec, use -gnatc
3874
3875 cannot generate code for file @var{fff} (subunit)
3876 to check subunit, use -gnatc
3877 @end smallexample
3878
3879 @noindent
3880 As indicated by the above error messages, if you want to submit
3881 one of these files to the compiler to check for correct semantics
3882 without generating code, then use the @option{-gnatc} switch.
3883
3884 The basic command for compiling a file containing an Ada unit is
3885
3886 @smallexample
3887 @c $ gcc -c @ovar{switches} @file{file name}
3888 @c Expanding @ovar macro inline (explanation in macro def comments)
3889 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3890 @end smallexample
3891
3892 @noindent
3893 where @var{file name} is the name of the Ada file (usually
3894 having an extension
3895 @file{.ads} for a spec or @file{.adb} for a body).
3896 @ifclear vms
3897 You specify the
3898 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3899 @end ifclear
3900 The result of a successful compilation is an object file, which has the
3901 same name as the source file but an extension of @file{.o} and an Ada
3902 Library Information (ALI) file, which also has the same name as the
3903 source file, but with @file{.ali} as the extension. GNAT creates these
3904 two output files in the current directory, but you may specify a source
3905 file in any directory using an absolute or relative path specification
3906 containing the directory information.
3907
3908 @findex gnat1
3909 @command{gcc} is actually a driver program that looks at the extensions of
3910 the file arguments and loads the appropriate compiler. For example, the
3911 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3912 These programs are in directories known to the driver program (in some
3913 configurations via environment variables you set), but need not be in
3914 your path. The @command{gcc} driver also calls the assembler and any other
3915 utilities needed to complete the generation of the required object
3916 files.
3917
3918 It is possible to supply several file names on the same @command{gcc}
3919 command. This causes @command{gcc} to call the appropriate compiler for
3920 each file. For example, the following command lists three separate
3921 files to be compiled:
3922
3923 @smallexample
3924 $ gcc -c x.adb y.adb z.c
3925 @end smallexample
3926
3927 @noindent
3928 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3929 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3930 The compiler generates three object files @file{x.o}, @file{y.o} and
3931 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3932 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3933 @ifclear vms
3934 except for
3935 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3936 @end ifclear
3937
3938 @node Switches for gcc
3939 @section Switches for @command{gcc}
3940
3941 @noindent
3942 The @command{gcc} command accepts switches that control the
3943 compilation process. These switches are fully described in this section.
3944 First we briefly list all the switches, in alphabetical order, then we
3945 describe the switches in more detail in functionally grouped sections.
3946
3947 More switches exist for GCC than those documented here, especially
3948 for specific targets. However, their use is not recommended as
3949 they may change code generation in ways that are incompatible with
3950 the Ada run-time library, or can cause inconsistencies between
3951 compilation units.
3952
3953 @menu
3954 * Output and Error Message Control::
3955 * Warning Message Control::
3956 * Debugging and Assertion Control::
3957 * Validity Checking::
3958 * Style Checking::
3959 * Run-Time Checks::
3960 * Using gcc for Syntax Checking::
3961 * Using gcc for Semantic Checking::
3962 * Compiling Different Versions of Ada::
3963 * Character Set Control::
3964 * File Naming Control::
3965 * Subprogram Inlining Control::
3966 * Auxiliary Output Control::
3967 * Debugging Control::
3968 * Exception Handling Control::
3969 * Units to Sources Mapping Files::
3970 * Integrated Preprocessing::
3971 * Code Generation Control::
3972 @ifset vms
3973 * Return Codes::
3974 @end ifset
3975 @end menu
3976
3977 @table @option
3978 @c !sort!
3979 @ifclear vms
3980 @cindex @option{-b} (@command{gcc})
3981 @item -b @var{target}
3982 Compile your program to run on @var{target}, which is the name of a
3983 system configuration. You must have a GNAT cross-compiler built if
3984 @var{target} is not the same as your host system.
3985
3986 @item -B@var{dir}
3987 @cindex @option{-B} (@command{gcc})
3988 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3989 from @var{dir} instead of the default location. Only use this switch
3990 when multiple versions of the GNAT compiler are available.
3991 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3992 GNU Compiler Collection (GCC)}, for further details. You would normally
3993 use the @option{-b} or @option{-V} switch instead.
3994
3995 @item -c
3996 @cindex @option{-c} (@command{gcc})
3997 Compile. Always use this switch when compiling Ada programs.
3998
3999 Note: for some other languages when using @command{gcc}, notably in
4000 the case of C and C++, it is possible to use
4001 use @command{gcc} without a @option{-c} switch to
4002 compile and link in one step. In the case of GNAT, you
4003 cannot use this approach, because the binder must be run
4004 and @command{gcc} cannot be used to run the GNAT binder.
4005 @end ifclear
4006
4007 @item -fno-inline
4008 @cindex @option{-fno-inline} (@command{gcc})
4009 Suppresses all back-end inlining, even if other optimization or inlining
4010 switches are set.
4011 This includes suppression of inlining that results
4012 from the use of the pragma @code{Inline_Always}.
4013 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4014 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4015 effect if this switch is present.
4016
4017 @item -fno-inline-functions
4018 @cindex @option{-fno-inline-functions} (@command{gcc})
4019 Suppresses automatic inlining of simple subprograms, which is enabled
4020 if @option{-O3} is used.
4021
4022 @item -fno-inline-small-functions
4023 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4024 Suppresses automatic inlining of small subprograms, which is enabled
4025 if @option{-O2} is used.
4026
4027 @item -fno-inline-functions-called-once
4028 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4029 Suppresses inlining of subprograms local to the unit and called once
4030 from within it, which is enabled if @option{-O1} is used.
4031
4032 @item -fno-ivopts
4033 @cindex @option{-fno-ivopts} (@command{gcc})
4034 Suppresses high-level loop induction variable optimizations, which are
4035 enabled if @option{-O1} is used. These optimizations are generally
4036 profitable but, for some specific cases of loops with numerous uses
4037 of the iteration variable that follow a common pattern, they may end
4038 up destroying the regularity that could be exploited at a lower level
4039 and thus producing inferior code.
4040
4041 @item -fno-strict-aliasing
4042 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4043 Causes the compiler to avoid assumptions regarding non-aliasing
4044 of objects of different types. See
4045 @ref{Optimization and Strict Aliasing} for details.
4046
4047 @item -fstack-check
4048 @cindex @option{-fstack-check} (@command{gcc})
4049 Activates stack checking.
4050 See @ref{Stack Overflow Checking} for details.
4051
4052 @item -fstack-usage
4053 @cindex @option{-fstack-usage} (@command{gcc})
4054 Makes the compiler output stack usage information for the program, on a
4055 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4056
4057 @item -fcallgraph-info@r{[}=su@r{]}
4058 @cindex @option{-fcallgraph-info} (@command{gcc})
4059 Makes the compiler output callgraph information for the program, on a
4060 per-file basis.  The information is generated in the VCG format.  It can
4061 be decorated with stack-usage per-node information.
4062
4063 @item ^-g^/DEBUG^
4064 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4065 Generate debugging information. This information is stored in the object
4066 file and copied from there to the final executable file by the linker,
4067 where it can be read by the debugger. You must use the
4068 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4069
4070 @item -gnat83
4071 @cindex @option{-gnat83} (@command{gcc})
4072 Enforce Ada 83 restrictions.
4073
4074 @item -gnat95
4075 @cindex @option{-gnat95} (@command{gcc})
4076 Enforce Ada 95 restrictions.
4077
4078 @item -gnat05
4079 @cindex @option{-gnat05} (@command{gcc})
4080 Allow full Ada 2005 features.
4081
4082 @item -gnata
4083 @cindex @option{-gnata} (@command{gcc})
4084 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4085 activated. Note that these pragmas can also be controlled using the
4086 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4087 It also activates pragmas @code{Check}, @code{Precondition}, and
4088 @code{Postcondition}. Note that these pragmas can also be controlled
4089 using the configuration pragma @code{Check_Policy}.
4090
4091 @item -gnatA
4092 @cindex @option{-gnatA} (@command{gcc})
4093 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4094 it will be ignored.
4095
4096 @item -gnatb
4097 @cindex @option{-gnatb} (@command{gcc})
4098 Generate brief messages to @file{stderr} even if verbose mode set.
4099
4100 @item -gnatB
4101 @cindex @option{-gnatB} (@command{gcc})
4102 Assume no invalid (bad) values except for 'Valid attribute use
4103 (@pxref{Validity Checking}).
4104
4105 @item -gnatc
4106 @cindex @option{-gnatc} (@command{gcc})
4107 Check syntax and semantics only (no code generation attempted).
4108
4109 @item -gnatC
4110 @cindex @option{-gnatC} (@command{gcc})
4111 Generate CodePeer information (no code generation attempted).
4112 This switch will generate an intermediate representation suitable for
4113 use by CodePeer (@file{.scil} files). This switch is not compatible with
4114 code generation (it will, among other things, disable some switches such
4115 as -gnatn, and enable others such as -gnata).
4116
4117 @item -gnatd
4118 @cindex @option{-gnatd} (@command{gcc})
4119 Specify debug options for the compiler. The string of characters after
4120 the @option{-gnatd} specify the specific debug options. The possible
4121 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4122 compiler source file @file{debug.adb} for details of the implemented
4123 debug options. Certain debug options are relevant to applications
4124 programmers, and these are documented at appropriate points in this
4125 users guide.
4126
4127 @ifclear vms
4128 @item -gnatD
4129 @cindex @option{-gnatD[nn]} (@command{gcc})
4130 @end ifclear
4131 @ifset vms
4132 @item /XDEBUG /LXDEBUG=nnn
4133 @end ifset
4134 Create expanded source files for source level debugging. This switch
4135 also suppress generation of cross-reference information
4136 (see @option{-gnatx}).
4137
4138 @item -gnatec=@var{path}
4139 @cindex @option{-gnatec} (@command{gcc})
4140 Specify a configuration pragma file
4141 @ifclear vms
4142 (the equal sign is optional)
4143 @end ifclear
4144 (@pxref{The Configuration Pragmas Files}).
4145
4146 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4147 @cindex @option{-gnateD} (@command{gcc})
4148 Defines a symbol, associated with @var{value}, for preprocessing.
4149 (@pxref{Integrated Preprocessing}).
4150
4151 @item -gnatef
4152 @cindex @option{-gnatef} (@command{gcc})
4153 Display full source path name in brief error messages.
4154
4155 @item -gnateG
4156 @cindex @option{-gnateG} (@command{gcc})
4157 Save result of preprocessing in a text file.
4158
4159 @item -gnatem=@var{path}
4160 @cindex @option{-gnatem} (@command{gcc})
4161 Specify a mapping file
4162 @ifclear vms
4163 (the equal sign is optional)
4164 @end ifclear
4165 (@pxref{Units to Sources Mapping Files}).
4166
4167 @item -gnatep=@var{file}
4168 @cindex @option{-gnatep} (@command{gcc})
4169 Specify a preprocessing data file
4170 @ifclear vms
4171 (the equal sign is optional)
4172 @end ifclear
4173 (@pxref{Integrated Preprocessing}).
4174
4175 @item -gnateS
4176 @cindex @option{-gnateS} (@command{gcc})
4177 Generate SCO (Source Coverage Obligation) information in the ALI
4178 file. This information is used by advanced coverage tools. See
4179 unit @file{SCOs} in the compiler sources for details in files
4180 @file{scos.ads} and @file{scos.adb}.
4181
4182 @item -gnatE
4183 @cindex @option{-gnatE} (@command{gcc})
4184 Full dynamic elaboration checks.
4185
4186 @item -gnatf
4187 @cindex @option{-gnatf} (@command{gcc})
4188 Full errors. Multiple errors per line, all undefined references, do not
4189 attempt to suppress cascaded errors.
4190
4191 @item -gnatF
4192 @cindex @option{-gnatF} (@command{gcc})
4193 Externals names are folded to all uppercase.
4194
4195 @item ^-gnatg^/GNAT_INTERNAL^
4196 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4197 Internal GNAT implementation mode. This should not be used for
4198 applications programs, it is intended only for use by the compiler
4199 and its run-time library. For documentation, see the GNAT sources.
4200 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4201 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4202 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4203 so that all standard warnings and all standard style options are turned on.
4204 All warnings and style error messages are treated as errors.
4205
4206 @ifclear vms
4207 @item -gnatG=nn
4208 @cindex @option{-gnatG[nn]} (@command{gcc})
4209 @end ifclear
4210 @ifset vms
4211 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4212 @end ifset
4213 List generated expanded code in source form.
4214
4215 @item ^-gnath^/HELP^
4216 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4217 Output usage information. The output is written to @file{stdout}.
4218
4219 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4220 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4221 Identifier character set
4222 @ifclear vms
4223 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4224 @end ifclear
4225 For details of the possible selections for @var{c},
4226 see @ref{Character Set Control}.
4227
4228 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4229 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4230 Ignore representation clauses. When this switch is used,
4231 representation clauses are treated as comments. This is useful
4232 when initially porting code where you want to ignore rep clause
4233 problems, and also for compiling foreign code (particularly
4234 for use with ASIS). The representation clauses that are ignored
4235 are: enumeration_representation_clause, record_representation_clause,
4236 and attribute_definition_clause for the following attributes:
4237 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4238 Object_Size, Size, Small, Stream_Size, and Value_Size.
4239 Note that this option should be used only for compiling -- the
4240 code is likely to malfunction at run time.
4241
4242 @item -gnatjnn
4243 @cindex @option{-gnatjnn} (@command{gcc})
4244 Reformat error messages to fit on nn character lines
4245
4246 @item -gnatk=@var{n}
4247 @cindex @option{-gnatk} (@command{gcc})
4248 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4249
4250 @item -gnatl
4251 @cindex @option{-gnatl} (@command{gcc})
4252 Output full source listing with embedded error messages.
4253
4254 @item -gnatL
4255 @cindex @option{-gnatL} (@command{gcc})
4256 Used in conjunction with -gnatG or -gnatD to intersperse original
4257 source lines (as comment lines with line numbers) in the expanded
4258 source output.
4259
4260 @item -gnatm=@var{n}
4261 @cindex @option{-gnatm} (@command{gcc})
4262 Limit number of detected error or warning messages to @var{n}
4263 where @var{n} is in the range 1..999999. The default setting if
4264 no switch is given is 9999. If the number of warnings reaches this
4265 limit, then a message is output and further warnings are suppressed,
4266 but the compilation is continued. If the number of error messages
4267 reaches this limit, then a message is output and the compilation
4268 is abandoned. The equal sign here is optional. A value of zero
4269 means that no limit applies.
4270
4271 @item -gnatn
4272 @cindex @option{-gnatn} (@command{gcc})
4273 Activate inlining for subprograms for which
4274 pragma @code{inline} is specified. This inlining is performed
4275 by the GCC back-end.
4276
4277 @item -gnatN
4278 @cindex @option{-gnatN} (@command{gcc})
4279 Activate front end inlining for subprograms for which
4280 pragma @code{Inline} is specified. This inlining is performed
4281 by the front end and will be visible in the
4282 @option{-gnatG} output.
4283
4284 When using a gcc-based back end (in practice this means using any version
4285 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4286 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4287 Historically front end inlining was more extensive than the gcc back end
4288 inlining, but that is no longer the case.
4289
4290 @item -gnato
4291 @cindex @option{-gnato} (@command{gcc})
4292 Enable numeric overflow checking (which is not normally enabled by
4293 default). Note that division by zero is a separate check that is not
4294 controlled by this switch (division by zero checking is on by default).
4295
4296 @item -gnatp
4297 @cindex @option{-gnatp} (@command{gcc})
4298 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4299 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4300
4301 @item -gnat-p
4302 @cindex @option{-gnat-p} (@command{gcc})
4303 Cancel effect of previous @option{-gnatp} switch.
4304
4305 @item -gnatP
4306 @cindex @option{-gnatP} (@command{gcc})
4307 Enable polling. This is required on some systems (notably Windows NT) to
4308 obtain asynchronous abort and asynchronous transfer of control capability.
4309 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4310 details.
4311
4312 @item -gnatq
4313 @cindex @option{-gnatq} (@command{gcc})
4314 Don't quit. Try semantics, even if parse errors.
4315
4316 @item -gnatQ
4317 @cindex @option{-gnatQ} (@command{gcc})
4318 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4319
4320 @item -gnatr
4321 @cindex @option{-gnatr} (@command{gcc})
4322 Treat pragma Restrictions as Restriction_Warnings.
4323
4324 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4325 @cindex @option{-gnatR} (@command{gcc})
4326 Output representation information for declared types and objects.
4327
4328 @item -gnats
4329 @cindex @option{-gnats} (@command{gcc})
4330 Syntax check only.
4331
4332 @item -gnatS
4333 @cindex @option{-gnatS} (@command{gcc})
4334 Print package Standard.
4335
4336 @item -gnatt
4337 @cindex @option{-gnatt} (@command{gcc})
4338 Generate tree output file.
4339
4340 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4341 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4342 All compiler tables start at @var{nnn} times usual starting size.
4343
4344 @item -gnatu
4345 @cindex @option{-gnatu} (@command{gcc})
4346 List units for this compilation.
4347
4348 @item -gnatU
4349 @cindex @option{-gnatU} (@command{gcc})
4350 Tag all error messages with the unique string ``error:''
4351
4352 @item -gnatv
4353 @cindex @option{-gnatv} (@command{gcc})
4354 Verbose mode. Full error output with source lines to @file{stdout}.
4355
4356 @item -gnatV
4357 @cindex @option{-gnatV} (@command{gcc})
4358 Control level of validity checking (@pxref{Validity Checking}).
4359
4360 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4361 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4362 Warning mode where
4363 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4364 the exact warnings that
4365 are enabled or disabled (@pxref{Warning Message Control}).
4366
4367 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4368 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4369 Wide character encoding method
4370 @ifclear vms
4371 (@var{e}=n/h/u/s/e/8).
4372 @end ifclear
4373 @ifset vms
4374 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4375 @end ifset
4376
4377 @item -gnatx
4378 @cindex @option{-gnatx} (@command{gcc})
4379 Suppress generation of cross-reference information.
4380
4381 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4382 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4383 Enable built-in style checks (@pxref{Style Checking}).
4384
4385 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4386 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4387 Distribution stub generation and compilation
4388 @ifclear vms
4389 (@var{m}=r/c for receiver/caller stubs).
4390 @end ifclear
4391 @ifset vms
4392 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4393 to be generated and compiled).
4394 @end ifset
4395
4396 @item ^-I^/SEARCH=^@var{dir}
4397 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4398 @cindex RTL
4399 Direct GNAT to search the @var{dir} directory for source files needed by
4400 the current compilation
4401 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4402
4403 @item ^-I-^/NOCURRENT_DIRECTORY^
4404 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4405 @cindex RTL
4406 Except for the source file named in the command line, do not look for source
4407 files in the directory containing the source file named in the command line
4408 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4409
4410 @ifclear vms
4411 @item -mbig-switch
4412 @cindex @option{-mbig-switch} (@command{gcc})
4413 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4414 This standard gcc switch causes the compiler to use larger offsets in its
4415 jump table representation for @code{case} statements.
4416 This may result in less efficient code, but is sometimes necessary
4417 (for example on HP-UX targets)
4418 @cindex HP-UX and @option{-mbig-switch} option
4419 in order to compile large and/or nested @code{case} statements.
4420
4421 @item -o @var{file}
4422 @cindex @option{-o} (@command{gcc})
4423 This switch is used in @command{gcc} to redirect the generated object file
4424 and its associated ALI file. Beware of this switch with GNAT, because it may
4425 cause the object file and ALI file to have different names which in turn
4426 may confuse the binder and the linker.
4427 @end ifclear
4428
4429 @item -nostdinc
4430 @cindex @option{-nostdinc} (@command{gcc})
4431 Inhibit the search of the default location for the GNAT Run Time
4432 Library (RTL) source files.
4433
4434 @item -nostdlib
4435 @cindex @option{-nostdlib} (@command{gcc})
4436 Inhibit the search of the default location for the GNAT Run Time
4437 Library (RTL) ALI files.
4438
4439 @ifclear vms
4440 @c @item -O@ovar{n}
4441 @c Expanding @ovar macro inline (explanation in macro def comments)
4442 @item -O@r{[}@var{n}@r{]}
4443 @cindex @option{-O} (@command{gcc})
4444 @var{n} controls the optimization level.
4445
4446 @table @asis
4447 @item n = 0
4448 No optimization, the default setting if no @option{-O} appears
4449
4450 @item n = 1
4451 Normal optimization, the default if you specify @option{-O} without
4452 an operand. A good compromise between code quality and compilation
4453 time.
4454
4455 @item n = 2
4456 Extensive optimization, may improve execution time, possibly at the cost of
4457 substantially increased compilation time.
4458
4459 @item n = 3
4460 Same as @option{-O2}, and also includes inline expansion for small subprograms
4461 in the same unit.
4462
4463 @item n = s
4464 Optimize space usage
4465 @end table
4466
4467 @noindent
4468 See also @ref{Optimization Levels}.
4469 @end ifclear
4470
4471 @ifset vms
4472 @item  /NOOPTIMIZE
4473 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4474 Equivalent to @option{/OPTIMIZE=NONE}.
4475 This is the default behavior in the absence of an @option{/OPTIMIZE}
4476 qualifier.
4477
4478 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4479 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4480 Selects the level of optimization for your program. The supported
4481 keywords are as follows:
4482 @table @code
4483 @item   ALL
4484 Perform most optimizations, including those that
4485 are expensive.
4486 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4487 without keyword options.
4488
4489 @item   NONE
4490 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4491
4492 @item SOME
4493 Perform some optimizations, but omit ones that are costly.
4494
4495 @item   DEVELOPMENT
4496 Same as @code{SOME}.
4497
4498 @item INLINING
4499 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4500 automatic inlining of small subprograms within a unit
4501
4502 @item   UNROLL_LOOPS
4503 Try to unroll loops. This keyword may be specified together with
4504 any keyword above other than @code{NONE}. Loop unrolling
4505 usually, but not always, improves the performance of programs.
4506
4507 @item SPACE
4508 Optimize space usage
4509 @end table
4510
4511 @noindent
4512 See also @ref{Optimization Levels}.
4513 @end ifset
4514
4515 @ifclear vms
4516 @item -pass-exit-codes
4517 @cindex @option{-pass-exit-codes} (@command{gcc})
4518 Catch exit codes from the compiler and use the most meaningful as
4519 exit status.
4520 @end ifclear
4521
4522 @item --RTS=@var{rts-path}
4523 @cindex @option{--RTS} (@command{gcc})
4524 Specifies the default location of the runtime library. Same meaning as the
4525 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4526
4527 @item ^-S^/ASM^
4528 @cindex @option{^-S^/ASM^} (@command{gcc})
4529 ^Used in place of @option{-c} to^Used to^
4530 cause the assembler source file to be
4531 generated, using @file{^.s^.S^} as the extension,
4532 instead of the object file.
4533 This may be useful if you need to examine the generated assembly code.
4534
4535 @item ^-fverbose-asm^/VERBOSE_ASM^
4536 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4537 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4538 to cause the generated assembly code file to be annotated with variable
4539 names, making it significantly easier to follow.
4540
4541 @item ^-v^/VERBOSE^
4542 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4543 Show commands generated by the @command{gcc} driver. Normally used only for
4544 debugging purposes or if you need to be sure what version of the
4545 compiler you are executing.
4546
4547 @ifclear vms
4548 @item -V @var{ver}
4549 @cindex @option{-V} (@command{gcc})
4550 Execute @var{ver} version of the compiler. This is the @command{gcc}
4551 version, not the GNAT version.
4552 @end ifclear
4553
4554 @item ^-w^/NO_BACK_END_WARNINGS^
4555 @cindex @option{-w} (@command{gcc})
4556 Turn off warnings generated by the back end of the compiler. Use of
4557 this switch also causes the default for front end warnings to be set
4558 to suppress (as though @option{-gnatws} had appeared at the start of
4559 the options).
4560
4561 @end table
4562
4563 @ifclear vms
4564 @c Combining qualifiers does not work on VMS
4565 You may combine a sequence of GNAT switches into a single switch. For
4566 example, the combined switch
4567
4568 @cindex Combining GNAT switches
4569 @smallexample
4570 -gnatofi3
4571 @end smallexample
4572
4573 @noindent
4574 is equivalent to specifying the following sequence of switches:
4575
4576 @smallexample
4577 -gnato -gnatf -gnati3
4578 @end smallexample
4579 @end ifclear
4580
4581 @noindent
4582 The following restrictions apply to the combination of switches
4583 in this manner:
4584
4585 @itemize @bullet
4586 @item
4587 The switch @option{-gnatc} if combined with other switches must come
4588 first in the string.
4589
4590 @item
4591 The switch @option{-gnats} if combined with other switches must come
4592 first in the string.
4593
4594 @item
4595 The switches
4596 ^^@option{/DISTRIBUTION_STUBS=},^
4597 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4598 switches, and only one of them may appear in the command line.
4599
4600 @item
4601 The switch @option{-gnat-p} may not be combined with any other switch.
4602
4603 @ifclear vms
4604 @item
4605 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4606 switch), then all further characters in the switch are interpreted
4607 as style modifiers (see description of @option{-gnaty}).
4608
4609 @item
4610 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4611 switch), then all further characters in the switch are interpreted
4612 as debug flags (see description of @option{-gnatd}).
4613
4614 @item
4615 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4616 switch), then all further characters in the switch are interpreted
4617 as warning mode modifiers (see description of @option{-gnatw}).
4618
4619 @item
4620 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4621 switch), then all further characters in the switch are interpreted
4622 as validity checking options (@pxref{Validity Checking}).
4623
4624 @item
4625 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4626 a combined list of options.
4627 @end ifclear
4628 @end itemize
4629
4630 @node Output and Error Message Control
4631 @subsection Output and Error Message Control
4632 @findex stderr
4633
4634 @noindent
4635 The standard default format for error messages is called ``brief format''.
4636 Brief format messages are written to @file{stderr} (the standard error
4637 file) and have the following form:
4638
4639 @smallexample
4640 e.adb:3:04: Incorrect spelling of keyword "function"
4641 e.adb:4:20: ";" should be "is"
4642 @end smallexample
4643
4644 @noindent
4645 The first integer after the file name is the line number in the file,
4646 and the second integer is the column number within the line.
4647 @ifclear vms
4648 @code{GPS} can parse the error messages
4649 and point to the referenced character.
4650 @end ifclear
4651 The following switches provide control over the error message
4652 format:
4653
4654 @table @option
4655 @c !sort!
4656 @item -gnatv
4657 @cindex @option{-gnatv} (@command{gcc})
4658 @findex stdout
4659 @ifclear vms
4660 The v stands for verbose.
4661 @end ifclear
4662 The effect of this setting is to write long-format error
4663 messages to @file{stdout} (the standard output file.
4664 The same program compiled with the
4665 @option{-gnatv} switch would generate:
4666
4667 @smallexample
4668 @cartouche
4669 3. funcion X (Q : Integer)
4670    |
4671 >>> Incorrect spelling of keyword "function"
4672 4. return Integer;
4673                  |
4674 >>> ";" should be "is"
4675 @end cartouche
4676 @end smallexample
4677
4678 @noindent
4679 The vertical bar indicates the location of the error, and the @samp{>>>}
4680 prefix can be used to search for error messages. When this switch is
4681 used the only source lines output are those with errors.
4682
4683 @item -gnatl
4684 @cindex @option{-gnatl} (@command{gcc})
4685 @ifclear vms
4686 The @code{l} stands for list.
4687 @end ifclear
4688 This switch causes a full listing of
4689 the file to be generated. In the case where a body is
4690 compiled, the corresponding spec is also listed, along
4691 with any subunits. Typical output from compiling a package
4692 body @file{p.adb} might look like:
4693
4694 @smallexample @c ada
4695 @cartouche
4696  Compiling: p.adb
4697
4698      1. package body p is
4699      2.    procedure a;
4700      3.    procedure a is separate;
4701      4. begin
4702      5.    null
4703                |
4704         >>> missing ";"
4705
4706      6. end;
4707
4708 Compiling: p.ads
4709
4710      1. package p is
4711      2.    pragma Elaborate_Body
4712                                 |
4713         >>> missing ";"
4714
4715      3. end p;
4716
4717 Compiling: p-a.adb
4718
4719      1. separate p
4720                 |
4721         >>> missing "("
4722
4723      2. procedure a is
4724      3. begin
4725      4.    null
4726                |
4727         >>> missing ";"
4728
4729      5. end;
4730 @end cartouche
4731 @end smallexample
4732
4733 @noindent
4734 @findex stderr
4735 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4736 standard output is redirected, a brief summary is written to
4737 @file{stderr} (standard error) giving the number of error messages and
4738 warning messages generated.
4739
4740 @item -^gnatl^OUTPUT_FILE^=file
4741 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4742 This has the same effect as @option{-gnatl} except that the output is
4743 written to a file instead of to standard output. If the given name
4744 @file{fname} does not start with a period, then it is the full name
4745 of the file to be written. If @file{fname} is an extension, it is
4746 appended to the name of the file being compiled. For example, if
4747 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4748 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4749
4750 @item -gnatU
4751 @cindex @option{-gnatU} (@command{gcc})
4752 This switch forces all error messages to be preceded by the unique
4753 string ``error:''. This means that error messages take a few more
4754 characters in space, but allows easy searching for and identification
4755 of error messages.
4756
4757 @item -gnatb
4758 @cindex @option{-gnatb} (@command{gcc})
4759 @ifclear vms
4760 The @code{b} stands for brief.
4761 @end ifclear
4762 This switch causes GNAT to generate the
4763 brief format error messages to @file{stderr} (the standard error
4764 file) as well as the verbose
4765 format message or full listing (which as usual is written to
4766 @file{stdout} (the standard output file).
4767
4768 @item -gnatm=@var{n}
4769 @cindex @option{-gnatm} (@command{gcc})
4770 @ifclear vms
4771 The @code{m} stands for maximum.
4772 @end ifclear
4773 @var{n} is a decimal integer in the
4774 range of 1 to 999999 and limits the number of error or warning
4775 messages to be generated. For example, using
4776 @option{-gnatm2} might yield
4777
4778 @smallexample
4779 e.adb:3:04: Incorrect spelling of keyword "function"
4780 e.adb:5:35: missing ".."
4781 fatal error: maximum number of errors detected
4782 compilation abandoned
4783 @end smallexample
4784
4785 @noindent
4786 The default setting if
4787 no switch is given is 9999. If the number of warnings reaches this
4788 limit, then a message is output and further warnings are suppressed,
4789 but the compilation is continued. If the number of error messages
4790 reaches this limit, then a message is output and the compilation
4791 is abandoned. A value of zero means that no limit applies.
4792
4793 @noindent
4794 Note that the equal sign is optional, so the switches
4795 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4796
4797 @item -gnatf
4798 @cindex @option{-gnatf} (@command{gcc})
4799 @cindex Error messages, suppressing
4800 @ifclear vms
4801 The @code{f} stands for full.
4802 @end ifclear
4803 Normally, the compiler suppresses error messages that are likely to be
4804 redundant. This switch causes all error
4805 messages to be generated. In particular, in the case of
4806 references to undefined variables. If a given variable is referenced
4807 several times, the normal format of messages is
4808 @smallexample
4809 e.adb:7:07: "V" is undefined (more references follow)
4810 @end smallexample
4811
4812 @noindent
4813 where the parenthetical comment warns that there are additional
4814 references to the variable @code{V}. Compiling the same program with the
4815 @option{-gnatf} switch yields
4816
4817 @smallexample
4818 e.adb:7:07: "V" is undefined
4819 e.adb:8:07: "V" is undefined
4820 e.adb:8:12: "V" is undefined
4821 e.adb:8:16: "V" is undefined
4822 e.adb:9:07: "V" is undefined
4823 e.adb:9:12: "V" is undefined
4824 @end smallexample
4825
4826 @noindent
4827 The @option{-gnatf} switch also generates additional information for
4828 some error messages.  Some examples are:
4829
4830 @itemize @bullet
4831 @item
4832 Details on possibly non-portable unchecked conversion
4833 @item
4834 List possible interpretations for ambiguous calls
4835 @item
4836 Additional details on incorrect parameters
4837 @end itemize
4838
4839 @item -gnatjnn
4840 @cindex @option{-gnatjnn} (@command{gcc})
4841 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4842 with continuation lines are treated as though the continuation lines were
4843 separate messages (and so a warning with two continuation lines counts as
4844 three warnings, and is listed as three separate messages).
4845
4846 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4847 messages are output in a different manner. A message and all its continuation
4848 lines are treated as a unit, and count as only one warning or message in the
4849 statistics totals. Furthermore, the message is reformatted so that no line
4850 is longer than nn characters.
4851
4852 @item -gnatq
4853 @cindex @option{-gnatq} (@command{gcc})
4854 @ifclear vms
4855 The @code{q} stands for quit (really ``don't quit'').
4856 @end ifclear
4857 In normal operation mode, the compiler first parses the program and
4858 determines if there are any syntax errors. If there are, appropriate
4859 error messages are generated and compilation is immediately terminated.
4860 This switch tells
4861 GNAT to continue with semantic analysis even if syntax errors have been
4862 found. This may enable the detection of more errors in a single run. On
4863 the other hand, the semantic analyzer is more likely to encounter some
4864 internal fatal error when given a syntactically invalid tree.
4865
4866 @item -gnatQ
4867 @cindex @option{-gnatQ} (@command{gcc})
4868 In normal operation mode, the @file{ALI} file is not generated if any
4869 illegalities are detected in the program. The use of @option{-gnatQ} forces
4870 generation of the @file{ALI} file. This file is marked as being in
4871 error, so it cannot be used for binding purposes, but it does contain
4872 reasonably complete cross-reference information, and thus may be useful
4873 for use by tools (e.g., semantic browsing tools or integrated development
4874 environments) that are driven from the @file{ALI} file. This switch
4875 implies @option{-gnatq}, since the semantic phase must be run to get a
4876 meaningful ALI file.
4877
4878 In addition, if @option{-gnatt} is also specified, then the tree file is
4879 generated even if there are illegalities. It may be useful in this case
4880 to also specify @option{-gnatq} to ensure that full semantic processing
4881 occurs. The resulting tree file can be processed by ASIS, for the purpose
4882 of providing partial information about illegal units, but if the error
4883 causes the tree to be badly malformed, then ASIS may crash during the
4884 analysis.
4885
4886 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4887 being in error, @command{gnatmake} will attempt to recompile the source when it
4888 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4889
4890 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4891 since ALI files are never generated if @option{-gnats} is set.
4892
4893 @end table
4894
4895 @node Warning Message Control
4896 @subsection Warning Message Control
4897 @cindex Warning messages
4898 @noindent
4899 In addition to error messages, which correspond to illegalities as defined
4900 in the Ada Reference Manual, the compiler detects two kinds of warning
4901 situations.
4902
4903 First, the compiler considers some constructs suspicious and generates a
4904 warning message to alert you to a possible error. Second, if the
4905 compiler detects a situation that is sure to raise an exception at
4906 run time, it generates a warning message. The following shows an example
4907 of warning messages:
4908 @smallexample
4909 e.adb:4:24: warning: creation of object may raise Storage_Error
4910 e.adb:10:17: warning: static value out of range
4911 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4912 @end smallexample
4913
4914 @noindent
4915 GNAT considers a large number of situations as appropriate
4916 for the generation of warning messages. As always, warnings are not
4917 definite indications of errors. For example, if you do an out-of-range
4918 assignment with the deliberate intention of raising a
4919 @code{Constraint_Error} exception, then the warning that may be
4920 issued does not indicate an error. Some of the situations for which GNAT
4921 issues warnings (at least some of the time) are given in the following
4922 list. This list is not complete, and new warnings are often added to
4923 subsequent versions of GNAT. The list is intended to give a general idea
4924 of the kinds of warnings that are generated.
4925
4926 @itemize @bullet
4927 @item
4928 Possible infinitely recursive calls
4929
4930 @item
4931 Out-of-range values being assigned
4932
4933 @item
4934 Possible order of elaboration problems
4935
4936 @item
4937 Assertions (pragma Assert) that are sure to fail
4938
4939 @item
4940 Unreachable code
4941
4942 @item
4943 Address clauses with possibly unaligned values, or where an attempt is
4944 made to overlay a smaller variable with a larger one.
4945
4946 @item
4947 Fixed-point type declarations with a null range
4948
4949 @item
4950 Direct_IO or Sequential_IO instantiated with a type that has access values
4951
4952 @item
4953 Variables that are never assigned a value
4954
4955 @item
4956 Variables that are referenced before being initialized
4957
4958 @item
4959 Task entries with no corresponding @code{accept} statement
4960
4961 @item
4962 Duplicate accepts for the same task entry in a @code{select}
4963
4964 @item
4965 Objects that take too much storage
4966
4967 @item
4968 Unchecked conversion between types of differing sizes
4969
4970 @item
4971 Missing @code{return} statement along some execution path in a function
4972
4973 @item
4974 Incorrect (unrecognized) pragmas
4975
4976 @item
4977 Incorrect external names
4978
4979 @item
4980 Allocation from empty storage pool
4981
4982 @item
4983 Potentially blocking operation in protected type
4984
4985 @item
4986 Suspicious parenthesization of expressions
4987
4988 @item
4989 Mismatching bounds in an aggregate
4990
4991 @item
4992 Attempt to return local value by reference
4993
4994 @item
4995 Premature instantiation of a generic body
4996
4997 @item
4998 Attempt to pack aliased components
4999
5000 @item
5001 Out of bounds array subscripts
5002
5003 @item
5004 Wrong length on string assignment
5005
5006 @item
5007 Violations of style rules if style checking is enabled
5008
5009 @item
5010 Unused @code{with} clauses
5011
5012 @item
5013 @code{Bit_Order} usage that does not have any effect
5014
5015 @item
5016 @code{Standard.Duration} used to resolve universal fixed expression
5017
5018 @item
5019 Dereference of possibly null value
5020
5021 @item
5022 Declaration that is likely to cause storage error
5023
5024 @item
5025 Internal GNAT unit @code{with}'ed by application unit
5026
5027 @item
5028 Values known to be out of range at compile time
5029
5030 @item
5031 Unreferenced labels and variables
5032
5033 @item
5034 Address overlays that could clobber memory
5035
5036 @item
5037 Unexpected initialization when address clause present
5038
5039 @item
5040 Bad alignment for address clause
5041
5042 @item
5043 Useless type conversions
5044
5045 @item
5046 Redundant assignment statements and other redundant constructs
5047
5048 @item
5049 Useless exception handlers
5050
5051 @item
5052 Accidental hiding of name by child unit
5053
5054 @item
5055 Access before elaboration detected at compile time
5056
5057 @item
5058 A range in a @code{for} loop that is known to be null or might be null
5059
5060 @end itemize
5061
5062 @noindent
5063 The following section lists compiler switches that are available
5064 to control the handling of warning messages. It is also possible
5065 to exercise much finer control over what warnings are issued and
5066 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5067 gnat_rm, GNAT Reference manual}.
5068
5069 @table @option
5070 @c !sort!
5071 @item -gnatwa
5072 @emph{Activate all optional errors.}
5073 @cindex @option{-gnatwa} (@command{gcc})
5074 This switch activates most optional warning messages, see remaining list
5075 in this section for details on optional warning messages that can be
5076 individually controlled.  The warnings that are not turned on by this
5077 switch are
5078 @option{-gnatwd} (implicit dereferencing),
5079 @option{-gnatwh} (hiding),
5080 @option{-gnatwl} (elaboration warnings),
5081 @option{-gnatw.o} (warn on values set by out parameters ignored)
5082 and @option{-gnatwt} (tracking of deleted conditional code).
5083 All other optional warnings are turned on.
5084
5085 @item -gnatwA
5086 @emph{Suppress all optional errors.}
5087 @cindex @option{-gnatwA} (@command{gcc})
5088 This switch suppresses all optional warning messages, see remaining list
5089 in this section for details on optional warning messages that can be
5090 individually controlled.
5091
5092 @item -gnatw.a
5093 @emph{Activate warnings on failing assertions.}
5094 @cindex @option{-gnatw.a} (@command{gcc})
5095 @cindex Assert failures
5096 This switch activates warnings for assertions where the compiler can tell at
5097 compile time that the assertion will fail. Note that this warning is given
5098 even if assertions are disabled. The default is that such warnings are
5099 generated.
5100
5101 @item -gnatw.A
5102 @emph{Suppress warnings on failing assertions.}
5103 @cindex @option{-gnatw.A} (@command{gcc})
5104 @cindex Assert failures
5105 This switch suppresses warnings for assertions where the compiler can tell at
5106 compile time that the assertion will fail.
5107
5108 @item -gnatwb
5109 @emph{Activate warnings on bad fixed values.}
5110 @cindex @option{-gnatwb} (@command{gcc})
5111 @cindex Bad fixed values
5112 @cindex Fixed-point Small value
5113 @cindex Small value
5114 This switch activates warnings for static fixed-point expressions whose
5115 value is not an exact multiple of Small. Such values are implementation
5116 dependent, since an implementation is free to choose either of the multiples
5117 that surround the value. GNAT always chooses the closer one, but this is not
5118 required behavior, and it is better to specify a value that is an exact
5119 multiple, ensuring predictable execution. The default is that such warnings
5120 are not generated.
5121
5122 @item -gnatwB
5123 @emph{Suppress warnings on bad fixed values.}
5124 @cindex @option{-gnatwB} (@command{gcc})
5125 This switch suppresses warnings for static fixed-point expressions whose
5126 value is not an exact multiple of Small.
5127
5128 @item -gnatw.b
5129 @emph{Activate warnings on biased representation.}
5130 @cindex @option{-gnatw.b} (@command{gcc})
5131 @cindex Biased representation
5132 This switch activates warnings when a size clause, value size clause, component
5133 clause, or component size clause forces the use of biased representation for an
5134 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5135 to represent 10/11). The default is that such warnings are generated.
5136
5137 @item -gnatw.B
5138 @emph{Suppress warnings on biased representation.}
5139 @cindex @option{-gnatwB} (@command{gcc})
5140 This switch suppresses warnings for representation clauses that force the use
5141 of biased representation.
5142
5143 @item -gnatwc
5144 @emph{Activate warnings on conditionals.}
5145 @cindex @option{-gnatwc} (@command{gcc})
5146 @cindex Conditionals, constant
5147 This switch activates warnings for conditional expressions used in
5148 tests that are known to be True or False at compile time. The default
5149 is that such warnings are not generated.
5150 Note that this warning does
5151 not get issued for the use of boolean variables or constants whose
5152 values are known at compile time, since this is a standard technique
5153 for conditional compilation in Ada, and this would generate too many
5154 false positive warnings.
5155
5156 This warning option also activates a special test for comparisons using
5157 the operators ``>='' and`` <=''.
5158 If the compiler can tell that only the equality condition is possible,
5159 then it will warn that the ``>'' or ``<'' part of the test
5160 is useless and that the operator could be replaced by ``=''.
5161 An example would be comparing a @code{Natural} variable <= 0.
5162
5163 This warning option also generates warnings if
5164 one or both tests is optimized away in a membership test for integer
5165 values if the result can be determined at compile time. Range tests on
5166 enumeration types are not included, since it is common for such tests
5167 to include an end point.
5168
5169 This warning can also be turned on using @option{-gnatwa}.
5170
5171 @item -gnatwC
5172 @emph{Suppress warnings on conditionals.}
5173 @cindex @option{-gnatwC} (@command{gcc})
5174 This switch suppresses warnings for conditional expressions used in
5175 tests that are known to be True or False at compile time.
5176
5177 @item -gnatw.c
5178 @emph{Activate warnings on missing component clauses.}
5179 @cindex @option{-gnatw.c} (@command{gcc})
5180 @cindex Component clause, missing
5181 This switch activates warnings for record components where a record
5182 representation clause is present and has component clauses for the
5183 majority, but not all, of the components. A warning is given for each
5184 component for which no component clause is present.
5185
5186 This warning can also be turned on using @option{-gnatwa}.
5187
5188 @item -gnatw.C
5189 @emph{Suppress warnings on missing component clauses.}
5190 @cindex @option{-gnatwC} (@command{gcc})
5191 This switch suppresses warnings for record components that are
5192 missing a component clause in the situation described above.
5193
5194 @item -gnatwd
5195 @emph{Activate warnings on implicit dereferencing.}
5196 @cindex @option{-gnatwd} (@command{gcc})
5197 If this switch is set, then the use of a prefix of an access type
5198 in an indexed component, slice, or selected component without an
5199 explicit @code{.all} will generate a warning. With this warning
5200 enabled, access checks occur only at points where an explicit
5201 @code{.all} appears in the source code (assuming no warnings are
5202 generated as a result of this switch). The default is that such
5203 warnings are not generated.
5204 Note that @option{-gnatwa} does not affect the setting of
5205 this warning option.
5206
5207 @item -gnatwD
5208 @emph{Suppress warnings on implicit dereferencing.}
5209 @cindex @option{-gnatwD} (@command{gcc})
5210 @cindex Implicit dereferencing
5211 @cindex Dereferencing, implicit
5212 This switch suppresses warnings for implicit dereferences in
5213 indexed components, slices, and selected components.
5214
5215 @item -gnatwe
5216 @emph{Treat warnings as errors.}
5217 @cindex @option{-gnatwe} (@command{gcc})
5218 @cindex Warnings, treat as error
5219 This switch causes warning messages to be treated as errors.
5220 The warning string still appears, but the warning messages are counted
5221 as errors, and prevent the generation of an object file.
5222
5223 @item -gnatw.e
5224 @emph{Activate every optional warning}
5225 @cindex @option{-gnatw.e} (@command{gcc})
5226 @cindex Warnings, activate every optional warning
5227 This switch activates all optional warnings, including those which
5228 are not activated by @code{-gnatwa}.
5229
5230 @item -gnatwf
5231 @emph{Activate warnings on unreferenced formals.}
5232 @cindex @option{-gnatwf} (@command{gcc})
5233 @cindex Formals, unreferenced
5234 This switch causes a warning to be generated if a formal parameter
5235 is not referenced in the body of the subprogram. This warning can
5236 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5237 default is that these warnings are not generated.
5238
5239 @item -gnatwF
5240 @emph{Suppress warnings on unreferenced formals.}
5241 @cindex @option{-gnatwF} (@command{gcc})
5242 This switch suppresses warnings for unreferenced formal
5243 parameters. Note that the
5244 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5245 effect of warning on unreferenced entities other than subprogram
5246 formals.
5247
5248 @item -gnatwg
5249 @emph{Activate warnings on unrecognized pragmas.}
5250 @cindex @option{-gnatwg} (@command{gcc})
5251 @cindex Pragmas, unrecognized
5252 This switch causes a warning to be generated if an unrecognized
5253 pragma is encountered. Apart from issuing this warning, the
5254 pragma is ignored and has no effect. This warning can
5255 also be turned on using @option{-gnatwa}. The default
5256 is that such warnings are issued (satisfying the Ada Reference
5257 Manual requirement that such warnings appear).
5258
5259 @item -gnatwG
5260 @emph{Suppress warnings on unrecognized pragmas.}
5261 @cindex @option{-gnatwG} (@command{gcc})
5262 This switch suppresses warnings for unrecognized pragmas.
5263
5264 @item -gnatwh
5265 @emph{Activate warnings on hiding.}
5266 @cindex @option{-gnatwh} (@command{gcc})
5267 @cindex Hiding of Declarations
5268 This switch activates warnings on hiding declarations.
5269 A declaration is considered hiding
5270 if it is for a non-overloadable entity, and it declares an entity with the
5271 same name as some other entity that is directly or use-visible. The default
5272 is that such warnings are not generated.
5273 Note that @option{-gnatwa} does not affect the setting of this warning option.
5274
5275 @item -gnatwH
5276 @emph{Suppress warnings on hiding.}
5277 @cindex @option{-gnatwH} (@command{gcc})
5278 This switch suppresses warnings on hiding declarations.
5279
5280 @item -gnatwi
5281 @emph{Activate warnings on implementation units.}
5282 @cindex @option{-gnatwi} (@command{gcc})
5283 This switch activates warnings for a @code{with} of an internal GNAT
5284 implementation unit, defined as any unit from the @code{Ada},
5285 @code{Interfaces}, @code{GNAT},
5286 ^^@code{DEC},^ or @code{System}
5287 hierarchies that is not
5288 documented in either the Ada Reference Manual or the GNAT
5289 Programmer's Reference Manual. Such units are intended only
5290 for internal implementation purposes and should not be @code{with}'ed
5291 by user programs. The default is that such warnings are generated
5292 This warning can also be turned on using @option{-gnatwa}.
5293
5294 @item -gnatwI
5295 @emph{Disable warnings on implementation units.}
5296 @cindex @option{-gnatwI} (@command{gcc})
5297 This switch disables warnings for a @code{with} of an internal GNAT
5298 implementation unit.
5299
5300 @item -gnatw.i
5301 @emph{Activate warnings on overlapping actuals.}
5302 @cindex @option{-gnatw.i} (@command{gcc})
5303 This switch enables a warning on statically detectable overlapping actuals in
5304 a subprogram call, when one of the actuals is an in-out parameter, and the
5305 types of the actuals are not by-copy types. The warning is off by default,
5306 and is not included under -gnatwa.
5307
5308 @item -gnatw.I
5309 @emph{Disable warnings on overlapping actuals.}
5310 @cindex @option{-gnatw.I} (@command{gcc})
5311 This switch disables warnings on overlapping actuals in a call..
5312
5313 @item -gnatwj
5314 @emph{Activate warnings on obsolescent features (Annex J).}
5315 @cindex @option{-gnatwj} (@command{gcc})
5316 @cindex Features, obsolescent
5317 @cindex Obsolescent features
5318 If this warning option is activated, then warnings are generated for
5319 calls to subprograms marked with @code{pragma Obsolescent} and
5320 for use of features in Annex J of the Ada Reference Manual. In the
5321 case of Annex J, not all features are flagged. In particular use
5322 of the renamed packages (like @code{Text_IO}) and use of package
5323 @code{ASCII} are not flagged, since these are very common and
5324 would generate many annoying positive warnings. The default is that
5325 such warnings are not generated. This warning is also turned on by
5326 the use of @option{-gnatwa}.
5327
5328 In addition to the above cases, warnings are also generated for
5329 GNAT features that have been provided in past versions but which
5330 have been superseded (typically by features in the new Ada standard).
5331 For example, @code{pragma Ravenscar} will be flagged since its
5332 function is replaced by @code{pragma Profile(Ravenscar)}.
5333
5334 Note that this warning option functions differently from the
5335 restriction @code{No_Obsolescent_Features} in two respects.
5336 First, the restriction applies only to annex J features.
5337 Second, the restriction does flag uses of package @code{ASCII}.
5338
5339 @item -gnatwJ
5340 @emph{Suppress warnings on obsolescent features (Annex J).}
5341 @cindex @option{-gnatwJ} (@command{gcc})
5342 This switch disables warnings on use of obsolescent features.
5343
5344 @item -gnatwk
5345 @emph{Activate warnings on variables that could be constants.}
5346 @cindex @option{-gnatwk} (@command{gcc})
5347 This switch activates warnings for variables that are initialized but
5348 never modified, and then could be declared constants. The default is that
5349 such warnings are not given.
5350 This warning can also be turned on using @option{-gnatwa}.
5351
5352 @item -gnatwK
5353 @emph{Suppress warnings on variables that could be constants.}
5354 @cindex @option{-gnatwK} (@command{gcc})
5355 This switch disables warnings on variables that could be declared constants.
5356
5357 @item -gnatwl
5358 @emph{Activate warnings for elaboration pragmas.}
5359 @cindex @option{-gnatwl} (@command{gcc})
5360 @cindex Elaboration, warnings
5361 This switch activates warnings on missing
5362 @code{Elaborate_All} and @code{Elaborate} pragmas.
5363 See the section in this guide on elaboration checking for details on
5364 when such pragmas should be used. In dynamic elaboration mode, this switch
5365 generations warnings about the need to add elaboration pragmas. Note however,
5366 that if you blindly follow these warnings, and add @code{Elaborate_All}
5367 warnings wherever they are recommended, you basically end up with the
5368 equivalent of the static elaboration model, which may not be what you want for
5369 legacy code for which the static model does not work.
5370
5371 For the static model, the messages generated are labeled "info:" (for
5372 information messages). They are not warnings to add elaboration pragmas,
5373 merely informational messages showing what implicit elaboration pragmas
5374 have been added, for use in analyzing elaboration circularity problems.
5375
5376 Warnings are also generated if you
5377 are using the static mode of elaboration, and a @code{pragma Elaborate}
5378 is encountered. The default is that such warnings
5379 are not generated.
5380 This warning is not automatically turned on by the use of @option{-gnatwa}.
5381
5382 @item -gnatwL
5383 @emph{Suppress warnings for elaboration pragmas.}
5384 @cindex @option{-gnatwL} (@command{gcc})
5385 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5386 See the section in this guide on elaboration checking for details on
5387 when such pragmas should be used.
5388
5389 @item -gnatwm
5390 @emph{Activate warnings on modified but unreferenced variables.}
5391 @cindex @option{-gnatwm} (@command{gcc})
5392 This switch activates warnings for variables that are assigned (using
5393 an initialization value or with one or more assignment statements) but
5394 whose value is never read. The warning is suppressed for volatile
5395 variables and also for variables that are renamings of other variables
5396 or for which an address clause is given.
5397 This warning can also be turned on using @option{-gnatwa}.
5398 The default is that these warnings are not given.
5399
5400 @item -gnatwM
5401 @emph{Disable warnings on modified but unreferenced variables.}
5402 @cindex @option{-gnatwM} (@command{gcc})
5403 This switch disables warnings for variables that are assigned or
5404 initialized, but never read.
5405
5406 @item -gnatw.m
5407 @emph{Activate warnings on suspicious modulus values.}
5408 @cindex @option{-gnatw.m} (@command{gcc})
5409 This switch activates warnings for modulus values that seem suspicious.
5410 The cases caught are where the size is the same as the modulus (e.g.
5411 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5412 with no size clause. The guess in both cases is that 2**x was intended
5413 rather than x. The default is that these warnings are given.
5414
5415 @item -gnatw.M
5416 @emph{Disable warnings on suspicious modulus values.}
5417 @cindex @option{-gnatw.M} (@command{gcc})
5418 This switch disables warnings for suspicious modulus values.
5419
5420 @item -gnatwn
5421 @emph{Set normal warnings mode.}
5422 @cindex @option{-gnatwn} (@command{gcc})
5423 This switch sets normal warning mode, in which enabled warnings are
5424 issued and treated as warnings rather than errors. This is the default
5425 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5426 an explicit @option{-gnatws} or
5427 @option{-gnatwe}. It also cancels the effect of the
5428 implicit @option{-gnatwe} that is activated by the
5429 use of @option{-gnatg}.
5430
5431 @item -gnatwo
5432 @emph{Activate warnings on address clause overlays.}
5433 @cindex @option{-gnatwo} (@command{gcc})
5434 @cindex Address Clauses, warnings
5435 This switch activates warnings for possibly unintended initialization
5436 effects of defining address clauses that cause one variable to overlap
5437 another. The default is that such warnings are generated.
5438 This warning can also be turned on using @option{-gnatwa}.
5439
5440 @item -gnatwO
5441 @emph{Suppress warnings on address clause overlays.}
5442 @cindex @option{-gnatwO} (@command{gcc})
5443 This switch suppresses warnings on possibly unintended initialization
5444 effects of defining address clauses that cause one variable to overlap
5445 another.
5446
5447 @item -gnatw.o
5448 @emph{Activate warnings on modified but unreferenced out parameters.}
5449 @cindex @option{-gnatw.o} (@command{gcc})
5450 This switch activates warnings for variables that are modified by using
5451 them as actuals for a call to a procedure with an out mode formal, where
5452 the resulting assigned value is never read. It is applicable in the case
5453 where there is more than one out mode formal. If there is only one out
5454 mode formal, the warning is issued by default (controlled by -gnatwu).
5455 The warning is suppressed for volatile
5456 variables and also for variables that are renamings of other variables
5457 or for which an address clause is given.
5458 The default is that these warnings are not given. Note that this warning
5459 is not included in -gnatwa, it must be activated explicitly.
5460
5461 @item -gnatw.O
5462 @emph{Disable warnings on modified but unreferenced out parameters.}
5463 @cindex @option{-gnatw.O} (@command{gcc})
5464 This switch suppresses warnings for variables that are modified by using
5465 them as actuals for a call to a procedure with an out mode formal, where
5466 the resulting assigned value is never read.
5467
5468 @item -gnatwp
5469 @emph{Activate warnings on ineffective pragma Inlines.}
5470 @cindex @option{-gnatwp} (@command{gcc})
5471 @cindex Inlining, warnings
5472 This switch activates warnings for failure of front end inlining
5473 (activated by @option{-gnatN}) to inline a particular call. There are
5474 many reasons for not being able to inline a call, including most
5475 commonly that the call is too complex to inline. The default is
5476 that such warnings are not given.
5477 This warning can also be turned on using @option{-gnatwa}.
5478 Warnings on ineffective inlining by the gcc back-end can be activated
5479 separately, using the gcc switch -Winline.
5480
5481 @item -gnatwP
5482 @emph{Suppress warnings on ineffective pragma Inlines.}
5483 @cindex @option{-gnatwP} (@command{gcc})
5484 This switch suppresses warnings on ineffective pragma Inlines. If the
5485 inlining mechanism cannot inline a call, it will simply ignore the
5486 request silently.
5487
5488 @item -gnatw.p
5489 @emph{Activate warnings on parameter ordering.}
5490 @cindex @option{-gnatw.p} (@command{gcc})
5491 @cindex Parameter order, warnings
5492 This switch activates warnings for cases of suspicious parameter
5493 ordering when the list of arguments are all simple identifiers that
5494 match the names of the formals, but are in a different order. The
5495 warning is suppressed if any use of named parameter notation is used,
5496 so this is the appropriate way to suppress a false positive (and
5497 serves to emphasize that the "misordering" is deliberate). The
5498 default is
5499 that such warnings are not given.
5500 This warning can also be turned on using @option{-gnatwa}.
5501
5502 @item -gnatw.P
5503 @emph{Suppress warnings on parameter ordering.}
5504 @cindex @option{-gnatw.P} (@command{gcc})
5505 This switch suppresses warnings on cases of suspicious parameter
5506 ordering.
5507
5508 @item -gnatwq
5509 @emph{Activate warnings on questionable missing parentheses.}
5510 @cindex @option{-gnatwq} (@command{gcc})
5511 @cindex Parentheses, warnings
5512 This switch activates warnings for cases where parentheses are not used and
5513 the result is potential ambiguity from a readers point of view. For example
5514 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5515 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5516 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5517 follow the rule of always parenthesizing to make the association clear, and
5518 this warning switch warns if such parentheses are not present. The default
5519 is that these warnings are given.
5520 This warning can also be turned on using @option{-gnatwa}.
5521
5522 @item -gnatwQ
5523 @emph{Suppress warnings on questionable missing parentheses.}
5524 @cindex @option{-gnatwQ} (@command{gcc})
5525 This switch suppresses warnings for cases where the association is not
5526 clear and the use of parentheses is preferred.
5527
5528 @item -gnatwr
5529 @emph{Activate warnings on redundant constructs.}
5530 @cindex @option{-gnatwr} (@command{gcc})
5531 This switch activates warnings for redundant constructs. The following
5532 is the current list of constructs regarded as redundant:
5533
5534 @itemize @bullet
5535 @item
5536 Assignment of an item to itself.
5537 @item
5538 Type conversion that converts an expression to its own type.
5539 @item
5540 Use of the attribute @code{Base} where @code{typ'Base} is the same
5541 as @code{typ}.
5542 @item
5543 Use of pragma @code{Pack} when all components are placed by a record
5544 representation clause.
5545 @item
5546 Exception handler containing only a reraise statement (raise with no
5547 operand) which has no effect.
5548 @item
5549 Use of the operator abs on an operand that is known at compile time
5550 to be non-negative
5551 @item
5552 Comparison of boolean expressions to an explicit True value.
5553 @end itemize
5554
5555 This warning can also be turned on using @option{-gnatwa}.
5556 The default is that warnings for redundant constructs are not given.
5557
5558 @item -gnatwR
5559 @emph{Suppress warnings on redundant constructs.}
5560 @cindex @option{-gnatwR} (@command{gcc})
5561 This switch suppresses warnings for redundant constructs.
5562
5563 @item -gnatw.r
5564 @emph{Activate warnings for object renaming function.}
5565 @cindex @option{-gnatw.r} (@command{gcc})
5566 This switch activates warnings for an object renaming that renames a
5567 function call, which is equivalent to a constant declaration (as
5568 opposed to renaming the function itself).  The default is that these
5569 warnings are given.  This warning can also be turned on using
5570 @option{-gnatwa}.
5571
5572 @item -gnatw.R
5573 @emph{Suppress warnings for object renaming function.}
5574 @cindex @option{-gnatwT} (@command{gcc})
5575 This switch suppresses warnings for object renaming function.
5576
5577 @item -gnatws
5578 @emph{Suppress all warnings.}
5579 @cindex @option{-gnatws} (@command{gcc})
5580 This switch completely suppresses the
5581 output of all warning messages from the GNAT front end.
5582 Note that it does not suppress warnings from the @command{gcc} back end.
5583 To suppress these back end warnings as well, use the switch @option{-w}
5584 in addition to @option{-gnatws}.
5585
5586 @item -gnatwt
5587 @emph{Activate warnings for tracking of deleted conditional code.}
5588 @cindex @option{-gnatwt} (@command{gcc})
5589 @cindex Deactivated code, warnings
5590 @cindex Deleted code, warnings
5591 This switch activates warnings for tracking of code in conditionals (IF and
5592 CASE statements) that is detected to be dead code which cannot be executed, and
5593 which is removed by the front end. This warning is off by default, and is not
5594 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5595 useful for detecting deactivated code in certified applications.
5596
5597 @item -gnatwT
5598 @emph{Suppress warnings for tracking of deleted conditional code.}
5599 @cindex @option{-gnatwT} (@command{gcc})
5600 This switch suppresses warnings for tracking of deleted conditional code.
5601
5602 @item -gnatwu
5603 @emph{Activate warnings on unused entities.}
5604 @cindex @option{-gnatwu} (@command{gcc})
5605 This switch activates warnings to be generated for entities that
5606 are declared but not referenced, and for units that are @code{with}'ed
5607 and not
5608 referenced. In the case of packages, a warning is also generated if
5609 no entities in the package are referenced. This means that if the package
5610 is referenced but the only references are in @code{use}
5611 clauses or @code{renames}
5612 declarations, a warning is still generated. A warning is also generated
5613 for a generic package that is @code{with}'ed but never instantiated.
5614 In the case where a package or subprogram body is compiled, and there
5615 is a @code{with} on the corresponding spec
5616 that is only referenced in the body,
5617 a warning is also generated, noting that the
5618 @code{with} can be moved to the body. The default is that
5619 such warnings are not generated.
5620 This switch also activates warnings on unreferenced formals
5621 (it includes the effect of @option{-gnatwf}).
5622 This warning can also be turned on using @option{-gnatwa}.
5623
5624 @item -gnatwU
5625 @emph{Suppress warnings on unused entities.}
5626 @cindex @option{-gnatwU} (@command{gcc})
5627 This switch suppresses warnings for unused entities and packages.
5628 It also turns off warnings on unreferenced formals (and thus includes
5629 the effect of @option{-gnatwF}).
5630
5631 @item -gnatwv
5632 @emph{Activate warnings on unassigned variables.}
5633 @cindex @option{-gnatwv} (@command{gcc})
5634 @cindex Unassigned variable warnings
5635 This switch activates warnings for access to variables which
5636 may not be properly initialized. The default is that
5637 such warnings are generated.
5638 This warning can also be turned on using @option{-gnatwa}.
5639
5640 @item -gnatwV
5641 @emph{Suppress warnings on unassigned variables.}
5642 @cindex @option{-gnatwV} (@command{gcc})
5643 This switch suppresses warnings for access to variables which
5644 may not be properly initialized.
5645 For variables of a composite type, the warning can also be suppressed in
5646 Ada 2005 by using a default initialization with a box. For example, if
5647 Table is an array of records whose components are only partially uninitialized,
5648 then the following code:
5649
5650 @smallexample @c ada
5651    Tab : Table := (others => <>);
5652 @end smallexample
5653
5654 will suppress warnings on subsequent statements that access components
5655 of variable Tab.
5656
5657 @item -gnatww
5658 @emph{Activate warnings on wrong low bound assumption.}
5659 @cindex @option{-gnatww} (@command{gcc})
5660 @cindex String indexing warnings
5661 This switch activates warnings for indexing an unconstrained string parameter
5662 with a literal or S'Length. This is a case where the code is assuming that the
5663 low bound is one, which is in general not true (for example when a slice is
5664 passed). The default is that such warnings are generated.
5665 This warning can also be turned on using @option{-gnatwa}.
5666
5667 @item -gnatwW
5668 @emph{Suppress warnings on wrong low bound assumption.}
5669 @cindex @option{-gnatwW} (@command{gcc})
5670 This switch suppresses warnings for indexing an unconstrained string parameter
5671 with a literal or S'Length. Note that this warning can also be suppressed
5672 in a particular case by adding an
5673 assertion that the lower bound is 1,
5674 as shown in the following example.
5675
5676 @smallexample @c ada
5677    procedure K (S : String) is
5678       pragma Assert (S'First = 1);
5679       @dots{}
5680 @end smallexample
5681
5682 @item -gnatw.w
5683 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5684 @cindex @option{-gnatw.w} (@command{gcc})
5685 @cindex Warnings Off control
5686 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5687 where either the pragma is entirely useless (because it suppresses no
5688 warnings), or it could be replaced by @code{pragma Unreferenced} or
5689 @code{pragma Unmodified}.The default is that these warnings are not given.
5690 Note that this warning is not included in -gnatwa, it must be
5691 activated explicitly.
5692
5693 @item -gnatw.W
5694 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5695 @cindex @option{-gnatw.W} (@command{gcc})
5696 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5697
5698 @item -gnatwx
5699 @emph{Activate warnings on Export/Import pragmas.}
5700 @cindex @option{-gnatwx} (@command{gcc})
5701 @cindex Export/Import pragma warnings
5702 This switch activates warnings on Export/Import pragmas when
5703 the compiler detects a possible conflict between the Ada and
5704 foreign language calling sequences. For example, the use of
5705 default parameters in a convention C procedure is dubious
5706 because the C compiler cannot supply the proper default, so
5707 a warning is issued. The default is that such warnings are
5708 generated.
5709 This warning can also be turned on using @option{-gnatwa}.
5710
5711 @item -gnatwX
5712 @emph{Suppress warnings on Export/Import pragmas.}
5713 @cindex @option{-gnatwX} (@command{gcc})
5714 This switch suppresses warnings on Export/Import pragmas.
5715 The sense of this is that you are telling the compiler that
5716 you know what you are doing in writing the pragma, and it
5717 should not complain at you.
5718
5719 @item -gnatw.x
5720 @emph{Activate warnings for No_Exception_Propagation mode.}
5721 @cindex @option{-gnatwm} (@command{gcc})
5722 This switch activates warnings for exception usage when pragma Restrictions
5723 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5724 explicit exception raises which are not covered by a local handler, and for
5725 exception handlers which do not cover a local raise. The default is that these
5726 warnings are not given.
5727
5728 @item -gnatw.X
5729 @emph{Disable warnings for No_Exception_Propagation mode.}
5730 This switch disables warnings for exception usage when pragma Restrictions
5731 (No_Exception_Propagation) is in effect.
5732
5733 @item -gnatwy
5734 @emph{Activate warnings for Ada 2005 compatibility issues.}
5735 @cindex @option{-gnatwy} (@command{gcc})
5736 @cindex Ada 2005 compatibility issues warnings
5737 For the most part Ada 2005 is upwards compatible with Ada 95,
5738 but there are some exceptions (for example the fact that
5739 @code{interface} is now a reserved word in Ada 2005). This
5740 switch activates several warnings to help in identifying
5741 and correcting such incompatibilities. The default is that
5742 these warnings are generated. Note that at one point Ada 2005
5743 was called Ada 0Y, hence the choice of character.
5744 This warning can also be turned on using @option{-gnatwa}.
5745
5746 @item -gnatwY
5747 @emph{Disable warnings for Ada 2005 compatibility issues.}
5748 @cindex @option{-gnatwY} (@command{gcc})
5749 @cindex Ada 2005 compatibility issues warnings
5750 This switch suppresses several warnings intended to help in identifying
5751 incompatibilities between Ada 95 and Ada 2005.
5752
5753 @item -gnatwz
5754 @emph{Activate warnings on unchecked conversions.}
5755 @cindex @option{-gnatwz} (@command{gcc})
5756 @cindex Unchecked_Conversion warnings
5757 This switch activates warnings for unchecked conversions
5758 where the types are known at compile time to have different
5759 sizes. The default
5760 is that such warnings are generated. Warnings are also
5761 generated for subprogram pointers with different conventions,
5762 and, on VMS only, for data pointers with different conventions.
5763 This warning can also be turned on using @option{-gnatwa}.
5764
5765 @item -gnatwZ
5766 @emph{Suppress warnings on unchecked conversions.}
5767 @cindex @option{-gnatwZ} (@command{gcc})
5768 This switch suppresses warnings for unchecked conversions
5769 where the types are known at compile time to have different
5770 sizes or conventions.
5771
5772 @item ^-Wunused^WARNINGS=UNUSED^
5773 @cindex @option{-Wunused}
5774 The warnings controlled by the @option{-gnatw} switch are generated by
5775 the front end of the compiler. The @option{GCC} back end can provide
5776 additional warnings and they are controlled by the @option{-W} switch.
5777 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5778 warnings for entities that are declared but not referenced.
5779
5780 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5781 @cindex @option{-Wuninitialized}
5782 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5783 the back end warning for uninitialized variables. This switch must be
5784 used in conjunction with an optimization level greater than zero.
5785
5786 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5787 @cindex @option{-Wall}
5788 This switch enables all the above warnings from the @option{GCC} back end.
5789 The code generator detects a number of warning situations that are missed
5790 by the @option{GNAT} front end, and this switch can be used to activate them.
5791 The use of this switch also sets the default front end warning mode to
5792 @option{-gnatwa}, that is, most front end warnings activated as well.
5793
5794 @item ^-w^/NO_BACK_END_WARNINGS^
5795 @cindex @option{-w}
5796 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5797 The use of this switch also sets the default front end warning mode to
5798 @option{-gnatws}, that is, front end warnings suppressed as well.
5799
5800 @end table
5801
5802 @noindent
5803 @ifclear vms
5804 A string of warning parameters can be used in the same parameter. For example:
5805
5806 @smallexample
5807 -gnatwaLe
5808 @end smallexample
5809
5810 @noindent
5811 will turn on all optional warnings except for elaboration pragma warnings,
5812 and also specify that warnings should be treated as errors.
5813 @end ifclear
5814 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5815
5816 @table @option
5817 @c !sort!
5818 @item -gnatwC
5819 @item -gnatwD
5820 @item -gnatwF
5821 @item -gnatwg
5822 @item -gnatwH
5823 @item -gnatwi
5824 @item -gnatwJ
5825 @item -gnatwK
5826 @item -gnatwL
5827 @item -gnatwM
5828 @item -gnatwn
5829 @item -gnatwo
5830 @item -gnatwP
5831 @item -gnatwR
5832 @item -gnatwU
5833 @item -gnatwv
5834 @item -gnatwz
5835 @item -gnatwx
5836
5837 @end table
5838
5839 @node Debugging and Assertion Control
5840 @subsection Debugging and Assertion Control
5841
5842 @table @option
5843 @item -gnata
5844 @cindex @option{-gnata} (@command{gcc})
5845 @findex Assert
5846 @findex Debug
5847 @cindex Assertions
5848
5849 @noindent
5850 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5851 are ignored. This switch, where @samp{a} stands for assert, causes
5852 @code{Assert} and @code{Debug} pragmas to be activated.
5853
5854 The pragmas have the form:
5855
5856 @smallexample
5857 @cartouche
5858    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5859                       @var{static-string-expression}@r{]})
5860    @b{pragma} Debug (@var{procedure call})
5861 @end cartouche
5862 @end smallexample
5863
5864 @noindent
5865 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5866 If the result is @code{True}, the pragma has no effect (other than
5867 possible side effects from evaluating the expression). If the result is
5868 @code{False}, the exception @code{Assert_Failure} declared in the package
5869 @code{System.Assertions} is
5870 raised (passing @var{static-string-expression}, if present, as the
5871 message associated with the exception). If no string expression is
5872 given the default is a string giving the file name and line number
5873 of the pragma.
5874
5875 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5876 @code{pragma Debug} may appear within a declaration sequence, allowing
5877 debugging procedures to be called between declarations.
5878
5879 @ifset vms
5880 @item /DEBUG@r{[}=debug-level@r{]}
5881 @itemx  /NODEBUG
5882 Specifies how much debugging information is to be included in
5883 the resulting object file where 'debug-level' is one of the following:
5884 @table @code
5885 @item   TRACEBACK
5886 Include both debugger symbol records and traceback
5887 the object file.
5888 This is the default setting.
5889 @item   ALL
5890 Include both debugger symbol records and traceback in
5891 object file.
5892 @item   NONE
5893 Excludes both debugger symbol records and traceback
5894 the object file. Same as /NODEBUG.
5895 @item   SYMBOLS
5896 Includes only debugger symbol records in the object
5897 file. Note that this doesn't include traceback information.
5898 @end table
5899 @end ifset
5900 @end table
5901
5902 @node Validity Checking
5903 @subsection Validity Checking
5904 @findex Validity Checking
5905
5906 @noindent
5907 The Ada Reference Manual defines the concept of invalid values (see
5908 RM 13.9.1). The primary source of invalid values is uninitialized
5909 variables. A scalar variable that is left uninitialized may contain
5910 an invalid value; the concept of invalid does not apply to access or
5911 composite types.
5912
5913 It is an error to read an invalid value, but the RM does not require
5914 run-time checks to detect such errors, except for some minimal
5915 checking to prevent erroneous execution (i.e. unpredictable
5916 behavior). This corresponds to the @option{-gnatVd} switch below,
5917 which is the default. For example, by default, if the expression of a
5918 case statement is invalid, it will raise Constraint_Error rather than
5919 causing a wild jump, and if an array index on the left-hand side of an
5920 assignment is invalid, it will raise Constraint_Error rather than
5921 overwriting an arbitrary memory location.
5922
5923 The @option{-gnatVa} may be used to enable additional validity checks,
5924 which are not required by the RM. These checks are often very
5925 expensive (which is why the RM does not require them). These checks
5926 are useful in tracking down uninitialized variables, but they are
5927 not usually recommended for production builds.
5928
5929 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5930 control; you can enable whichever validity checks you desire. However,
5931 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5932 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5933 sufficient for non-debugging use.
5934
5935 The @option{-gnatB} switch tells the compiler to assume that all
5936 values are valid (that is, within their declared subtype range)
5937 except in the context of a use of the Valid attribute. This means
5938 the compiler can generate more efficient code, since the range
5939 of values is better known at compile time. However, an uninitialized
5940 variable can cause wild jumps and memory corruption in this mode.
5941
5942 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5943 checking mode as described below.
5944 @ifclear vms
5945 The @code{x} argument is a string of letters that
5946 indicate validity checks that are performed or not performed in addition
5947 to the default checks required by Ada as described above.
5948 @end ifclear
5949 @ifset vms
5950 The options allowed for this qualifier
5951 indicate validity checks that are performed or not performed in addition
5952 to the default checks required by Ada as described above.
5953 @end ifset
5954
5955 @table @option
5956 @c !sort!
5957 @item -gnatVa
5958 @emph{All validity checks.}
5959 @cindex @option{-gnatVa} (@command{gcc})
5960 All validity checks are turned on.
5961 @ifclear vms
5962 That is, @option{-gnatVa} is
5963 equivalent to @option{gnatVcdfimorst}.
5964 @end ifclear
5965
5966 @item -gnatVc
5967 @emph{Validity checks for copies.}
5968 @cindex @option{-gnatVc} (@command{gcc})
5969 The right hand side of assignments, and the initializing values of
5970 object declarations are validity checked.
5971
5972 @item -gnatVd
5973 @emph{Default (RM) validity checks.}
5974 @cindex @option{-gnatVd} (@command{gcc})
5975 Some validity checks are done by default following normal Ada semantics
5976 (RM 13.9.1 (9-11)).
5977 A check is done in case statements that the expression is within the range
5978 of the subtype. If it is not, Constraint_Error is raised.
5979 For assignments to array components, a check is done that the expression used
5980 as index is within the range. If it is not, Constraint_Error is raised.
5981 Both these validity checks may be turned off using switch @option{-gnatVD}.
5982 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5983 switch @option{-gnatVd} will leave the checks turned on.
5984 Switch @option{-gnatVD} should be used only if you are sure that all such
5985 expressions have valid values. If you use this switch and invalid values
5986 are present, then the program is erroneous, and wild jumps or memory
5987 overwriting may occur.
5988
5989 @item -gnatVe
5990 @emph{Validity checks for elementary components.}
5991 @cindex @option{-gnatVe} (@command{gcc})
5992 In the absence of this switch, assignments to record or array components are
5993 not validity checked, even if validity checks for assignments generally
5994 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5995 require valid data, but assignment of individual components does. So for
5996 example, there is a difference between copying the elements of an array with a
5997 slice assignment, compared to assigning element by element in a loop. This
5998 switch allows you to turn off validity checking for components, even when they
5999 are assigned component by component.
6000
6001 @item -gnatVf
6002 @emph{Validity checks for floating-point values.}
6003 @cindex @option{-gnatVf} (@command{gcc})
6004 In the absence of this switch, validity checking occurs only for discrete
6005 values. If @option{-gnatVf} is specified, then validity checking also applies
6006 for floating-point values, and NaNs and infinities are considered invalid,
6007 as well as out of range values for constrained types. Note that this means
6008 that standard IEEE infinity mode is not allowed. The exact contexts
6009 in which floating-point values are checked depends on the setting of other
6010 options. For example,
6011 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6012 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6013 (the order does not matter) specifies that floating-point parameters of mode
6014 @code{in} should be validity checked.
6015
6016 @item -gnatVi
6017 @emph{Validity checks for @code{in} mode parameters}
6018 @cindex @option{-gnatVi} (@command{gcc})
6019 Arguments for parameters of mode @code{in} are validity checked in function
6020 and procedure calls at the point of call.
6021
6022 @item -gnatVm
6023 @emph{Validity checks for @code{in out} mode parameters.}
6024 @cindex @option{-gnatVm} (@command{gcc})
6025 Arguments for parameters of mode @code{in out} are validity checked in
6026 procedure calls at the point of call. The @code{'m'} here stands for
6027 modify, since this concerns parameters that can be modified by the call.
6028 Note that there is no specific option to test @code{out} parameters,
6029 but any reference within the subprogram will be tested in the usual
6030 manner, and if an invalid value is copied back, any reference to it
6031 will be subject to validity checking.
6032
6033 @item -gnatVn
6034 @emph{No validity checks.}
6035 @cindex @option{-gnatVn} (@command{gcc})
6036 This switch turns off all validity checking, including the default checking
6037 for case statements and left hand side subscripts. Note that the use of
6038 the switch @option{-gnatp} suppresses all run-time checks, including
6039 validity checks, and thus implies @option{-gnatVn}. When this switch
6040 is used, it cancels any other @option{-gnatV} previously issued.
6041
6042 @item -gnatVo
6043 @emph{Validity checks for operator and attribute operands.}
6044 @cindex @option{-gnatVo} (@command{gcc})
6045 Arguments for predefined operators and attributes are validity checked.
6046 This includes all operators in package @code{Standard},
6047 the shift operators defined as intrinsic in package @code{Interfaces}
6048 and operands for attributes such as @code{Pos}. Checks are also made
6049 on individual component values for composite comparisons, and on the
6050 expressions in type conversions and qualified expressions. Checks are
6051 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6052
6053 @item -gnatVp
6054 @emph{Validity checks for parameters.}
6055 @cindex @option{-gnatVp} (@command{gcc})
6056 This controls the treatment of parameters within a subprogram (as opposed
6057 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6058 of parameters on a call. If either of these call options is used, then
6059 normally an assumption is made within a subprogram that the input arguments
6060 have been validity checking at the point of call, and do not need checking
6061 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6062 is not made, and parameters are not assumed to be valid, so their validity
6063 will be checked (or rechecked) within the subprogram.
6064
6065 @item -gnatVr
6066 @emph{Validity checks for function returns.}
6067 @cindex @option{-gnatVr} (@command{gcc})
6068 The expression in @code{return} statements in functions is validity
6069 checked.
6070
6071 @item -gnatVs
6072 @emph{Validity checks for subscripts.}
6073 @cindex @option{-gnatVs} (@command{gcc})
6074 All subscripts expressions are checked for validity, whether they appear
6075 on the right side or left side (in default mode only left side subscripts
6076 are validity checked).
6077
6078 @item -gnatVt
6079 @emph{Validity checks for tests.}
6080 @cindex @option{-gnatVt} (@command{gcc})
6081 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6082 statements are checked, as well as guard expressions in entry calls.
6083
6084 @end table
6085
6086 @noindent
6087 The @option{-gnatV} switch may be followed by
6088 ^a string of letters^a list of options^
6089 to turn on a series of validity checking options.
6090 For example,
6091 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6092 specifies that in addition to the default validity checking, copies and
6093 function return expressions are to be validity checked.
6094 In order to make it easier
6095 to specify the desired combination of effects,
6096 @ifclear vms
6097 the upper case letters @code{CDFIMORST} may
6098 be used to turn off the corresponding lower case option.
6099 @end ifclear
6100 @ifset vms
6101 the prefix @code{NO} on an option turns off the corresponding validity
6102 checking:
6103 @itemize @bullet
6104 @item @code{NOCOPIES}
6105 @item @code{NODEFAULT}
6106 @item @code{NOFLOATS}
6107 @item @code{NOIN_PARAMS}
6108 @item @code{NOMOD_PARAMS}
6109 @item @code{NOOPERANDS}
6110 @item @code{NORETURNS}
6111 @item @code{NOSUBSCRIPTS}
6112 @item @code{NOTESTS}
6113 @end itemize
6114 @end ifset
6115 Thus
6116 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6117 turns on all validity checking options except for
6118 checking of @code{@b{in out}} procedure arguments.
6119
6120 The specification of additional validity checking generates extra code (and
6121 in the case of @option{-gnatVa} the code expansion can be substantial).
6122 However, these additional checks can be very useful in detecting
6123 uninitialized variables, incorrect use of unchecked conversion, and other
6124 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6125 is useful in conjunction with the extra validity checking, since this
6126 ensures that wherever possible uninitialized variables have invalid values.
6127
6128 See also the pragma @code{Validity_Checks} which allows modification of
6129 the validity checking mode at the program source level, and also allows for
6130 temporary disabling of validity checks.
6131
6132 @node Style Checking
6133 @subsection Style Checking
6134 @findex Style checking
6135
6136 @noindent
6137 The @option{-gnaty^x^(option,option,@dots{})^} switch
6138 @cindex @option{-gnaty} (@command{gcc})
6139 causes the compiler to
6140 enforce specified style rules. A limited set of style rules has been used
6141 in writing the GNAT sources themselves. This switch allows user programs
6142 to activate all or some of these checks. If the source program fails a
6143 specified style check, an appropriate warning message is given, preceded by
6144 the character sequence ``(style)''.
6145 @ifset vms
6146 @code{(option,option,@dots{})} is a sequence of keywords
6147 @end ifset
6148 @ifclear vms
6149 The string @var{x} is a sequence of letters or digits
6150 @end ifclear
6151 indicating the particular style
6152 checks to be performed. The following checks are defined:
6153
6154 @table @option
6155 @c !sort!
6156 @item 0-9
6157 @emph{Specify indentation level.}
6158 If a digit from 1-9 appears
6159 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6160 then proper indentation is checked, with the digit indicating the
6161 indentation level required. A value of zero turns off this style check.
6162 The general style of required indentation is as specified by
6163 the examples in the Ada Reference Manual. Full line comments must be
6164 aligned with the @code{--} starting on a column that is a multiple of
6165 the alignment level, or they may be aligned the same way as the following
6166 non-blank line (this is useful when full line comments appear in the middle
6167 of a statement.
6168
6169 @item ^a^ATTRIBUTE^
6170 @emph{Check attribute casing.}
6171 Attribute names, including the case of keywords such as @code{digits}
6172 used as attributes names, must be written in mixed case, that is, the
6173 initial letter and any letter following an underscore must be uppercase.
6174 All other letters must be lowercase.
6175
6176 @item ^A^ARRAY_INDEXES^
6177 @emph{Use of array index numbers in array attributes.}
6178 When using the array attributes First, Last, Range,
6179 or Length, the index number must be omitted for one-dimensional arrays
6180 and is required for multi-dimensional arrays.
6181
6182 @item ^b^BLANKS^
6183 @emph{Blanks not allowed at statement end.}
6184 Trailing blanks are not allowed at the end of statements. The purpose of this
6185 rule, together with h (no horizontal tabs), is to enforce a canonical format
6186 for the use of blanks to separate source tokens.
6187
6188 @item ^B^BOOLEAN_OPERATORS^
6189 @emph{Check Boolean operators.}
6190 The use of AND/OR operators is not permitted except in the cases of modular
6191 operands, array operands, and simple stand-alone boolean variables or
6192 boolean constants. In all other cases AND THEN/OR ELSE are required.
6193
6194 @item ^c^COMMENTS^
6195 @emph{Check comments.}
6196 Comments must meet the following set of rules:
6197
6198 @itemize @bullet
6199
6200 @item
6201 The ``@code{--}'' that starts the column must either start in column one,
6202 or else at least one blank must precede this sequence.
6203
6204 @item
6205 Comments that follow other tokens on a line must have at least one blank
6206 following the ``@code{--}'' at the start of the comment.
6207
6208 @item
6209 Full line comments must have two blanks following the ``@code{--}'' that
6210 starts the comment, with the following exceptions.
6211
6212 @item
6213 A line consisting only of the ``@code{--}'' characters, possibly preceded
6214 by blanks is permitted.
6215
6216 @item
6217 A comment starting with ``@code{--x}'' where @code{x} is a special character
6218 is permitted.
6219 This allows proper processing of the output generated by specialized tools
6220 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6221 annotation
6222 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6223 special character is defined as being in one of the ASCII ranges
6224 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6225 Note that this usage is not permitted
6226 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6227
6228 @item
6229 A line consisting entirely of minus signs, possibly preceded by blanks, is
6230 permitted. This allows the construction of box comments where lines of minus
6231 signs are used to form the top and bottom of the box.
6232
6233 @item
6234 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6235 least one blank follows the initial ``@code{--}''. Together with the preceding
6236 rule, this allows the construction of box comments, as shown in the following
6237 example:
6238 @smallexample
6239 ---------------------------
6240 -- This is a box comment --
6241 -- with two text lines.  --
6242 ---------------------------
6243 @end smallexample
6244 @end itemize
6245
6246 @item ^d^DOS_LINE_ENDINGS^
6247 @emph{Check no DOS line terminators present.}
6248 All lines must be terminated by a single ASCII.LF
6249 character (in particular the DOS line terminator sequence CR/LF is not
6250 allowed).
6251
6252 @item ^e^END^
6253 @emph{Check end/exit labels.}
6254 Optional labels on @code{end} statements ending subprograms and on
6255 @code{exit} statements exiting named loops, are required to be present.
6256
6257 @item ^f^VTABS^
6258 @emph{No form feeds or vertical tabs.}
6259 Neither form feeds nor vertical tab characters are permitted
6260 in the source text.
6261
6262 @item ^g^GNAT^
6263 @emph{GNAT style mode}
6264 The set of style check switches is set to match that used by the GNAT sources.
6265 This may be useful when developing code that is eventually intended to be
6266 incorporated into GNAT. For further details, see GNAT sources.
6267
6268 @item ^h^HTABS^
6269 @emph{No horizontal tabs.}
6270 Horizontal tab characters are not permitted in the source text.
6271 Together with the b (no blanks at end of line) check, this
6272 enforces a canonical form for the use of blanks to separate
6273 source tokens.
6274
6275 @item ^i^IF_THEN^
6276 @emph{Check if-then layout.}
6277 The keyword @code{then} must appear either on the same
6278 line as corresponding @code{if}, or on a line on its own, lined
6279 up under the @code{if} with at least one non-blank line in between
6280 containing all or part of the condition to be tested.
6281
6282 @item ^I^IN_MODE^
6283 @emph{check mode IN keywords}
6284 Mode @code{in} (the default mode) is not
6285 allowed to be given explicitly. @code{in out} is fine,
6286 but not @code{in} on its own.
6287
6288 @item ^k^KEYWORD^
6289 @emph{Check keyword casing.}
6290 All keywords must be in lower case (with the exception of keywords
6291 such as @code{digits} used as attribute names to which this check
6292 does not apply).
6293
6294 @item ^l^LAYOUT^
6295 @emph{Check layout.}
6296 Layout of statement and declaration constructs must follow the
6297 recommendations in the Ada Reference Manual, as indicated by the
6298 form of the syntax rules. For example an @code{else} keyword must
6299 be lined up with the corresponding @code{if} keyword.
6300
6301 There are two respects in which the style rule enforced by this check
6302 option are more liberal than those in the Ada Reference Manual. First
6303 in the case of record declarations, it is permissible to put the
6304 @code{record} keyword on the same line as the @code{type} keyword, and
6305 then the @code{end} in @code{end record} must line up under @code{type}.
6306 This is also permitted when the type declaration is split on two lines.
6307 For example, any of the following three layouts is acceptable:
6308
6309 @smallexample @c ada
6310 @cartouche
6311 type q is record
6312    a : integer;
6313    b : integer;
6314 end record;
6315
6316 type q is
6317    record
6318       a : integer;
6319       b : integer;
6320    end record;
6321
6322 type q is
6323    record
6324       a : integer;
6325       b : integer;
6326 end record;
6327
6328 @end cartouche
6329 @end smallexample
6330
6331 @noindent
6332 Second, in the case of a block statement, a permitted alternative
6333 is to put the block label on the same line as the @code{declare} or
6334 @code{begin} keyword, and then line the @code{end} keyword up under
6335 the block label. For example both the following are permitted:
6336
6337 @smallexample @c ada
6338 @cartouche
6339 Block : declare
6340    A : Integer := 3;
6341 begin
6342    Proc (A, A);
6343 end Block;
6344
6345 Block :
6346    declare
6347       A : Integer := 3;
6348    begin
6349       Proc (A, A);
6350    end Block;
6351 @end cartouche
6352 @end smallexample
6353
6354 @noindent
6355 The same alternative format is allowed for loops. For example, both of
6356 the following are permitted:
6357
6358 @smallexample @c ada
6359 @cartouche
6360 Clear : while J < 10 loop
6361    A (J) := 0;
6362 end loop Clear;
6363
6364 Clear :
6365    while J < 10 loop
6366       A (J) := 0;
6367    end loop Clear;
6368 @end cartouche
6369 @end smallexample
6370
6371 @item ^Lnnn^MAX_NESTING=nnn^
6372 @emph{Set maximum nesting level}
6373 The maximum level of nesting of constructs (including subprograms, loops,
6374 blocks, packages, and conditionals) may not exceed the given value
6375 @option{nnn}. A value of zero disconnects this style check.
6376
6377 @item ^m^LINE_LENGTH^
6378 @emph{Check maximum line length.}
6379 The length of source lines must not exceed 79 characters, including
6380 any trailing blanks. The value of 79 allows convenient display on an
6381 80 character wide device or window, allowing for possible special
6382 treatment of 80 character lines. Note that this count is of
6383 characters in the source text. This means that a tab character counts
6384 as one character in this count but a wide character sequence counts as
6385 a single character (however many bytes are needed in the encoding).
6386
6387 @item ^Mnnn^MAX_LENGTH=nnn^
6388 @emph{Set maximum line length.}
6389 The length of lines must not exceed the
6390 given value @option{nnn}. The maximum value that can be specified is 32767.
6391
6392 @item ^n^STANDARD_CASING^
6393 @emph{Check casing of entities in Standard.}
6394 Any identifier from Standard must be cased
6395 to match the presentation in the Ada Reference Manual (for example,
6396 @code{Integer} and @code{ASCII.NUL}).
6397
6398 @item ^N^NONE^
6399 @emph{Turn off all style checks}
6400 All style check options are turned off.
6401
6402 @item ^o^ORDERED_SUBPROGRAMS^
6403 @emph{Check order of subprogram bodies.}
6404 All subprogram bodies in a given scope
6405 (e.g.@: a package body) must be in alphabetical order. The ordering
6406 rule uses normal Ada rules for comparing strings, ignoring casing
6407 of letters, except that if there is a trailing numeric suffix, then
6408 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6409 before Junk10).
6410
6411 @item ^O^OVERRIDING_INDICATORS^
6412 @emph{Check that overriding subprograms are explicitly marked as such.}
6413 The declaration of a primitive operation of a type extension that overrides
6414 an inherited operation must carry an overriding indicator.
6415
6416 @item ^p^PRAGMA^
6417 @emph{Check pragma casing.}
6418 Pragma names must be written in mixed case, that is, the
6419 initial letter and any letter following an underscore must be uppercase.
6420 All other letters must be lowercase.
6421
6422 @item ^r^REFERENCES^
6423 @emph{Check references.}
6424 All identifier references must be cased in the same way as the
6425 corresponding declaration. No specific casing style is imposed on
6426 identifiers. The only requirement is for consistency of references
6427 with declarations.
6428
6429 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6430 @emph{Check no statements after THEN/ELSE.}
6431 No statements are allowed
6432 on the same line as a THEN or ELSE keyword following the
6433 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6434 and a special exception allows a pragma to appear after ELSE.
6435
6436 @item ^s^SPECS^
6437 @emph{Check separate specs.}
6438 Separate declarations (``specs'') are required for subprograms (a
6439 body is not allowed to serve as its own declaration). The only
6440 exception is that parameterless library level procedures are
6441 not required to have a separate declaration. This exception covers
6442 the most frequent form of main program procedures.
6443
6444 @item ^t^TOKEN^
6445 @emph{Check token spacing.}
6446 The following token spacing rules are enforced:
6447
6448 @itemize @bullet
6449
6450 @item
6451 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6452
6453 @item
6454 The token @code{=>} must be surrounded by spaces.
6455
6456 @item
6457 The token @code{<>} must be preceded by a space or a left parenthesis.
6458
6459 @item
6460 Binary operators other than @code{**} must be surrounded by spaces.
6461 There is no restriction on the layout of the @code{**} binary operator.
6462
6463 @item
6464 Colon must be surrounded by spaces.
6465
6466 @item
6467 Colon-equal (assignment, initialization) must be surrounded by spaces.
6468
6469 @item
6470 Comma must be the first non-blank character on the line, or be
6471 immediately preceded by a non-blank character, and must be followed
6472 by a space.
6473
6474 @item
6475 If the token preceding a left parenthesis ends with a letter or digit, then
6476 a space must separate the two tokens.
6477
6478 @item
6479 if the token following a right parenthesis starts with a letter or digit, then
6480 a space must separate the two tokens.
6481
6482 @item
6483 A right parenthesis must either be the first non-blank character on
6484 a line, or it must be preceded by a non-blank character.
6485
6486 @item
6487 A semicolon must not be preceded by a space, and must not be followed by
6488 a non-blank character.
6489
6490 @item
6491 A unary plus or minus may not be followed by a space.
6492
6493 @item
6494 A vertical bar must be surrounded by spaces.
6495 @end itemize
6496
6497 @item ^u^UNNECESSARY_BLANK_LINES^
6498 @emph{Check unnecessary blank lines.}
6499 Unnecessary blank lines are not allowed. A blank line is considered
6500 unnecessary if it appears at the end of the file, or if more than
6501 one blank line occurs in sequence.
6502
6503 @item ^x^XTRA_PARENS^
6504 @emph{Check extra parentheses.}
6505 Unnecessary extra level of parentheses (C-style) are not allowed
6506 around conditions in @code{if} statements, @code{while} statements and
6507 @code{exit} statements.
6508
6509 @item ^y^ALL_BUILTIN^
6510 @emph{Set all standard style check options}
6511 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6512 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6513 @option{-gnatyS}, @option{-gnatyLnnn},
6514 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6515
6516 @ifclear vms
6517 @item -
6518 @emph{Remove style check options}
6519 This causes any subsequent options in the string to act as canceling the
6520 corresponding style check option. To cancel maximum nesting level control,
6521 use @option{L} parameter witout any integer value after that, because any
6522 digit following @option{-} in the parameter string of the @option{-gnaty}
6523 option will be threated as canceling indentation check. The same is true
6524 for @option{M} parameter. @option{y} and @option{N} parameters are not
6525 allowed after @option{-}.
6526
6527 @item +
6528 This causes any subsequent options in the string to enable the corresponding
6529 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6530 if any.
6531 @end ifclear
6532
6533 @ifset vms
6534 @item NOxxx
6535 @emph{Removing style check options}
6536 If the name of a style check is preceded by @option{NO} then the corresponding
6537 style check is turned off. For example @option{NOCOMMENTS} turns off style
6538 checking for comments.
6539 @end ifset
6540 @end table
6541
6542 @noindent
6543 In the above rules, appearing in column one is always permitted, that is,
6544 counts as meeting either a requirement for a required preceding space,
6545 or as meeting a requirement for no preceding space.
6546
6547 Appearing at the end of a line is also always permitted, that is, counts
6548 as meeting either a requirement for a following space, or as meeting
6549 a requirement for no following space.
6550
6551 @noindent
6552 If any of these style rules is violated, a message is generated giving
6553 details on the violation. The initial characters of such messages are
6554 always ``@code{(style)}''. Note that these messages are treated as warning
6555 messages, so they normally do not prevent the generation of an object
6556 file. The @option{-gnatwe} switch can be used to treat warning messages,
6557 including style messages, as fatal errors.
6558
6559 The switch
6560 @ifclear vms
6561 @option{-gnaty} on its own (that is not
6562 followed by any letters or digits), then the effect is equivalent
6563 to the use of @option{-gnatyy}, as described above, that is all
6564 built-in standard style check options are enabled.
6565
6566 @end ifclear
6567 @ifset vms
6568 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6569 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6570 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6571 @end ifset
6572
6573 The switch
6574 @ifclear vms
6575 @option{-gnatyN}
6576 @end ifclear
6577 @ifset vms
6578 /STYLE_CHECKS=NONE
6579 @end ifset
6580 clears any previously set style checks.
6581
6582 @node Run-Time Checks
6583 @subsection Run-Time Checks
6584 @cindex Division by zero
6585 @cindex Access before elaboration
6586 @cindex Checks, division by zero
6587 @cindex Checks, access before elaboration
6588 @cindex Checks, stack overflow checking
6589
6590 @noindent
6591 By default, the following checks are suppressed: integer overflow
6592 checks, stack overflow checks, and checks for access before
6593 elaboration on subprogram calls. All other checks, including range
6594 checks and array bounds checks, are turned on by default. The
6595 following @command{gcc} switches refine this default behavior.
6596
6597 @table @option
6598 @c !sort!
6599 @item -gnatp
6600 @cindex @option{-gnatp} (@command{gcc})
6601 @cindex Suppressing checks
6602 @cindex Checks, suppressing
6603 @findex Suppress
6604 This switch causes the unit to be compiled
6605 as though @code{pragma Suppress (All_checks)}
6606 had been present in the source. Validity checks are also eliminated (in
6607 other words @option{-gnatp} also implies @option{-gnatVn}.
6608 Use this switch to improve the performance
6609 of the code at the expense of safety in the presence of invalid data or
6610 program bugs.
6611
6612 Note that when checks are suppressed, the compiler is allowed, but not
6613 required, to omit the checking code. If the run-time cost of the
6614 checking code is zero or near-zero, the compiler will generate it even
6615 if checks are suppressed. In particular, if the compiler can prove
6616 that a certain check will necessarily fail, it will generate code to
6617 do an unconditional ``raise'', even if checks are suppressed. The
6618 compiler warns in this case. Another case in which checks may not be
6619 eliminated is when they are embedded in certain run time routines such
6620 as math library routines.
6621
6622 Of course, run-time checks are omitted whenever the compiler can prove
6623 that they will not fail, whether or not checks are suppressed.
6624
6625 Note that if you suppress a check that would have failed, program
6626 execution is erroneous, which means the behavior is totally
6627 unpredictable. The program might crash, or print wrong answers, or
6628 do anything else. It might even do exactly what you wanted it to do
6629 (and then it might start failing mysteriously next week or next
6630 year). The compiler will generate code based on the assumption that
6631 the condition being checked is true, which can result in disaster if
6632 that assumption is wrong.
6633
6634 The @option{-gnatp} switch has no effect if a subsequent
6635 @option{-gnat-p} switch appears.
6636
6637 @item -gnat-p
6638 @cindex @option{-gnat-p} (@command{gcc})
6639 @cindex Suppressing checks
6640 @cindex Checks, suppressing
6641 @findex Suppress
6642 This switch cancels the effect of a previous @option{gnatp} switch.
6643
6644 @item -gnato
6645 @cindex @option{-gnato} (@command{gcc})
6646 @cindex Overflow checks
6647 @cindex Check, overflow
6648 Enables overflow checking for integer operations.
6649 This causes GNAT to generate slower and larger executable
6650 programs by adding code to check for overflow (resulting in raising
6651 @code{Constraint_Error} as required by standard Ada
6652 semantics). These overflow checks correspond to situations in which
6653 the true value of the result of an operation may be outside the base
6654 range of the result type. The following example shows the distinction:
6655
6656 @smallexample @c ada
6657 X1 : Integer := "Integer'Last";
6658 X2 : Integer range 1 .. 5 := "5";
6659 X3 : Integer := "Integer'Last";
6660 X4 : Integer range 1 .. 5 := "5";
6661 F  : Float := "2.0E+20";
6662 @dots{}
6663 X1 := X1 + 1;
6664 X2 := X2 + 1;
6665 X3 := Integer (F);
6666 X4 := Integer (F);
6667 @end smallexample
6668
6669 @noindent
6670 Note that if explicit values are assigned at compile time, the
6671 compiler may be able to detect overflow at compile time, in which case
6672 no actual run-time checking code is required, and Constraint_Error
6673 will be raised unconditionally, with or without
6674 @option{-gnato}. That's why the assigned values in the above fragment
6675 are in quotes, the meaning is "assign a value not known to the
6676 compiler that happens to be equal to ...". The remaining discussion
6677 assumes that the compiler cannot detect the values at compile time.
6678
6679 Here the first addition results in a value that is outside the base range
6680 of Integer, and hence requires an overflow check for detection of the
6681 constraint error. Thus the first assignment to @code{X1} raises a
6682 @code{Constraint_Error} exception only if @option{-gnato} is set.
6683
6684 The second increment operation results in a violation of the explicit
6685 range constraint; such range checks are performed by default, and are
6686 unaffected by @option{-gnato}.
6687
6688 The two conversions of @code{F} both result in values that are outside
6689 the base range of type @code{Integer} and thus will raise
6690 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6691 The fact that the result of the second conversion is assigned to
6692 variable @code{X4} with a restricted range is irrelevant, since the problem
6693 is in the conversion, not the assignment.
6694
6695 Basically the rule is that in the default mode (@option{-gnato} not
6696 used), the generated code assures that all integer variables stay
6697 within their declared ranges, or within the base range if there is
6698 no declared range. This prevents any serious problems like indexes
6699 out of range for array operations.
6700
6701 What is not checked in default mode is an overflow that results in
6702 an in-range, but incorrect value. In the above example, the assignments
6703 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6704 range of the target variable, but the result is wrong in the sense that
6705 it is too large to be represented correctly. Typically the assignment
6706 to @code{X1} will result in wrap around to the largest negative number.
6707 The conversions of @code{F} will result in some @code{Integer} value
6708 and if that integer value is out of the @code{X4} range then the
6709 subsequent assignment would generate an exception.
6710
6711 @findex Machine_Overflows
6712 Note that the @option{-gnato} switch does not affect the code generated
6713 for any floating-point operations; it applies only to integer
6714 semantics).
6715 For floating-point, GNAT has the @code{Machine_Overflows}
6716 attribute set to @code{False} and the normal mode of operation is to
6717 generate IEEE NaN and infinite values on overflow or invalid operations
6718 (such as dividing 0.0 by 0.0).
6719
6720 The reason that we distinguish overflow checking from other kinds of
6721 range constraint checking is that a failure of an overflow check, unlike
6722 for example the failure of a range check, can result in an incorrect
6723 value, but cannot cause random memory destruction (like an out of range
6724 subscript), or a wild jump (from an out of range case value). Overflow
6725 checking is also quite expensive in time and space, since in general it
6726 requires the use of double length arithmetic.
6727
6728 Note again that @option{-gnato} is off by default, so overflow checking is
6729 not performed in default mode. This means that out of the box, with the
6730 default settings, GNAT does not do all the checks expected from the
6731 language description in the Ada Reference Manual. If you want all constraint
6732 checks to be performed, as described in this Manual, then you must
6733 explicitly use the -gnato switch either on the @command{gnatmake} or
6734 @command{gcc} command.
6735
6736 @item -gnatE
6737 @cindex @option{-gnatE} (@command{gcc})
6738 @cindex Elaboration checks
6739 @cindex Check, elaboration
6740 Enables dynamic checks for access-before-elaboration
6741 on subprogram calls and generic instantiations.
6742 Note that @option{-gnatE} is not necessary for safety, because in the
6743 default mode, GNAT ensures statically that the checks would not fail.
6744 For full details of the effect and use of this switch,
6745 @xref{Compiling Using gcc}.
6746
6747 @item -fstack-check
6748 @cindex @option{-fstack-check} (@command{gcc})
6749 @cindex Stack Overflow Checking
6750 @cindex Checks, stack overflow checking
6751 Activates stack overflow checking. For full details of the effect and use of
6752 this switch see @ref{Stack Overflow Checking}.
6753 @end table
6754
6755 @findex Unsuppress
6756 @noindent
6757 The setting of these switches only controls the default setting of the
6758 checks. You may modify them using either @code{Suppress} (to remove
6759 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6760 the program source.
6761
6762 @node Using gcc for Syntax Checking
6763 @subsection Using @command{gcc} for Syntax Checking
6764 @table @option
6765 @item -gnats
6766 @cindex @option{-gnats} (@command{gcc})
6767 @ifclear vms
6768
6769 @noindent
6770 The @code{s} stands for ``syntax''.
6771 @end ifclear
6772
6773 Run GNAT in syntax checking only mode. For
6774 example, the command
6775
6776 @smallexample
6777 $ gcc -c -gnats x.adb
6778 @end smallexample
6779
6780 @noindent
6781 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6782 series of files in a single command
6783 @ifclear vms
6784 , and can use wild cards to specify such a group of files.
6785 Note that you must specify the @option{-c} (compile
6786 only) flag in addition to the @option{-gnats} flag.
6787 @end ifclear
6788 .
6789 You may use other switches in conjunction with @option{-gnats}. In
6790 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6791 format of any generated error messages.
6792
6793 When the source file is empty or contains only empty lines and/or comments,
6794 the output is a warning:
6795
6796 @smallexample
6797 $ gcc -c -gnats -x ada toto.txt
6798 toto.txt:1:01: warning: empty file, contains no compilation units
6799 $
6800 @end smallexample
6801
6802 Otherwise, the output is simply the error messages, if any. No object file or
6803 ALI file is generated by a syntax-only compilation. Also, no units other
6804 than the one specified are accessed. For example, if a unit @code{X}
6805 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6806 check only mode does not access the source file containing unit
6807 @code{Y}.
6808
6809 @cindex Multiple units, syntax checking
6810 Normally, GNAT allows only a single unit in a source file. However, this
6811 restriction does not apply in syntax-check-only mode, and it is possible
6812 to check a file containing multiple compilation units concatenated
6813 together. This is primarily used by the @code{gnatchop} utility
6814 (@pxref{Renaming Files Using gnatchop}).
6815 @end table
6816
6817 @node Using gcc for Semantic Checking
6818 @subsection Using @command{gcc} for Semantic Checking
6819 @table @option
6820 @item -gnatc
6821 @cindex @option{-gnatc} (@command{gcc})
6822
6823 @ifclear vms
6824 @noindent
6825 The @code{c} stands for ``check''.
6826 @end ifclear
6827 Causes the compiler to operate in semantic check mode,
6828 with full checking for all illegalities specified in the
6829 Ada Reference Manual, but without generation of any object code
6830 (no object file is generated).
6831
6832 Because dependent files must be accessed, you must follow the GNAT
6833 semantic restrictions on file structuring to operate in this mode:
6834
6835 @itemize @bullet
6836 @item
6837 The needed source files must be accessible
6838 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6839
6840 @item
6841 Each file must contain only one compilation unit.
6842
6843 @item
6844 The file name and unit name must match (@pxref{File Naming Rules}).
6845 @end itemize
6846
6847 The output consists of error messages as appropriate. No object file is
6848 generated. An @file{ALI} file is generated for use in the context of
6849 cross-reference tools, but this file is marked as not being suitable
6850 for binding (since no object file is generated).
6851 The checking corresponds exactly to the notion of
6852 legality in the Ada Reference Manual.
6853
6854 Any unit can be compiled in semantics-checking-only mode, including
6855 units that would not normally be compiled (subunits,
6856 and specifications where a separate body is present).
6857 @end table
6858
6859 @node Compiling Different Versions of Ada
6860 @subsection Compiling Different Versions of Ada
6861
6862 @noindent
6863 The switches described in this section allow you to explicitly specify
6864 the version of the Ada language that your programs are written in.
6865 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6866 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6867 indicate Ada 83 compatibility mode.
6868
6869 @table @option
6870 @cindex Compatibility with Ada 83
6871
6872 @item -gnat83 (Ada 83 Compatibility Mode)
6873 @cindex @option{-gnat83} (@command{gcc})
6874 @cindex ACVC, Ada 83 tests
6875 @cindex Ada 83 mode
6876
6877 @noindent
6878 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6879 specifies that the program is to be compiled in Ada 83 mode. With
6880 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6881 semantics where this can be done easily.
6882 It is not possible to guarantee this switch does a perfect
6883 job; some subtle tests, such as are
6884 found in earlier ACVC tests (and that have been removed from the ACATS suite
6885 for Ada 95), might not compile correctly.
6886 Nevertheless, this switch may be useful in some circumstances, for example
6887 where, due to contractual reasons, existing code needs to be maintained
6888 using only Ada 83 features.
6889
6890 With few exceptions (most notably the need to use @code{<>} on
6891 @cindex Generic formal parameters
6892 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6893 reserved words, and the use of packages
6894 with optional bodies), it is not necessary to specify the
6895 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6896 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6897 a correct Ada 83 program is usually also a correct program
6898 in these later versions of the language standard.
6899 For further information, please refer to @ref{Compatibility and Porting Guide}.
6900
6901 @item -gnat95 (Ada 95 mode)
6902 @cindex @option{-gnat95} (@command{gcc})
6903 @cindex Ada 95 mode
6904
6905 @noindent
6906 This switch directs the compiler to implement the Ada 95 version of the
6907 language.
6908 Since Ada 95 is almost completely upwards
6909 compatible with Ada 83, Ada 83 programs may generally be compiled using
6910 this switch (see the description of the @option{-gnat83} switch for further
6911 information about Ada 83 mode).
6912 If an Ada 2005 program is compiled in Ada 95 mode,
6913 uses of the new Ada 2005 features will cause error
6914 messages or warnings.
6915
6916 This switch also can be used to cancel the effect of a previous
6917 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6918
6919 @item -gnat05 (Ada 2005 mode)
6920 @cindex @option{-gnat05} (@command{gcc})
6921 @cindex Ada 2005 mode
6922
6923 @noindent
6924 This switch directs the compiler to implement the Ada 2005 version of the
6925 language.
6926 Since Ada 2005 is almost completely upwards
6927 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6928 may generally be compiled using this switch (see the description of the
6929 @option{-gnat83} and @option{-gnat95} switches for further
6930 information).
6931
6932 For information about the approved ``Ada Issues'' that have been incorporated
6933 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6934 Included with GNAT releases is a file @file{features-ada0y} that describes
6935 the set of implemented Ada 2005 features.
6936 @end table
6937
6938
6939 @node Character Set Control
6940 @subsection Character Set Control
6941 @table @option
6942 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6943 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6944
6945 @noindent
6946 Normally GNAT recognizes the Latin-1 character set in source program
6947 identifiers, as described in the Ada Reference Manual.
6948 This switch causes
6949 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6950 single character ^^or word^ indicating the character set, as follows:
6951
6952 @table @code
6953 @item 1
6954 ISO 8859-1 (Latin-1) identifiers
6955
6956 @item 2
6957 ISO 8859-2 (Latin-2) letters allowed in identifiers
6958
6959 @item 3
6960 ISO 8859-3 (Latin-3) letters allowed in identifiers
6961
6962 @item 4
6963 ISO 8859-4 (Latin-4) letters allowed in identifiers
6964
6965 @item 5
6966 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6967
6968 @item 9
6969 ISO 8859-15 (Latin-9) letters allowed in identifiers
6970
6971 @item ^p^PC^
6972 IBM PC letters (code page 437) allowed in identifiers
6973
6974 @item ^8^PC850^
6975 IBM PC letters (code page 850) allowed in identifiers
6976
6977 @item ^f^FULL_UPPER^
6978 Full upper-half codes allowed in identifiers
6979
6980 @item ^n^NO_UPPER^
6981 No upper-half codes allowed in identifiers
6982
6983 @item ^w^WIDE^
6984 Wide-character codes (that is, codes greater than 255)
6985 allowed in identifiers
6986 @end table
6987
6988 @xref{Foreign Language Representation}, for full details on the
6989 implementation of these character sets.
6990
6991 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6992 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6993 Specify the method of encoding for wide characters.
6994 @var{e} is one of the following:
6995
6996 @table @code
6997
6998 @item ^h^HEX^
6999 Hex encoding (brackets coding also recognized)
7000
7001 @item ^u^UPPER^
7002 Upper half encoding (brackets encoding also recognized)
7003
7004 @item ^s^SHIFT_JIS^
7005 Shift/JIS encoding (brackets encoding also recognized)
7006
7007 @item ^e^EUC^
7008 EUC encoding (brackets encoding also recognized)
7009
7010 @item ^8^UTF8^
7011 UTF-8 encoding (brackets encoding also recognized)
7012
7013 @item ^b^BRACKETS^
7014 Brackets encoding only (default value)
7015 @end table
7016 For full details on these encoding
7017 methods see @ref{Wide Character Encodings}.
7018 Note that brackets coding is always accepted, even if one of the other
7019 options is specified, so for example @option{-gnatW8} specifies that both
7020 brackets and UTF-8 encodings will be recognized. The units that are
7021 with'ed directly or indirectly will be scanned using the specified
7022 representation scheme, and so if one of the non-brackets scheme is
7023 used, it must be used consistently throughout the program. However,
7024 since brackets encoding is always recognized, it may be conveniently
7025 used in standard libraries, allowing these libraries to be used with
7026 any of the available coding schemes.
7027 scheme.
7028
7029 If no @option{-gnatW?} parameter is present, then the default
7030 representation is normally Brackets encoding only. However, if the
7031 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7032 byte order mark or BOM for UTF-8), then these three characters are
7033 skipped and the default representation for the file is set to UTF-8.
7034
7035 Note that the wide character representation that is specified (explicitly
7036 or by default) for the main program also acts as the default encoding used
7037 for Wide_Text_IO files if not specifically overridden by a WCEM form
7038 parameter.
7039
7040 @end table
7041 @node File Naming Control
7042 @subsection File Naming Control
7043
7044 @table @option
7045 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7046 @cindex @option{-gnatk} (@command{gcc})
7047 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7048 1-999, indicates the maximum allowable length of a file name (not
7049 including the @file{.ads} or @file{.adb} extension). The default is not
7050 to enable file name krunching.
7051
7052 For the source file naming rules, @xref{File Naming Rules}.
7053 @end table
7054
7055 @node Subprogram Inlining Control
7056 @subsection Subprogram Inlining Control
7057
7058 @table @option
7059 @c !sort!
7060 @item -gnatn
7061 @cindex @option{-gnatn} (@command{gcc})
7062 @ifclear vms
7063 The @code{n} here is intended to suggest the first syllable of the
7064 word ``inline''.
7065 @end ifclear
7066 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7067 inlining to actually occur, optimization must be enabled. To enable
7068 inlining of subprograms specified by pragma @code{Inline},
7069 you must also specify this switch.
7070 In the absence of this switch, GNAT does not attempt
7071 inlining and does not need to access the bodies of
7072 subprograms for which @code{pragma Inline} is specified if they are not
7073 in the current unit.
7074
7075 If you specify this switch the compiler will access these bodies,
7076 creating an extra source dependency for the resulting object file, and
7077 where possible, the call will be inlined.
7078 For further details on when inlining is possible
7079 see @ref{Inlining of Subprograms}.
7080
7081 @item -gnatN
7082 @cindex @option{-gnatN} (@command{gcc})
7083 This switch activates front-end inlining which also
7084 generates additional dependencies.
7085
7086 When using a gcc-based back end (in practice this means using any version
7087 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7088 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7089 Historically front end inlining was more extensive than the gcc back end
7090 inlining, but that is no longer the case.
7091 @end table
7092
7093 @node Auxiliary Output Control
7094 @subsection Auxiliary Output Control
7095
7096 @table @option
7097 @item -gnatt
7098 @cindex @option{-gnatt} (@command{gcc})
7099 @cindex Writing internal trees
7100 @cindex Internal trees, writing to file
7101 Causes GNAT to write the internal tree for a unit to a file (with the
7102 extension @file{.adt}.
7103 This not normally required, but is used by separate analysis tools.
7104 Typically
7105 these tools do the necessary compilations automatically, so you should
7106 not have to specify this switch in normal operation.
7107 Note that the combination of switches @option{-gnatct}
7108 generates a tree in the form required by ASIS applications.
7109
7110 @item -gnatu
7111 @cindex @option{-gnatu} (@command{gcc})
7112 Print a list of units required by this compilation on @file{stdout}.
7113 The listing includes all units on which the unit being compiled depends
7114 either directly or indirectly.
7115
7116 @ifclear vms
7117 @item -pass-exit-codes
7118 @cindex @option{-pass-exit-codes} (@command{gcc})
7119 If this switch is not used, the exit code returned by @command{gcc} when
7120 compiling multiple files indicates whether all source files have
7121 been successfully used to generate object files or not.
7122
7123 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7124 exit status and allows an integrated development environment to better
7125 react to a compilation failure. Those exit status are:
7126
7127 @table @asis
7128 @item 5
7129 There was an error in at least one source file.
7130 @item 3
7131 At least one source file did not generate an object file.
7132 @item 2
7133 The compiler died unexpectedly (internal error for example).
7134 @item 0
7135 An object file has been generated for every source file.
7136 @end table
7137 @end ifclear
7138 @end table
7139
7140 @node Debugging Control
7141 @subsection Debugging Control
7142
7143 @table @option
7144 @c !sort!
7145 @cindex Debugging options
7146 @ifclear vms
7147 @item -gnatd@var{x}
7148 @cindex @option{-gnatd} (@command{gcc})
7149 Activate internal debugging switches. @var{x} is a letter or digit, or
7150 string of letters or digits, which specifies the type of debugging
7151 outputs desired. Normally these are used only for internal development
7152 or system debugging purposes. You can find full documentation for these
7153 switches in the body of the @code{Debug} unit in the compiler source
7154 file @file{debug.adb}.
7155 @end ifclear
7156
7157 @item -gnatG[=nn]
7158 @cindex @option{-gnatG} (@command{gcc})
7159 This switch causes the compiler to generate auxiliary output containing
7160 a pseudo-source listing of the generated expanded code. Like most Ada
7161 compilers, GNAT works by first transforming the high level Ada code into
7162 lower level constructs. For example, tasking operations are transformed
7163 into calls to the tasking run-time routines. A unique capability of GNAT
7164 is to list this expanded code in a form very close to normal Ada source.
7165 This is very useful in understanding the implications of various Ada
7166 usage on the efficiency of the generated code. There are many cases in
7167 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7168 generate a lot of run-time code. By using @option{-gnatG} you can identify
7169 these cases, and consider whether it may be desirable to modify the coding
7170 approach to improve efficiency.
7171
7172 The optional parameter @code{nn} if present after -gnatG specifies an
7173 alternative maximum line length that overrides the normal default of 72.
7174 This value is in the range 40-999999, values less than 40 being silently
7175 reset to 40. The equal sign is optional.
7176
7177 The format of the output is very similar to standard Ada source, and is
7178 easily understood by an Ada programmer. The following special syntactic
7179 additions correspond to low level features used in the generated code that
7180 do not have any exact analogies in pure Ada source form. The following
7181 is a partial list of these special constructions. See the spec
7182 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7183
7184 If the switch @option{-gnatL} is used in conjunction with
7185 @cindex @option{-gnatL} (@command{gcc})
7186 @option{-gnatG}, then the original source lines are interspersed
7187 in the expanded source (as comment lines with the original line number).
7188
7189 @table @code
7190 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7191 Shows the storage pool being used for an allocator.
7192
7193 @item at end @var{procedure-name};
7194 Shows the finalization (cleanup) procedure for a scope.
7195
7196 @item (if @var{expr} then @var{expr} else @var{expr})
7197 Conditional expression equivalent to the @code{x?y:z} construction in C.
7198
7199 @item @var{target}^^^(@var{source})
7200 A conversion with floating-point truncation instead of rounding.
7201
7202 @item @var{target}?(@var{source})
7203 A conversion that bypasses normal Ada semantic checking. In particular
7204 enumeration types and fixed-point types are treated simply as integers.
7205
7206 @item @var{target}?^^^(@var{source})
7207 Combines the above two cases.
7208
7209 @item @var{x} #/ @var{y}
7210 @itemx @var{x} #mod @var{y}
7211 @itemx @var{x} #* @var{y}
7212 @itemx @var{x} #rem @var{y}
7213 A division or multiplication of fixed-point values which are treated as
7214 integers without any kind of scaling.
7215
7216 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7217 Shows the storage pool associated with a @code{free} statement.
7218
7219 @item [subtype or type declaration]
7220 Used to list an equivalent declaration for an internally generated
7221 type that is referenced elsewhere in the listing.
7222
7223 @c @item freeze @var{type-name} @ovar{actions}
7224 @c Expanding @ovar macro inline (explanation in macro def comments)
7225 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7226 Shows the point at which @var{type-name} is frozen, with possible
7227 associated actions to be performed at the freeze point.
7228
7229 @item reference @var{itype}
7230 Reference (and hence definition) to internal type @var{itype}.
7231
7232 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7233 Intrinsic function call.
7234
7235 @item @var{label-name} : label
7236 Declaration of label @var{labelname}.
7237
7238 @item #$ @var{subprogram-name}
7239 An implicit call to a run-time support routine
7240 (to meet the requirement of H.3.1(9) in a
7241 convenient manner).
7242
7243 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7244 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7245 @var{expr}, but handled more efficiently).
7246
7247 @item [constraint_error]
7248 Raise the @code{Constraint_Error} exception.
7249
7250 @item @var{expression}'reference
7251 A pointer to the result of evaluating @var{expression}.
7252
7253 @item @var{target-type}!(@var{source-expression})
7254 An unchecked conversion of @var{source-expression} to @var{target-type}.
7255
7256 @item [@var{numerator}/@var{denominator}]
7257 Used to represent internal real literals (that) have no exact
7258 representation in base 2-16 (for example, the result of compile time
7259 evaluation of the expression 1.0/27.0).
7260 @end table
7261
7262 @item -gnatD[=nn]
7263 @cindex @option{-gnatD} (@command{gcc})
7264 When used in conjunction with @option{-gnatG}, this switch causes
7265 the expanded source, as described above for
7266 @option{-gnatG} to be written to files with names
7267 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7268 instead of to the standard output file. For
7269 example, if the source file name is @file{hello.adb}, then a file
7270 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7271 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7272 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7273 you to do source level debugging using the generated code which is
7274 sometimes useful for complex code, for example to find out exactly
7275 which part of a complex construction raised an exception. This switch
7276 also suppress generation of cross-reference information (see
7277 @option{-gnatx}) since otherwise the cross-reference information
7278 would refer to the @file{^.dg^.DG^} file, which would cause
7279 confusion since this is not the original source file.
7280
7281 Note that @option{-gnatD} actually implies @option{-gnatG}
7282 automatically, so it is not necessary to give both options.
7283 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7284
7285 If the switch @option{-gnatL} is used in conjunction with
7286 @cindex @option{-gnatL} (@command{gcc})
7287 @option{-gnatDG}, then the original source lines are interspersed
7288 in the expanded source (as comment lines with the original line number).
7289
7290 The optional parameter @code{nn} if present after -gnatD specifies an
7291 alternative maximum line length that overrides the normal default of 72.
7292 This value is in the range 40-999999, values less than 40 being silently
7293 reset to 40. The equal sign is optional.
7294
7295 @item -gnatr
7296 @cindex @option{-gnatr} (@command{gcc})
7297 @cindex pragma Restrictions
7298 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7299 so that violation of restrictions causes warnings rather than illegalities.
7300 This is useful during the development process when new restrictions are added
7301 or investigated. The switch also causes pragma Profile to be treated as
7302 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7303 restriction warnings rather than restrictions.
7304
7305 @ifclear vms
7306 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7307 @cindex @option{-gnatR} (@command{gcc})
7308 This switch controls output from the compiler of a listing showing
7309 representation information for declared types and objects. For
7310 @option{-gnatR0}, no information is output (equivalent to omitting
7311 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7312 so @option{-gnatR} with no parameter has the same effect), size and alignment
7313 information is listed for declared array and record types. For
7314 @option{-gnatR2}, size and alignment information is listed for all
7315 declared types and objects. Finally @option{-gnatR3} includes symbolic
7316 expressions for values that are computed at run time for
7317 variant records. These symbolic expressions have a mostly obvious
7318 format with #n being used to represent the value of the n'th
7319 discriminant. See source files @file{repinfo.ads/adb} in the
7320 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7321 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7322 the output is to a file with the name @file{^file.rep^file_REP^} where
7323 file is the name of the corresponding source file.
7324 @end ifclear
7325 @ifset vms
7326 @item /REPRESENTATION_INFO
7327 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7328 This qualifier controls output from the compiler of a listing showing
7329 representation information for declared types and objects. For
7330 @option{/REPRESENTATION_INFO=NONE}, no information is output
7331 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7332 @option{/REPRESENTATION_INFO} without option is equivalent to
7333 @option{/REPRESENTATION_INFO=ARRAYS}.
7334 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7335 information is listed for declared array and record types. For
7336 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7337 is listed for all expression information for values that are computed
7338 at run time for variant records. These symbolic expressions have a mostly
7339 obvious format with #n being used to represent the value of the n'th
7340 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7341 @code{GNAT} sources for full details on the format of
7342 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7343 If _FILE is added at the end of an option
7344 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7345 then the output is to a file with the name @file{file_REP} where
7346 file is the name of the corresponding source file.
7347 @end ifset
7348 Note that it is possible for record components to have zero size. In
7349 this case, the component clause uses an obvious extension of permitted
7350 Ada syntax, for example @code{at 0 range 0 .. -1}.
7351
7352 Representation information requires that code be generated (since it is the
7353 code generator that lays out complex data structures). If an attempt is made
7354 to output representation information when no code is generated, for example
7355 when a subunit is compiled on its own, then no information can be generated
7356 and the compiler outputs a message to this effect.
7357
7358 @item -gnatS
7359 @cindex @option{-gnatS} (@command{gcc})
7360 The use of the switch @option{-gnatS} for an
7361 Ada compilation will cause the compiler to output a
7362 representation of package Standard in a form very
7363 close to standard Ada. It is not quite possible to
7364 do this entirely in standard Ada (since new
7365 numeric base types cannot be created in standard
7366 Ada), but the output is easily
7367 readable to any Ada programmer, and is useful to
7368 determine the characteristics of target dependent
7369 types in package Standard.
7370
7371 @item -gnatx
7372 @cindex @option{-gnatx} (@command{gcc})
7373 Normally the compiler generates full cross-referencing information in
7374 the @file{ALI} file. This information is used by a number of tools,
7375 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7376 suppresses this information. This saves some space and may slightly
7377 speed up compilation, but means that these tools cannot be used.
7378 @end table
7379
7380 @node Exception Handling Control
7381 @subsection Exception Handling Control
7382
7383 @noindent
7384 GNAT uses two methods for handling exceptions at run-time. The
7385 @code{setjmp/longjmp} method saves the context when entering
7386 a frame with an exception handler. Then when an exception is
7387 raised, the context can be restored immediately, without the
7388 need for tracing stack frames. This method provides very fast
7389 exception propagation, but introduces significant overhead for
7390 the use of exception handlers, even if no exception is raised.
7391
7392 The other approach is called ``zero cost'' exception handling.
7393 With this method, the compiler builds static tables to describe
7394 the exception ranges. No dynamic code is required when entering
7395 a frame containing an exception handler. When an exception is
7396 raised, the tables are used to control a back trace of the
7397 subprogram invocation stack to locate the required exception
7398 handler. This method has considerably poorer performance for
7399 the propagation of exceptions, but there is no overhead for
7400 exception handlers if no exception is raised. Note that in this
7401 mode and in the context of mixed Ada and C/C++ programming,
7402 to propagate an exception through a C/C++ code, the C/C++ code
7403 must be compiled with the @option{-funwind-tables} GCC's
7404 option.
7405
7406 The following switches may be used to control which of the
7407 two exception handling methods is used.
7408
7409 @table @option
7410 @c !sort!
7411
7412 @item --RTS=sjlj
7413 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7414 This switch causes the setjmp/longjmp run-time (when available) to be used
7415 for exception handling. If the default
7416 mechanism for the target is zero cost exceptions, then
7417 this switch can be used to modify this default, and must be
7418 used for all units in the partition.
7419 This option is rarely used. One case in which it may be
7420 advantageous is if you have an application where exception
7421 raising is common and the overall performance of the
7422 application is improved by favoring exception propagation.
7423
7424 @item --RTS=zcx
7425 @cindex @option{--RTS=zcx} (@command{gnatmake})
7426 @cindex Zero Cost Exceptions
7427 This switch causes the zero cost approach to be used
7428 for exception handling. If this is the default mechanism for the
7429 target (see below), then this switch is unneeded. If the default
7430 mechanism for the target is setjmp/longjmp exceptions, then
7431 this switch can be used to modify this default, and must be
7432 used for all units in the partition.
7433 This option can only be used if the zero cost approach
7434 is available for the target in use, otherwise it will generate an error.
7435 @end table
7436
7437 @noindent
7438 The same option @option{--RTS} must be used both for @command{gcc}
7439 and @command{gnatbind}. Passing this option to @command{gnatmake}
7440 (@pxref{Switches for gnatmake}) will ensure the required consistency
7441 through the compilation and binding steps.
7442
7443 @node Units to Sources Mapping Files
7444 @subsection Units to Sources Mapping Files
7445
7446 @table @option
7447
7448 @item -gnatem=@var{path}
7449 @cindex @option{-gnatem} (@command{gcc})
7450 A mapping file is a way to communicate to the compiler two mappings:
7451 from unit names to file names (without any directory information) and from
7452 file names to path names (with full directory information). These mappings
7453 are used by the compiler to short-circuit the path search.
7454
7455 The use of mapping files is not required for correct operation of the
7456 compiler, but mapping files can improve efficiency, particularly when
7457 sources are read over a slow network connection. In normal operation,
7458 you need not be concerned with the format or use of mapping files,
7459 and the @option{-gnatem} switch is not a switch that you would use
7460 explicitly. It is intended primarily for use by automatic tools such as
7461 @command{gnatmake} running under the project file facility. The
7462 description here of the format of mapping files is provided
7463 for completeness and for possible use by other tools.
7464
7465 A mapping file is a sequence of sets of three lines. In each set, the
7466 first line is the unit name, in lower case, with @code{%s} appended
7467 for specs and @code{%b} appended for bodies; the second line is the
7468 file name; and the third line is the path name.
7469
7470 Example:
7471 @smallexample
7472    main%b
7473    main.2.ada
7474    /gnat/project1/sources/main.2.ada
7475 @end smallexample
7476
7477 When the switch @option{-gnatem} is specified, the compiler will
7478 create in memory the two mappings from the specified file. If there is
7479 any problem (nonexistent file, truncated file or duplicate entries),
7480 no mapping will be created.
7481
7482 Several @option{-gnatem} switches may be specified; however, only the
7483 last one on the command line will be taken into account.
7484
7485 When using a project file, @command{gnatmake} creates a temporary
7486 mapping file and communicates it to the compiler using this switch.
7487
7488 @end table
7489
7490 @node Integrated Preprocessing
7491 @subsection Integrated Preprocessing
7492
7493 @noindent
7494 GNAT sources may be preprocessed immediately before compilation.
7495 In this case, the actual
7496 text of the source is not the text of the source file, but is derived from it
7497 through a process called preprocessing. Integrated preprocessing is specified
7498 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7499 indicates, through a text file, the preprocessing data to be used.
7500 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7501
7502 @noindent
7503 Note that when integrated preprocessing is used, the output from the
7504 preprocessor is not written to any external file. Instead it is passed
7505 internally to the compiler. If you need to preserve the result of
7506 preprocessing in a file, then you should use @command{gnatprep}
7507 to perform the desired preprocessing in stand-alone mode.
7508
7509 @noindent
7510 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7511 used when Integrated Preprocessing is used. The reason is that preprocessing
7512 with another Preprocessing Data file without changing the sources will
7513 not trigger recompilation without this switch.
7514
7515 @noindent
7516 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7517 always trigger recompilation for sources that are preprocessed,
7518 because @command{gnatmake} cannot compute the checksum of the source after
7519 preprocessing.
7520
7521 @noindent
7522 The actual preprocessing function is described in details in section
7523 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7524 preprocessing is triggered and parameterized.
7525
7526 @table @code
7527
7528 @item -gnatep=@var{file}
7529 @cindex @option{-gnatep} (@command{gcc})
7530 This switch indicates to the compiler the file name (without directory
7531 information) of the preprocessor data file to use. The preprocessor data file
7532 should be found in the source directories.
7533
7534 @noindent
7535 A preprocessing data file is a text file with significant lines indicating
7536 how should be preprocessed either a specific source or all sources not
7537 mentioned in other lines. A significant line is a nonempty, non-comment line.
7538 Comments are similar to Ada comments.
7539
7540 @noindent
7541 Each significant line starts with either a literal string or the character '*'.
7542 A literal string is the file name (without directory information) of the source
7543 to preprocess. A character '*' indicates the preprocessing for all the sources
7544 that are not specified explicitly on other lines (order of the lines is not
7545 significant). It is an error to have two lines with the same file name or two
7546 lines starting with the character '*'.
7547
7548 @noindent
7549 After the file name or the character '*', another optional literal string
7550 indicating the file name of the definition file to be used for preprocessing
7551 (@pxref{Form of Definitions File}). The definition files are found by the
7552 compiler in one of the source directories. In some cases, when compiling
7553 a source in a directory other than the current directory, if the definition
7554 file is in the current directory, it may be necessary to add the current
7555 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7556 the compiler would not find the definition file.
7557
7558 @noindent
7559 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7560 be found. Those ^switches^switches^ are:
7561
7562 @table @code
7563
7564 @item -b
7565 Causes both preprocessor lines and the lines deleted by
7566 preprocessing to be replaced by blank lines, preserving the line number.
7567 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7568 it cancels the effect of @option{-c}.
7569
7570 @item -c
7571 Causes both preprocessor lines and the lines deleted
7572 by preprocessing to be retained as comments marked
7573 with the special string ``@code{--! }''.
7574
7575 @item -Dsymbol=value
7576 Define or redefine a symbol, associated with value. A symbol is an Ada
7577 identifier, or an Ada reserved word, with the exception of @code{if},
7578 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7579 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7580 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7581 same name defined in a definition file.
7582
7583 @item -s
7584 Causes a sorted list of symbol names and values to be
7585 listed on the standard output file.
7586
7587 @item -u
7588 Causes undefined symbols to be treated as having the value @code{FALSE}
7589 in the context
7590 of a preprocessor test. In the absence of this option, an undefined symbol in
7591 a @code{#if} or @code{#elsif} test will be treated as an error.
7592
7593 @end table
7594
7595 @noindent
7596 Examples of valid lines in a preprocessor data file:
7597
7598 @smallexample
7599   "toto.adb"  "prep.def" -u
7600   --  preprocess "toto.adb", using definition file "prep.def",
7601   --  undefined symbol are False.
7602
7603   * -c -DVERSION=V101
7604   --  preprocess all other sources without a definition file;
7605   --  suppressed lined are commented; symbol VERSION has the value V101.
7606
7607   "titi.adb" "prep2.def" -s
7608   --  preprocess "titi.adb", using definition file "prep2.def";
7609   --  list all symbols with their values.
7610 @end smallexample
7611
7612 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7613 @cindex @option{-gnateD} (@command{gcc})
7614 Define or redefine a preprocessing symbol, associated with value. If no value
7615 is given on the command line, then the value of the symbol is @code{True}.
7616 A symbol is an identifier, following normal Ada (case-insensitive)
7617 rules for its syntax, and value is any sequence (including an empty sequence)
7618 of characters from the set (letters, digits, period, underline).
7619 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7620 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7621
7622 @noindent
7623 A symbol declared with this ^switch^switch^ on the command line replaces a
7624 symbol with the same name either in a definition file or specified with a
7625 ^switch^switch^ -D in the preprocessor data file.
7626
7627 @noindent
7628 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7629
7630 @item -gnateG
7631 When integrated preprocessing is performed and the preprocessor modifies
7632 the source text, write the result of this preprocessing into a file
7633 <source>^.prep^_prep^.
7634
7635 @end table
7636
7637 @node Code Generation Control
7638 @subsection Code Generation Control
7639
7640 @noindent
7641
7642 The GCC technology provides a wide range of target dependent
7643 @option{-m} switches for controlling
7644 details of code generation with respect to different versions of
7645 architectures. This includes variations in instruction sets (e.g.@:
7646 different members of the power pc family), and different requirements
7647 for optimal arrangement of instructions (e.g.@: different members of
7648 the x86 family). The list of available @option{-m} switches may be
7649 found in the GCC documentation.
7650
7651 Use of these @option{-m} switches may in some cases result in improved
7652 code performance.
7653
7654 The GNAT Pro technology is tested and qualified without any
7655 @option{-m} switches,
7656 so generally the most reliable approach is to avoid the use of these
7657 switches. However, we generally expect most of these switches to work
7658 successfully with GNAT Pro, and many customers have reported successful
7659 use of these options.
7660
7661 Our general advice is to avoid the use of @option{-m} switches unless
7662 special needs lead to requirements in this area. In particular,
7663 there is no point in using @option{-m} switches to improve performance
7664 unless you actually see a performance improvement.
7665
7666 @ifset vms
7667 @node Return Codes
7668 @subsection Return Codes
7669 @cindex Return Codes
7670 @cindex @option{/RETURN_CODES=VMS}
7671
7672 @noindent
7673 On VMS, GNAT compiled programs return POSIX-style codes by default,
7674 e.g.@: @option{/RETURN_CODES=POSIX}.
7675
7676 To enable VMS style return codes, use GNAT BIND and LINK with the option
7677 @option{/RETURN_CODES=VMS}. For example:
7678
7679 @smallexample
7680 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7681 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7682 @end smallexample
7683
7684 @noindent
7685 Programs built with /RETURN_CODES=VMS are suitable to be called in
7686 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7687 are suitable for spawning with appropriate GNAT RTL routines.
7688
7689 @end ifset
7690
7691 @node Search Paths and the Run-Time Library (RTL)
7692 @section Search Paths and the Run-Time Library (RTL)
7693
7694 @noindent
7695 With the GNAT source-based library system, the compiler must be able to
7696 find source files for units that are needed by the unit being compiled.
7697 Search paths are used to guide this process.
7698
7699 The compiler compiles one source file whose name must be given
7700 explicitly on the command line. In other words, no searching is done
7701 for this file. To find all other source files that are needed (the most
7702 common being the specs of units), the compiler examines the following
7703 directories, in the following order:
7704
7705 @enumerate
7706 @item
7707 The directory containing the source file of the main unit being compiled
7708 (the file name on the command line).
7709
7710 @item
7711 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7712 @command{gcc} command line, in the order given.
7713
7714 @item
7715 @findex ADA_PRJ_INCLUDE_FILE
7716 Each of the directories listed in the text file whose name is given
7717 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7718
7719 @noindent
7720 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7721 driver when project files are used. It should not normally be set
7722 by other means.
7723
7724 @item
7725 @findex ADA_INCLUDE_PATH
7726 Each of the directories listed in the value of the
7727 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7728 @ifclear vms
7729 Construct this value
7730 exactly as the @env{PATH} environment variable: a list of directory
7731 names separated by colons (semicolons when working with the NT version).
7732 @end ifclear
7733 @ifset vms
7734 Normally, define this value as a logical name containing a comma separated
7735 list of directory names.
7736
7737 This variable can also be defined by means of an environment string
7738 (an argument to the HP C exec* set of functions).
7739
7740 Logical Name:
7741 @smallexample
7742 DEFINE ANOTHER_PATH FOO:[BAG]
7743 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7744 @end smallexample
7745
7746 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7747 first, followed by the standard Ada
7748 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7749 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7750 (Text_IO, Sequential_IO, etc)
7751 instead of the standard Ada packages. Thus, in order to get the standard Ada
7752 packages by default, ADA_INCLUDE_PATH must be redefined.
7753 @end ifset
7754
7755 @item
7756 The content of the @file{ada_source_path} file which is part of the GNAT
7757 installation tree and is used to store standard libraries such as the
7758 GNAT Run Time Library (RTL) source files.
7759 @ifclear vms
7760 @ref{Installing a library}
7761 @end ifclear
7762 @end enumerate
7763
7764 @noindent
7765 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7766 inhibits the use of the directory
7767 containing the source file named in the command line. You can still
7768 have this directory on your search path, but in this case it must be
7769 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7770
7771 Specifying the switch @option{-nostdinc}
7772 inhibits the search of the default location for the GNAT Run Time
7773 Library (RTL) source files.
7774
7775 The compiler outputs its object files and ALI files in the current
7776 working directory.
7777 @ifclear vms
7778 Caution: The object file can be redirected with the @option{-o} switch;
7779 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7780 so the @file{ALI} file will not go to the right place. Therefore, you should
7781 avoid using the @option{-o} switch.
7782 @end ifclear
7783
7784 @findex System.IO
7785 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7786 children make up the GNAT RTL, together with the simple @code{System.IO}
7787 package used in the @code{"Hello World"} example. The sources for these units
7788 are needed by the compiler and are kept together in one directory. Not
7789 all of the bodies are needed, but all of the sources are kept together
7790 anyway. In a normal installation, you need not specify these directory
7791 names when compiling or binding. Either the environment variables or
7792 the built-in defaults cause these files to be found.
7793
7794 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7795 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7796 consisting of child units of @code{GNAT}. This is a collection of generally
7797 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7798 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7799
7800 Besides simplifying access to the RTL, a major use of search paths is
7801 in compiling sources from multiple directories. This can make
7802 development environments much more flexible.
7803
7804 @node Order of Compilation Issues
7805 @section Order of Compilation Issues
7806
7807 @noindent
7808 If, in our earlier example, there was a spec for the @code{hello}
7809 procedure, it would be contained in the file @file{hello.ads}; yet this
7810 file would not have to be explicitly compiled. This is the result of the
7811 model we chose to implement library management. Some of the consequences
7812 of this model are as follows:
7813
7814 @itemize @bullet
7815 @item
7816 There is no point in compiling specs (except for package
7817 specs with no bodies) because these are compiled as needed by clients. If
7818 you attempt a useless compilation, you will receive an error message.
7819 It is also useless to compile subunits because they are compiled as needed
7820 by the parent.
7821
7822 @item
7823 There are no order of compilation requirements: performing a
7824 compilation never obsoletes anything. The only way you can obsolete
7825 something and require recompilations is to modify one of the
7826 source files on which it depends.
7827
7828 @item
7829 There is no library as such, apart from the ALI files
7830 (@pxref{The Ada Library Information Files}, for information on the format
7831 of these files). For now we find it convenient to create separate ALI files,
7832 but eventually the information therein may be incorporated into the object
7833 file directly.
7834
7835 @item
7836 When you compile a unit, the source files for the specs of all units
7837 that it @code{with}'s, all its subunits, and the bodies of any generics it
7838 instantiates must be available (reachable by the search-paths mechanism
7839 described above), or you will receive a fatal error message.
7840 @end itemize
7841
7842 @node Examples
7843 @section Examples
7844
7845 @noindent
7846 The following are some typical Ada compilation command line examples:
7847
7848 @table @code
7849 @item $ gcc -c xyz.adb
7850 Compile body in file @file{xyz.adb} with all default options.
7851
7852 @ifclear vms
7853 @item $ gcc -c -O2 -gnata xyz-def.adb
7854 @end ifclear
7855 @ifset vms
7856 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7857 @end ifset
7858
7859 Compile the child unit package in file @file{xyz-def.adb} with extensive
7860 optimizations, and pragma @code{Assert}/@code{Debug} statements
7861 enabled.
7862
7863 @item $ gcc -c -gnatc abc-def.adb
7864 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7865 mode.
7866 @end table
7867
7868 @node Binding Using gnatbind
7869 @chapter Binding Using @code{gnatbind}
7870 @findex gnatbind
7871
7872 @menu
7873 * Running gnatbind::
7874 * Switches for gnatbind::
7875 * Command-Line Access::
7876 * Search Paths for gnatbind::
7877 * Examples of gnatbind Usage::
7878 @end menu
7879
7880 @noindent
7881 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7882 to bind compiled GNAT objects.
7883
7884 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7885 driver (see @ref{The GNAT Driver and Project Files}).
7886
7887 The @code{gnatbind} program performs four separate functions:
7888
7889 @enumerate
7890 @item
7891 Checks that a program is consistent, in accordance with the rules in
7892 Chapter 10 of the Ada Reference Manual. In particular, error
7893 messages are generated if a program uses inconsistent versions of a
7894 given unit.
7895
7896 @item
7897 Checks that an acceptable order of elaboration exists for the program
7898 and issues an error message if it cannot find an order of elaboration
7899 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7900
7901 @item
7902 Generates a main program incorporating the given elaboration order.
7903 This program is a small Ada package (body and spec) that
7904 must be subsequently compiled
7905 using the GNAT compiler. The necessary compilation step is usually
7906 performed automatically by @command{gnatlink}. The two most important
7907 functions of this program
7908 are to call the elaboration routines of units in an appropriate order
7909 and to call the main program.
7910
7911 @item
7912 Determines the set of object files required by the given main program.
7913 This information is output in the forms of comments in the generated program,
7914 to be read by the @command{gnatlink} utility used to link the Ada application.
7915 @end enumerate
7916
7917 @node Running gnatbind
7918 @section Running @code{gnatbind}
7919
7920 @noindent
7921 The form of the @code{gnatbind} command is
7922
7923 @smallexample
7924 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7925 @c Expanding @ovar macro inline (explanation in macro def comments)
7926 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7927 @end smallexample
7928
7929 @noindent
7930 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7931 unit body. @code{gnatbind} constructs an Ada
7932 package in two files whose names are
7933 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7934 For example, if given the
7935 parameter @file{hello.ali}, for a main program contained in file
7936 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7937 and @file{b~hello.adb}.
7938
7939 When doing consistency checking, the binder takes into consideration
7940 any source files it can locate. For example, if the binder determines
7941 that the given main program requires the package @code{Pack}, whose
7942 @file{.ALI}
7943 file is @file{pack.ali} and whose corresponding source spec file is
7944 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7945 (using the same search path conventions as previously described for the
7946 @command{gcc} command). If it can locate this source file, it checks that
7947 the time stamps
7948 or source checksums of the source and its references to in @file{ALI} files
7949 match. In other words, any @file{ALI} files that mentions this spec must have
7950 resulted from compiling this version of the source file (or in the case
7951 where the source checksums match, a version close enough that the
7952 difference does not matter).
7953
7954 @cindex Source files, use by binder
7955 The effect of this consistency checking, which includes source files, is
7956 that the binder ensures that the program is consistent with the latest
7957 version of the source files that can be located at bind time. Editing a
7958 source file without compiling files that depend on the source file cause
7959 error messages to be generated by the binder.
7960
7961 For example, suppose you have a main program @file{hello.adb} and a
7962 package @code{P}, from file @file{p.ads} and you perform the following
7963 steps:
7964
7965 @enumerate
7966 @item
7967 Enter @code{gcc -c hello.adb} to compile the main program.
7968
7969 @item
7970 Enter @code{gcc -c p.ads} to compile package @code{P}.
7971
7972 @item
7973 Edit file @file{p.ads}.
7974
7975 @item
7976 Enter @code{gnatbind hello}.
7977 @end enumerate
7978
7979 @noindent
7980 At this point, the file @file{p.ali} contains an out-of-date time stamp
7981 because the file @file{p.ads} has been edited. The attempt at binding
7982 fails, and the binder generates the following error messages:
7983
7984 @smallexample
7985 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7986 error: "p.ads" has been modified and must be recompiled
7987 @end smallexample
7988
7989 @noindent
7990 Now both files must be recompiled as indicated, and then the bind can
7991 succeed, generating a main program. You need not normally be concerned
7992 with the contents of this file, but for reference purposes a sample
7993 binder output file is given in @ref{Example of Binder Output File}.
7994
7995 In most normal usage, the default mode of @command{gnatbind} which is to
7996 generate the main package in Ada, as described in the previous section.
7997 In particular, this means that any Ada programmer can read and understand
7998 the generated main program. It can also be debugged just like any other
7999 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8000 @command{gnatbind} and @command{gnatlink}.
8001
8002 @node Switches for gnatbind
8003 @section Switches for @command{gnatbind}
8004
8005 @noindent
8006 The following switches are available with @code{gnatbind}; details will
8007 be presented in subsequent sections.
8008
8009 @menu
8010 * Consistency-Checking Modes::
8011 * Binder Error Message Control::
8012 * Elaboration Control::
8013 * Output Control::
8014 * Binding with Non-Ada Main Programs::
8015 * Binding Programs with No Main Subprogram::
8016 @end menu
8017
8018 @table @option
8019 @c !sort!
8020
8021 @item --version
8022 @cindex @option{--version} @command{gnatbind}
8023 Display Copyright and version, then exit disregarding all other options.
8024
8025 @item --help
8026 @cindex @option{--help} @command{gnatbind}
8027 If @option{--version} was not used, display usage, then exit disregarding
8028 all other options.
8029
8030 @item -a
8031 @cindex @option{-a} @command{gnatbind}
8032 Indicates that, if supported by the platform, the adainit procedure should
8033 be treated as an initialisation routine by the linker (a constructor). This
8034 is intended to be used by the Project Manager to automatically initialize
8035 shared Stand-Alone Libraries.
8036
8037 @item ^-aO^/OBJECT_SEARCH^
8038 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8039 Specify directory to be searched for ALI files.
8040
8041 @item ^-aI^/SOURCE_SEARCH^
8042 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8043 Specify directory to be searched for source file.
8044
8045 @item ^-b^/REPORT_ERRORS=BRIEF^
8046 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8047 Generate brief messages to @file{stderr} even if verbose mode set.
8048
8049 @item ^-c^/NOOUTPUT^
8050 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8051 Check only, no generation of binder output file.
8052
8053 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8054 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8055 This switch can be used to change the default task stack size value
8056 to a specified size @var{nn}, which is expressed in bytes by default, or
8057 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8058 with @var{m}.
8059 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8060 in effect, to completing all task specs with
8061 @smallexample @c ada
8062    pragma Storage_Size (nn);
8063 @end smallexample
8064 When they do not already have such a pragma.
8065
8066 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8067 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8068 This switch can be used to change the default secondary stack size value
8069 to a specified size @var{nn}, which is expressed in bytes by default, or
8070 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8071 with @var{m}.
8072
8073 The secondary stack is used to deal with functions that return a variable
8074 sized result, for example a function returning an unconstrained
8075 String. There are two ways in which this secondary stack is allocated.
8076
8077 For most targets, the secondary stack is growing on demand and is allocated
8078 as a chain of blocks in the heap. The -D option is not very
8079 relevant. It only give some control over the size of the allocated
8080 blocks (whose size is the minimum of the default secondary stack size value,
8081 and the actual size needed for the current allocation request).
8082
8083 For certain targets, notably VxWorks 653,
8084 the secondary stack is allocated by carving off a fixed ratio chunk of the
8085 primary task stack. The -D option is used to define the
8086 size of the environment task's secondary stack.
8087
8088 @item ^-e^/ELABORATION_DEPENDENCIES^
8089 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8090 Output complete list of elaboration-order dependencies.
8091
8092 @item ^-E^/STORE_TRACEBACKS^
8093 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8094 Store tracebacks in exception occurrences when the target supports it.
8095 This is the default with the zero cost exception mechanism.
8096 @ignore
8097 @c The following may get moved to an appendix
8098 This option is currently supported on the following targets:
8099 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8100 @end ignore
8101 See also the packages @code{GNAT.Traceback} and
8102 @code{GNAT.Traceback.Symbolic} for more information.
8103 @ifclear vms
8104 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8105 @command{gcc} option.
8106 @end ifclear
8107
8108 @item ^-F^/FORCE_ELABS_FLAGS^
8109 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8110 Force the checks of elaboration flags. @command{gnatbind} does not normally
8111 generate checks of elaboration flags for the main executable, except when
8112 a Stand-Alone Library is used. However, there are cases when this cannot be
8113 detected by gnatbind. An example is importing an interface of a Stand-Alone
8114 Library through a pragma Import and only specifying through a linker switch
8115 this Stand-Alone Library. This switch is used to guarantee that elaboration
8116 flag checks are generated.
8117
8118 @item ^-h^/HELP^
8119 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8120 Output usage (help) information
8121
8122 @item ^-I^/SEARCH^
8123 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8124 Specify directory to be searched for source and ALI files.
8125
8126 @item ^-I-^/NOCURRENT_DIRECTORY^
8127 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8128 Do not look for sources in the current directory where @code{gnatbind} was
8129 invoked, and do not look for ALI files in the directory containing the
8130 ALI file named in the @code{gnatbind} command line.
8131
8132 @item ^-l^/ORDER_OF_ELABORATION^
8133 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8134 Output chosen elaboration order.
8135
8136 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8137 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8138 Bind the units for library building. In this case the adainit and
8139 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8140 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8141 ^@var{xxx}final^@var{XXX}FINAL^.
8142 Implies ^-n^/NOCOMPILE^.
8143 @ifclear vms
8144 (@xref{GNAT and Libraries}, for more details.)
8145 @end ifclear
8146 @ifset vms
8147 On OpenVMS, these init and final procedures are exported in uppercase
8148 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8149 the init procedure will be "TOTOINIT" and the exported name of the final
8150 procedure will be "TOTOFINAL".
8151 @end ifset
8152
8153 @item ^-Mxyz^/RENAME_MAIN=xyz^
8154 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8155 Rename generated main program from main to xyz. This option is
8156 supported on cross environments only.
8157
8158 @item ^-m^/ERROR_LIMIT=^@var{n}
8159 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8160 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8161 in the range 1..999999. The default value if no switch is
8162 given is 9999. If the number of warnings reaches this limit, then a
8163 message is output and further warnings are suppressed, the bind
8164 continues in this case. If the number of errors reaches this
8165 limit, then a message is output and the bind is abandoned.
8166 A value of zero means that no limit is enforced. The equal
8167 sign is optional.
8168
8169 @ifset unw
8170 Furthermore, under Windows, the sources pointed to by the libraries path
8171 set in the registry are not searched for.
8172 @end ifset
8173
8174 @item ^-n^/NOMAIN^
8175 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8176 No main program.
8177
8178 @item -nostdinc
8179 @cindex @option{-nostdinc} (@command{gnatbind})
8180 Do not look for sources in the system default directory.
8181
8182 @item -nostdlib
8183 @cindex @option{-nostdlib} (@command{gnatbind})
8184 Do not look for library files in the system default directory.
8185
8186 @item --RTS=@var{rts-path}
8187 @cindex @option{--RTS} (@code{gnatbind})
8188 Specifies the default location of the runtime library. Same meaning as the
8189 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8190
8191 @item ^-o ^/OUTPUT=^@var{file}
8192 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8193 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8194 Note that if this option is used, then linking must be done manually,
8195 gnatlink cannot be used.
8196
8197 @item ^-O^/OBJECT_LIST^
8198 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8199 Output object list.
8200
8201 @item ^-p^/PESSIMISTIC_ELABORATION^
8202 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8203 Pessimistic (worst-case) elaboration order
8204
8205 @item ^-R^-R^
8206 @cindex @option{^-R^-R^} (@command{gnatbind})
8207 Output closure source list.
8208
8209 @item ^-s^/READ_SOURCES=ALL^
8210 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8211 Require all source files to be present.
8212
8213 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8214 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8215 Specifies the value to be used when detecting uninitialized scalar
8216 objects with pragma Initialize_Scalars.
8217 The @var{xxx} ^string specified with the switch^option^ may be either
8218 @itemize @bullet
8219 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8220 @item ``@option{^lo^LOW^}'' for the lowest possible value
8221 @item ``@option{^hi^HIGH^}'' for the highest possible value
8222 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8223 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8224 @end itemize
8225
8226 In addition, you can specify @option{-Sev} to indicate that the value is
8227 to be set at run time. In this case, the program will look for an environment
8228 @cindex GNAT_INIT_SCALARS
8229 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8230 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8231 If no environment variable is found, or if it does not have a valid value,
8232 then the default is @option{in} (invalid values).
8233
8234 @ifclear vms
8235 @item -static
8236 @cindex @option{-static} (@code{gnatbind})
8237 Link against a static GNAT run time.
8238
8239 @item -shared
8240 @cindex @option{-shared} (@code{gnatbind})
8241 Link against a shared GNAT run time when available.
8242 @end ifclear
8243
8244 @item ^-t^/NOTIME_STAMP_CHECK^
8245 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8246 Tolerate time stamp and other consistency errors
8247
8248 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8249 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8250 Set the time slice value to @var{n} milliseconds. If the system supports
8251 the specification of a specific time slice value, then the indicated value
8252 is used. If the system does not support specific time slice values, but
8253 does support some general notion of round-robin scheduling, then any
8254 nonzero value will activate round-robin scheduling.
8255
8256 A value of zero is treated specially. It turns off time
8257 slicing, and in addition, indicates to the tasking run time that the
8258 semantics should match as closely as possible the Annex D
8259 requirements of the Ada RM, and in particular sets the default
8260 scheduling policy to @code{FIFO_Within_Priorities}.
8261
8262 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8263 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8264 Enable dynamic stack usage, with @var{n} results stored and displayed
8265 at program termination. A result is generated when a task
8266 terminates. Results that can't be stored are displayed on the fly, at
8267 task termination. This option is currently not supported on Itanium
8268 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8269
8270 @item ^-v^/REPORT_ERRORS=VERBOSE^
8271 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8272 Verbose mode. Write error messages, header, summary output to
8273 @file{stdout}.
8274
8275 @ifclear vms
8276 @item -w@var{x}
8277 @cindex @option{-w} (@code{gnatbind})
8278 Warning mode (@var{x}=s/e for suppress/treat as error)
8279 @end ifclear
8280
8281 @ifset vms
8282 @item /WARNINGS=NORMAL
8283 @cindex @option{/WARNINGS} (@code{gnatbind})
8284 Normal warnings mode. Warnings are issued but ignored
8285
8286 @item /WARNINGS=SUPPRESS
8287 @cindex @option{/WARNINGS} (@code{gnatbind})
8288 All warning messages are suppressed
8289
8290 @item /WARNINGS=ERROR
8291 @cindex @option{/WARNINGS} (@code{gnatbind})
8292 Warning messages are treated as fatal errors
8293 @end ifset
8294
8295 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8296 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8297 Override default wide character encoding for standard Text_IO files.
8298
8299 @item ^-x^/READ_SOURCES=NONE^
8300 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8301 Exclude source files (check object consistency only).
8302
8303 @ifset vms
8304 @item /READ_SOURCES=AVAILABLE
8305 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8306 Default mode, in which sources are checked for consistency only if
8307 they are available.
8308 @end ifset
8309
8310 @item ^-y^/ENABLE_LEAP_SECONDS^
8311 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8312 Enable leap seconds support in @code{Ada.Calendar} and its children.
8313
8314 @item ^-z^/ZERO_MAIN^
8315 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8316 No main subprogram.
8317 @end table
8318
8319 @ifclear vms
8320 @noindent
8321 You may obtain this listing of switches by running @code{gnatbind} with
8322 no arguments.
8323 @end ifclear
8324
8325 @node Consistency-Checking Modes
8326 @subsection Consistency-Checking Modes
8327
8328 @noindent
8329 As described earlier, by default @code{gnatbind} checks
8330 that object files are consistent with one another and are consistent
8331 with any source files it can locate. The following switches control binder
8332 access to sources.
8333
8334 @table @option
8335 @c !sort!
8336 @item ^-s^/READ_SOURCES=ALL^
8337 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8338 Require source files to be present. In this mode, the binder must be
8339 able to locate all source files that are referenced, in order to check
8340 their consistency. In normal mode, if a source file cannot be located it
8341 is simply ignored. If you specify this switch, a missing source
8342 file is an error.
8343
8344 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8345 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8346 Override default wide character encoding for standard Text_IO files.
8347 Normally the default wide character encoding method used for standard
8348 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8349 the main source input (see description of switch
8350 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8351 use of this switch for the binder (which has the same set of
8352 possible arguments) overrides this default as specified.
8353
8354 @item ^-x^/READ_SOURCES=NONE^
8355 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8356 Exclude source files. In this mode, the binder only checks that ALI
8357 files are consistent with one another. Source files are not accessed.
8358 The binder runs faster in this mode, and there is still a guarantee that
8359 the resulting program is self-consistent.
8360 If a source file has been edited since it was last compiled, and you
8361 specify this switch, the binder will not detect that the object
8362 file is out of date with respect to the source file. Note that this is the
8363 mode that is automatically used by @command{gnatmake} because in this
8364 case the checking against sources has already been performed by
8365 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8366
8367 @ifset vms
8368 @item /READ_SOURCES=AVAILABLE
8369 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8370 This is the default mode in which source files are checked if they are
8371 available, and ignored if they are not available.
8372 @end ifset
8373 @end table
8374
8375 @node Binder Error Message Control
8376 @subsection Binder Error Message Control
8377
8378 @noindent
8379 The following switches provide control over the generation of error
8380 messages from the binder:
8381
8382 @table @option
8383 @c !sort!
8384 @item ^-v^/REPORT_ERRORS=VERBOSE^
8385 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8386 Verbose mode. In the normal mode, brief error messages are generated to
8387 @file{stderr}. If this switch is present, a header is written
8388 to @file{stdout} and any error messages are directed to @file{stdout}.
8389 All that is written to @file{stderr} is a brief summary message.
8390
8391 @item ^-b^/REPORT_ERRORS=BRIEF^
8392 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8393 Generate brief error messages to @file{stderr} even if verbose mode is
8394 specified. This is relevant only when used with the
8395 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8396
8397 @ifclear vms
8398 @item -m@var{n}
8399 @cindex @option{-m} (@code{gnatbind})
8400 Limits the number of error messages to @var{n}, a decimal integer in the
8401 range 1-999. The binder terminates immediately if this limit is reached.
8402
8403 @item -M@var{xxx}
8404 @cindex @option{-M} (@code{gnatbind})
8405 Renames the generated main program from @code{main} to @code{xxx}.
8406 This is useful in the case of some cross-building environments, where
8407 the actual main program is separate from the one generated
8408 by @code{gnatbind}.
8409 @end ifclear
8410
8411 @item ^-ws^/WARNINGS=SUPPRESS^
8412 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8413 @cindex Warnings
8414 Suppress all warning messages.
8415
8416 @item ^-we^/WARNINGS=ERROR^
8417 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8418 Treat any warning messages as fatal errors.
8419
8420 @ifset vms
8421 @item /WARNINGS=NORMAL
8422 Standard mode with warnings generated, but warnings do not get treated
8423 as errors.
8424 @end ifset
8425
8426 @item ^-t^/NOTIME_STAMP_CHECK^
8427 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8428 @cindex Time stamp checks, in binder
8429 @cindex Binder consistency checks
8430 @cindex Consistency checks, in binder
8431 The binder performs a number of consistency checks including:
8432
8433 @itemize @bullet
8434 @item
8435 Check that time stamps of a given source unit are consistent
8436 @item
8437 Check that checksums of a given source unit are consistent
8438 @item
8439 Check that consistent versions of @code{GNAT} were used for compilation
8440 @item
8441 Check consistency of configuration pragmas as required
8442 @end itemize
8443
8444 @noindent
8445 Normally failure of such checks, in accordance with the consistency
8446 requirements of the Ada Reference Manual, causes error messages to be
8447 generated which abort the binder and prevent the output of a binder
8448 file and subsequent link to obtain an executable.
8449
8450 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8451 into warnings, so that
8452 binding and linking can continue to completion even in the presence of such
8453 errors. The result may be a failed link (due to missing symbols), or a
8454 non-functional executable which has undefined semantics.
8455 @emph{This means that
8456 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8457 with extreme care.}
8458 @end table
8459
8460 @node Elaboration Control
8461 @subsection Elaboration Control
8462
8463 @noindent
8464 The following switches provide additional control over the elaboration
8465 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8466
8467 @table @option
8468 @item ^-p^/PESSIMISTIC_ELABORATION^
8469 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8470 Normally the binder attempts to choose an elaboration order that is
8471 likely to minimize the likelihood of an elaboration order error resulting
8472 in raising a @code{Program_Error} exception. This switch reverses the
8473 action of the binder, and requests that it deliberately choose an order
8474 that is likely to maximize the likelihood of an elaboration error.
8475 This is useful in ensuring portability and avoiding dependence on
8476 accidental fortuitous elaboration ordering.
8477
8478 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8479 switch if dynamic
8480 elaboration checking is used (@option{-gnatE} switch used for compilation).
8481 This is because in the default static elaboration mode, all necessary
8482 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8483 These implicit pragmas are still respected by the binder in
8484 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8485 safe elaboration order is assured.
8486 @end table
8487
8488 @node Output Control
8489 @subsection Output Control
8490
8491 @noindent
8492 The following switches allow additional control over the output
8493 generated by the binder.
8494
8495 @table @option
8496 @c !sort!
8497
8498 @item ^-c^/NOOUTPUT^
8499 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8500 Check only. Do not generate the binder output file. In this mode the
8501 binder performs all error checks but does not generate an output file.
8502
8503 @item ^-e^/ELABORATION_DEPENDENCIES^
8504 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8505 Output complete list of elaboration-order dependencies, showing the
8506 reason for each dependency. This output can be rather extensive but may
8507 be useful in diagnosing problems with elaboration order. The output is
8508 written to @file{stdout}.
8509
8510 @item ^-h^/HELP^
8511 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8512 Output usage information. The output is written to @file{stdout}.
8513
8514 @item ^-K^/LINKER_OPTION_LIST^
8515 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8516 Output linker options to @file{stdout}. Includes library search paths,
8517 contents of pragmas Ident and Linker_Options, and libraries added
8518 by @code{gnatbind}.
8519
8520 @item ^-l^/ORDER_OF_ELABORATION^
8521 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8522 Output chosen elaboration order. The output is written to @file{stdout}.
8523
8524 @item ^-O^/OBJECT_LIST^
8525 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8526 Output full names of all the object files that must be linked to provide
8527 the Ada component of the program. The output is written to @file{stdout}.
8528 This list includes the files explicitly supplied and referenced by the user
8529 as well as implicitly referenced run-time unit files. The latter are
8530 omitted if the corresponding units reside in shared libraries. The
8531 directory names for the run-time units depend on the system configuration.
8532
8533 @item ^-o ^/OUTPUT=^@var{file}
8534 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8535 Set name of output file to @var{file} instead of the normal
8536 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8537 binder generated body filename.
8538 Note that if this option is used, then linking must be done manually.
8539 It is not possible to use gnatlink in this case, since it cannot locate
8540 the binder file.
8541
8542 @item ^-r^/RESTRICTION_LIST^
8543 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8544 Generate list of @code{pragma Restrictions} that could be applied to
8545 the current unit. This is useful for code audit purposes, and also may
8546 be used to improve code generation in some cases.
8547
8548 @end table
8549
8550 @node Binding with Non-Ada Main Programs
8551 @subsection Binding with Non-Ada Main Programs
8552
8553 @noindent
8554 In our description so far we have assumed that the main
8555 program is in Ada, and that the task of the binder is to generate a
8556 corresponding function @code{main} that invokes this Ada main
8557 program. GNAT also supports the building of executable programs where
8558 the main program is not in Ada, but some of the called routines are
8559 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8560 The following switch is used in this situation:
8561
8562 @table @option
8563 @item ^-n^/NOMAIN^
8564 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8565 No main program. The main program is not in Ada.
8566 @end table
8567
8568 @noindent
8569 In this case, most of the functions of the binder are still required,
8570 but instead of generating a main program, the binder generates a file
8571 containing the following callable routines:
8572
8573 @table @code
8574 @item adainit
8575 @findex adainit
8576 You must call this routine to initialize the Ada part of the program by
8577 calling the necessary elaboration routines. A call to @code{adainit} is
8578 required before the first call to an Ada subprogram.
8579
8580 Note that it is assumed that the basic execution environment must be setup
8581 to be appropriate for Ada execution at the point where the first Ada
8582 subprogram is called. In particular, if the Ada code will do any
8583 floating-point operations, then the FPU must be setup in an appropriate
8584 manner. For the case of the x86, for example, full precision mode is
8585 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8586 that the FPU is in the right state.
8587
8588 @item adafinal
8589 @findex adafinal
8590 You must call this routine to perform any library-level finalization
8591 required by the Ada subprograms. A call to @code{adafinal} is required
8592 after the last call to an Ada subprogram, and before the program
8593 terminates.
8594 @end table
8595
8596 @noindent
8597 If the @option{^-n^/NOMAIN^} switch
8598 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8599 @cindex Binder, multiple input files
8600 is given, more than one ALI file may appear on
8601 the command line for @code{gnatbind}. The normal @dfn{closure}
8602 calculation is performed for each of the specified units. Calculating
8603 the closure means finding out the set of units involved by tracing
8604 @code{with} references. The reason it is necessary to be able to
8605 specify more than one ALI file is that a given program may invoke two or
8606 more quite separate groups of Ada units.
8607
8608 The binder takes the name of its output file from the last specified ALI
8609 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8610 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8611 The output is an Ada unit in source form that can be compiled with GNAT.
8612 This compilation occurs automatically as part of the @command{gnatlink}
8613 processing.
8614
8615 Currently the GNAT run time requires a FPU using 80 bits mode
8616 precision. Under targets where this is not the default it is required to
8617 call GNAT.Float_Control.Reset before using floating point numbers (this
8618 include float computation, float input and output) in the Ada code. A
8619 side effect is that this could be the wrong mode for the foreign code
8620 where floating point computation could be broken after this call.
8621
8622 @node Binding Programs with No Main Subprogram
8623 @subsection Binding Programs with No Main Subprogram
8624
8625 @noindent
8626 It is possible to have an Ada program which does not have a main
8627 subprogram. This program will call the elaboration routines of all the
8628 packages, then the finalization routines.
8629
8630 The following switch is used to bind programs organized in this manner:
8631
8632 @table @option
8633 @item ^-z^/ZERO_MAIN^
8634 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8635 Normally the binder checks that the unit name given on the command line
8636 corresponds to a suitable main subprogram. When this switch is used,
8637 a list of ALI files can be given, and the execution of the program
8638 consists of elaboration of these units in an appropriate order. Note
8639 that the default wide character encoding method for standard Text_IO
8640 files is always set to Brackets if this switch is set (you can use
8641 the binder switch
8642 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8643 @end table
8644
8645 @node Command-Line Access
8646 @section Command-Line Access
8647
8648 @noindent
8649 The package @code{Ada.Command_Line} provides access to the command-line
8650 arguments and program name. In order for this interface to operate
8651 correctly, the two variables
8652
8653 @smallexample
8654 @group
8655 int gnat_argc;
8656 char **gnat_argv;
8657 @end group
8658 @end smallexample
8659
8660 @noindent
8661 @findex gnat_argv
8662 @findex gnat_argc
8663 are declared in one of the GNAT library routines. These variables must
8664 be set from the actual @code{argc} and @code{argv} values passed to the
8665 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8666 generates the C main program to automatically set these variables.
8667 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8668 set these variables. If they are not set, the procedures in
8669 @code{Ada.Command_Line} will not be available, and any attempt to use
8670 them will raise @code{Constraint_Error}. If command line access is
8671 required, your main program must set @code{gnat_argc} and
8672 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8673 it.
8674
8675 @node Search Paths for gnatbind
8676 @section Search Paths for @code{gnatbind}
8677
8678 @noindent
8679 The binder takes the name of an ALI file as its argument and needs to
8680 locate source files as well as other ALI files to verify object consistency.
8681
8682 For source files, it follows exactly the same search rules as @command{gcc}
8683 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8684 directories searched are:
8685
8686 @enumerate
8687 @item
8688 The directory containing the ALI file named in the command line, unless
8689 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8690
8691 @item
8692 All directories specified by @option{^-I^/SEARCH^}
8693 switches on the @code{gnatbind}
8694 command line, in the order given.
8695
8696 @item
8697 @findex ADA_PRJ_OBJECTS_FILE
8698 Each of the directories listed in the text file whose name is given
8699 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8700
8701 @noindent
8702 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8703 driver when project files are used. It should not normally be set
8704 by other means.
8705
8706 @item
8707 @findex ADA_OBJECTS_PATH
8708 Each of the directories listed in the value of the
8709 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8710 @ifset unw
8711 Construct this value
8712 exactly as the @env{PATH} environment variable: a list of directory
8713 names separated by colons (semicolons when working with the NT version
8714 of GNAT).
8715 @end ifset
8716 @ifset vms
8717 Normally, define this value as a logical name containing a comma separated
8718 list of directory names.
8719
8720 This variable can also be defined by means of an environment string
8721 (an argument to the HP C exec* set of functions).
8722
8723 Logical Name:
8724 @smallexample
8725 DEFINE ANOTHER_PATH FOO:[BAG]
8726 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8727 @end smallexample
8728
8729 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8730 first, followed by the standard Ada
8731 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8732 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8733 (Text_IO, Sequential_IO, etc)
8734 instead of the standard Ada packages. Thus, in order to get the standard Ada
8735 packages by default, ADA_OBJECTS_PATH must be redefined.
8736 @end ifset
8737
8738 @item
8739 The content of the @file{ada_object_path} file which is part of the GNAT
8740 installation tree and is used to store standard libraries such as the
8741 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8742 specified.
8743 @ifclear vms
8744 @ref{Installing a library}
8745 @end ifclear
8746 @end enumerate
8747
8748 @noindent
8749 In the binder the switch @option{^-I^/SEARCH^}
8750 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8751 is used to specify both source and
8752 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8753 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8754 instead if you want to specify
8755 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8756 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8757 if you want to specify library paths
8758 only. This means that for the binder
8759 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8760 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8761 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8762 The binder generates the bind file (a C language source file) in the
8763 current working directory.
8764
8765 @findex Ada
8766 @findex System
8767 @findex Interfaces
8768 @findex GNAT
8769 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8770 children make up the GNAT Run-Time Library, together with the package
8771 GNAT and its children, which contain a set of useful additional
8772 library functions provided by GNAT. The sources for these units are
8773 needed by the compiler and are kept together in one directory. The ALI
8774 files and object files generated by compiling the RTL are needed by the
8775 binder and the linker and are kept together in one directory, typically
8776 different from the directory containing the sources. In a normal
8777 installation, you need not specify these directory names when compiling
8778 or binding. Either the environment variables or the built-in defaults
8779 cause these files to be found.
8780
8781 Besides simplifying access to the RTL, a major use of search paths is
8782 in compiling sources from multiple directories. This can make
8783 development environments much more flexible.
8784
8785 @node Examples of gnatbind Usage
8786 @section Examples of @code{gnatbind} Usage
8787
8788 @noindent
8789 This section contains a number of examples of using the GNAT binding
8790 utility @code{gnatbind}.
8791
8792 @table @code
8793 @item gnatbind hello
8794 The main program @code{Hello} (source program in @file{hello.adb}) is
8795 bound using the standard switch settings. The generated main program is
8796 @file{b~hello.adb}. This is the normal, default use of the binder.
8797
8798 @ifclear vms
8799 @item gnatbind hello -o mainprog.adb
8800 @end ifclear
8801 @ifset vms
8802 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8803 @end ifset
8804 The main program @code{Hello} (source program in @file{hello.adb}) is
8805 bound using the standard switch settings. The generated main program is
8806 @file{mainprog.adb} with the associated spec in
8807 @file{mainprog.ads}. Note that you must specify the body here not the
8808 spec. Note that if this option is used, then linking must be done manually,
8809 since gnatlink will not be able to find the generated file.
8810 @end table
8811
8812 @c ------------------------------------
8813 @node Linking Using gnatlink
8814 @chapter Linking Using @command{gnatlink}
8815 @c ------------------------------------
8816 @findex gnatlink
8817
8818 @noindent
8819 This chapter discusses @command{gnatlink}, a tool that links
8820 an Ada program and builds an executable file. This utility
8821 invokes the system linker ^(via the @command{gcc} command)^^
8822 with a correct list of object files and library references.
8823 @command{gnatlink} automatically determines the list of files and
8824 references for the Ada part of a program. It uses the binder file
8825 generated by the @command{gnatbind} to determine this list.
8826
8827 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8828 driver (see @ref{The GNAT Driver and Project Files}).
8829
8830 @menu
8831 * Running gnatlink::
8832 * Switches for gnatlink::
8833 @end menu
8834
8835 @node Running gnatlink
8836 @section Running @command{gnatlink}
8837
8838 @noindent
8839 The form of the @command{gnatlink} command is
8840
8841 @smallexample
8842 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8843 @c            @ovar{non-Ada objects} @ovar{linker options}
8844 @c Expanding @ovar macro inline (explanation in macro def comments)
8845 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8846            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8847
8848 @end smallexample
8849
8850 @noindent
8851 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8852 non-Ada objects
8853 or linker options) may be in any order, provided that no non-Ada object may
8854 be mistaken for a main @file{ALI} file.
8855 Any file name @file{F} without the @file{.ali}
8856 extension will be taken as the main @file{ALI} file if a file exists
8857 whose name is the concatenation of @file{F} and @file{.ali}.
8858
8859 @noindent
8860 @file{@var{mainprog}.ali} references the ALI file of the main program.
8861 The @file{.ali} extension of this file can be omitted. From this
8862 reference, @command{gnatlink} locates the corresponding binder file
8863 @file{b~@var{mainprog}.adb} and, using the information in this file along
8864 with the list of non-Ada objects and linker options, constructs a
8865 linker command file to create the executable.
8866
8867 The arguments other than the @command{gnatlink} switches and the main
8868 @file{ALI} file are passed to the linker uninterpreted.
8869 They typically include the names of
8870 object files for units written in other languages than Ada and any library
8871 references required to resolve references in any of these foreign language
8872 units, or in @code{Import} pragmas in any Ada units.
8873
8874 @var{linker options} is an optional list of linker specific
8875 switches.
8876 The default linker called by gnatlink is @command{gcc} which in
8877 turn calls the appropriate system linker.
8878 Standard options for the linker such as @option{-lmy_lib} or
8879 @option{-Ldir} can be added as is.
8880 For options that are not recognized by
8881 @command{gcc} as linker options, use the @command{gcc} switches
8882 @option{-Xlinker} or @option{-Wl,}.
8883 Refer to the GCC documentation for
8884 details. Here is an example showing how to generate a linker map:
8885
8886 @smallexample
8887 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8888 @end smallexample
8889
8890 Using @var{linker options} it is possible to set the program stack and
8891 heap size.
8892 @ifset unw
8893 See @ref{Setting Stack Size from gnatlink} and
8894 @ref{Setting Heap Size from gnatlink}.
8895 @end ifset
8896
8897 @command{gnatlink} determines the list of objects required by the Ada
8898 program and prepends them to the list of objects passed to the linker.
8899 @command{gnatlink} also gathers any arguments set by the use of
8900 @code{pragma Linker_Options} and adds them to the list of arguments
8901 presented to the linker.
8902
8903 @ifset vms
8904 @command{gnatlink} accepts the following types of extra files on the command
8905 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8906 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8907 handled according to their extension.
8908 @end ifset
8909
8910 @node Switches for gnatlink
8911 @section Switches for @command{gnatlink}
8912
8913 @noindent
8914 The following switches are available with the @command{gnatlink} utility:
8915
8916 @table @option
8917 @c !sort!
8918
8919 @item --version
8920 @cindex @option{--version} @command{gnatlink}
8921 Display Copyright and version, then exit disregarding all other options.
8922
8923 @item --help
8924 @cindex @option{--help} @command{gnatlink}
8925 If @option{--version} was not used, display usage, then exit disregarding
8926 all other options.
8927
8928 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8929 @cindex Command line length
8930 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8931 On some targets, the command line length is limited, and @command{gnatlink}
8932 will generate a separate file for the linker if the list of object files
8933 is too long.
8934 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8935 to be generated even if
8936 the limit is not exceeded. This is useful in some cases to deal with
8937 special situations where the command line length is exceeded.
8938
8939 @item ^-g^/DEBUG^
8940 @cindex Debugging information, including
8941 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8942 The option to include debugging information causes the Ada bind file (in
8943 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8944 @option{^-g^/DEBUG^}.
8945 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8946 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8947 Without @option{^-g^/DEBUG^}, the binder removes these files by
8948 default. The same procedure apply if a C bind file was generated using
8949 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8950 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8951
8952 @item ^-n^/NOCOMPILE^
8953 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8954 Do not compile the file generated by the binder. This may be used when
8955 a link is rerun with different options, but there is no need to recompile
8956 the binder file.
8957
8958 @item ^-v^/VERBOSE^
8959 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8960 Causes additional information to be output, including a full list of the
8961 included object files. This switch option is most useful when you want
8962 to see what set of object files are being used in the link step.
8963
8964 @item ^-v -v^/VERBOSE/VERBOSE^
8965 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8966 Very verbose mode. Requests that the compiler operate in verbose mode when
8967 it compiles the binder file, and that the system linker run in verbose mode.
8968
8969 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8970 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8971 @var{exec-name} specifies an alternate name for the generated
8972 executable program. If this switch is omitted, the executable has the same
8973 name as the main unit. For example, @code{gnatlink try.ali} creates
8974 an executable called @file{^try^TRY.EXE^}.
8975
8976 @ifclear vms
8977 @item -b @var{target}
8978 @cindex @option{-b} (@command{gnatlink})
8979 Compile your program to run on @var{target}, which is the name of a
8980 system configuration. You must have a GNAT cross-compiler built if
8981 @var{target} is not the same as your host system.
8982
8983 @item -B@var{dir}
8984 @cindex @option{-B} (@command{gnatlink})
8985 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8986 from @var{dir} instead of the default location. Only use this switch
8987 when multiple versions of the GNAT compiler are available.
8988 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8989 for further details. You would normally use the @option{-b} or
8990 @option{-V} switch instead.
8991
8992 @item --GCC=@var{compiler_name}
8993 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8994 Program used for compiling the binder file. The default is
8995 @command{gcc}. You need to use quotes around @var{compiler_name} if
8996 @code{compiler_name} contains spaces or other separator characters.
8997 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8998 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8999 inserted after your command name. Thus in the above example the compiler
9000 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9001 A limitation of this syntax is that the name and path name of the executable
9002 itself must not include any embedded spaces. If the compiler executable is
9003 different from the default one (gcc or <prefix>-gcc), then the back-end
9004 switches in the ALI file are not used to compile the binder generated source.
9005 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9006 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9007 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9008 is taken into account. However, all the additional switches are also taken
9009 into account. Thus,
9010 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9011 @option{--GCC="bar -x -y -z -t"}.
9012
9013 @item --LINK=@var{name}
9014 @cindex @option{--LINK=} (@command{gnatlink})
9015 @var{name} is the name of the linker to be invoked. This is especially
9016 useful in mixed language programs since languages such as C++ require
9017 their own linker to be used. When this switch is omitted, the default
9018 name for the linker is @command{gcc}. When this switch is used, the
9019 specified linker is called instead of @command{gcc} with exactly the same
9020 parameters that would have been passed to @command{gcc} so if the desired
9021 linker requires different parameters it is necessary to use a wrapper
9022 script that massages the parameters before invoking the real linker. It
9023 may be useful to control the exact invocation by using the verbose
9024 switch.
9025
9026 @end ifclear
9027
9028 @ifset vms
9029 @item /DEBUG=TRACEBACK
9030 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9031 This qualifier causes sufficient information to be included in the
9032 executable file to allow a traceback, but does not include the full
9033 symbol information needed by the debugger.
9034
9035 @item /IDENTIFICATION="<string>"
9036 @code{"<string>"} specifies the string to be stored in the image file
9037 identification field in the image header.
9038 It overrides any pragma @code{Ident} specified string.
9039
9040 @item /NOINHIBIT-EXEC
9041 Generate the executable file even if there are linker warnings.
9042
9043 @item /NOSTART_FILES
9044 Don't link in the object file containing the ``main'' transfer address.
9045 Used when linking with a foreign language main program compiled with an
9046 HP compiler.
9047
9048 @item /STATIC
9049 Prefer linking with object libraries over sharable images, even without
9050 /DEBUG.
9051 @end ifset
9052
9053 @end table
9054
9055 @node The GNAT Make Program gnatmake
9056 @chapter The GNAT Make Program @command{gnatmake}
9057 @findex gnatmake
9058
9059 @menu
9060 * Running gnatmake::
9061 * Switches for gnatmake::
9062 * Mode Switches for gnatmake::
9063 * Notes on the Command Line::
9064 * How gnatmake Works::
9065 * Examples of gnatmake Usage::
9066 @end menu
9067 @noindent
9068 A typical development cycle when working on an Ada program consists of
9069 the following steps:
9070
9071 @enumerate
9072 @item
9073 Edit some sources to fix bugs.
9074
9075 @item
9076 Add enhancements.
9077
9078 @item
9079 Compile all sources affected.
9080
9081 @item
9082 Rebind and relink.
9083
9084 @item
9085 Test.
9086 @end enumerate
9087
9088 @noindent
9089 The third step can be tricky, because not only do the modified files
9090 @cindex Dependency rules
9091 have to be compiled, but any files depending on these files must also be
9092 recompiled. The dependency rules in Ada can be quite complex, especially
9093 in the presence of overloading, @code{use} clauses, generics and inlined
9094 subprograms.
9095
9096 @command{gnatmake} automatically takes care of the third and fourth steps
9097 of this process. It determines which sources need to be compiled,
9098 compiles them, and binds and links the resulting object files.
9099
9100 Unlike some other Ada make programs, the dependencies are always
9101 accurately recomputed from the new sources. The source based approach of
9102 the GNAT compilation model makes this possible. This means that if
9103 changes to the source program cause corresponding changes in
9104 dependencies, they will always be tracked exactly correctly by
9105 @command{gnatmake}.
9106
9107 @node Running gnatmake
9108 @section Running @command{gnatmake}
9109
9110 @noindent
9111 The usual form of the @command{gnatmake} command is
9112
9113 @smallexample
9114 @c $ gnatmake @ovar{switches} @var{file_name}
9115 @c       @ovar{file_names} @ovar{mode_switches}
9116 @c Expanding @ovar macro inline (explanation in macro def comments)
9117 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9118       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9119 @end smallexample
9120
9121 @noindent
9122 The only required argument is one @var{file_name}, which specifies
9123 a compilation unit that is a main program. Several @var{file_names} can be
9124 specified: this will result in several executables being built.
9125 If @code{switches} are present, they can be placed before the first
9126 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9127 If @var{mode_switches} are present, they must always be placed after
9128 the last @var{file_name} and all @code{switches}.
9129
9130 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9131 extension may be omitted from the @var{file_name} arguments. However, if
9132 you are using non-standard extensions, then it is required that the
9133 extension be given. A relative or absolute directory path can be
9134 specified in a @var{file_name}, in which case, the input source file will
9135 be searched for in the specified directory only. Otherwise, the input
9136 source file will first be searched in the directory where
9137 @command{gnatmake} was invoked and if it is not found, it will be search on
9138 the source path of the compiler as described in
9139 @ref{Search Paths and the Run-Time Library (RTL)}.
9140
9141 All @command{gnatmake} output (except when you specify
9142 @option{^-M^/DEPENDENCIES_LIST^}) is to
9143 @file{stderr}. The output produced by the
9144 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9145 @file{stdout}.
9146
9147 @node Switches for gnatmake
9148 @section Switches for @command{gnatmake}
9149
9150 @noindent
9151 You may specify any of the following switches to @command{gnatmake}:
9152
9153 @table @option
9154 @c !sort!
9155
9156 @item --version
9157 @cindex @option{--version} @command{gnatmake}
9158 Display Copyright and version, then exit disregarding all other options.
9159
9160 @item --help
9161 @cindex @option{--help} @command{gnatmake}
9162 If @option{--version} was not used, display usage, then exit disregarding
9163 all other options.
9164
9165 @ifclear vms
9166 @item --GCC=@var{compiler_name}
9167 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9168 Program used for compiling. The default is `@command{gcc}'. You need to use
9169 quotes around @var{compiler_name} if @code{compiler_name} contains
9170 spaces or other separator characters. As an example @option{--GCC="foo -x
9171 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9172 compiler. A limitation of this syntax is that the name and path name of
9173 the executable itself must not include any embedded spaces. Note that
9174 switch @option{-c} is always inserted after your command name. Thus in the
9175 above example the compiler command that will be used by @command{gnatmake}
9176 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9177 used, only the last @var{compiler_name} is taken into account. However,
9178 all the additional switches are also taken into account. Thus,
9179 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9180 @option{--GCC="bar -x -y -z -t"}.
9181
9182 @item --GNATBIND=@var{binder_name}
9183 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9184 Program used for binding. The default is `@code{gnatbind}'. You need to
9185 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9186 or other separator characters. As an example @option{--GNATBIND="bar -x
9187 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9188 binder. Binder switches that are normally appended by @command{gnatmake}
9189 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9190 A limitation of this syntax is that the name and path name of the executable
9191 itself must not include any embedded spaces.
9192
9193 @item --GNATLINK=@var{linker_name}
9194 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9195 Program used for linking. The default is `@command{gnatlink}'. You need to
9196 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9197 or other separator characters. As an example @option{--GNATLINK="lan -x
9198 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9199 linker. Linker switches that are normally appended by @command{gnatmake} to
9200 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9201 A limitation of this syntax is that the name and path name of the executable
9202 itself must not include any embedded spaces.
9203
9204 @end ifclear
9205
9206 @item ^-a^/ALL_FILES^
9207 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9208 Consider all files in the make process, even the GNAT internal system
9209 files (for example, the predefined Ada library files), as well as any
9210 locked files. Locked files are files whose ALI file is write-protected.
9211 By default,
9212 @command{gnatmake} does not check these files,
9213 because the assumption is that the GNAT internal files are properly up
9214 to date, and also that any write protected ALI files have been properly
9215 installed. Note that if there is an installation problem, such that one
9216 of these files is not up to date, it will be properly caught by the
9217 binder.
9218 You may have to specify this switch if you are working on GNAT
9219 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9220 in conjunction with @option{^-f^/FORCE_COMPILE^}
9221 if you need to recompile an entire application,
9222 including run-time files, using special configuration pragmas,
9223 such as a @code{Normalize_Scalars} pragma.
9224
9225 By default
9226 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9227 internal files with
9228 @ifclear vms
9229 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9230 @end ifclear
9231 @ifset vms
9232 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9233 @end ifset
9234
9235 @item ^-b^/ACTIONS=BIND^
9236 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9237 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9238 compilation and binding, but no link.
9239 Can be combined with @option{^-l^/ACTIONS=LINK^}
9240 to do binding and linking. When not combined with
9241 @option{^-c^/ACTIONS=COMPILE^}
9242 all the units in the closure of the main program must have been previously
9243 compiled and must be up to date. The root unit specified by @var{file_name}
9244 may be given without extension, with the source extension or, if no GNAT
9245 Project File is specified, with the ALI file extension.
9246
9247 @item ^-c^/ACTIONS=COMPILE^
9248 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9249 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9250 is also specified. Do not perform linking, except if both
9251 @option{^-b^/ACTIONS=BIND^} and
9252 @option{^-l^/ACTIONS=LINK^} are also specified.
9253 If the root unit specified by @var{file_name} is not a main unit, this is the
9254 default. Otherwise @command{gnatmake} will attempt binding and linking
9255 unless all objects are up to date and the executable is more recent than
9256 the objects.
9257
9258 @item ^-C^/MAPPING^
9259 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9260 Use a temporary mapping file. A mapping file is a way to communicate
9261 to the compiler two mappings: from unit names to file names (without
9262 any directory information) and from file names to path names (with
9263 full directory information). A mapping file can make the compiler's
9264 file searches faster, especially if there are many source directories,
9265 or the sources are read over a slow network connection. If
9266 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9267 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9268 is initially populated based on the project file. If
9269 @option{^-C^/MAPPING^} is used without
9270 @option{^-P^/PROJECT_FILE^},
9271 the mapping file is initially empty. Each invocation of the compiler
9272 will add any newly accessed sources to the mapping file.
9273
9274 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9275 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9276 Use a specific mapping file. The file, specified as a path name (absolute or
9277 relative) by this switch, should already exist, otherwise the switch is
9278 ineffective. The specified mapping file will be communicated to the compiler.
9279 This switch is not compatible with a project file
9280 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9281 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9282
9283 @item ^-d^/DISPLAY_PROGRESS^
9284 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9285 Display progress for each source, up to date or not, as a single line
9286
9287 @smallexample
9288 completed x out of y (zz%)
9289 @end smallexample
9290
9291 If the file needs to be compiled this is displayed after the invocation of
9292 the compiler. These lines are displayed even in quiet output mode.
9293
9294 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9295 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9296 Put all object files and ALI file in directory @var{dir}.
9297 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9298 and ALI files go in the current working directory.
9299
9300 This switch cannot be used when using a project file.
9301
9302 @ifclear vms
9303 @item -eL
9304 @cindex @option{-eL} (@command{gnatmake})
9305 @cindex symbolic links
9306 Follow all symbolic links when processing project files.
9307 This should be used if your project uses symbolic links for files or
9308 directories, but is not needed in other cases.
9309
9310 @cindex naming scheme
9311 This also assumes that no directory matches the naming scheme for files (for
9312 instance that you do not have a directory called "sources.ads" when using the
9313 default GNAT naming scheme).
9314
9315 When you do not have to use this switch (ie by default), gnatmake is able to
9316 save a lot of system calls (several per source file and object file), which
9317 can result in a significant speed up to load and manipulate a project file,
9318 especially when using source files from a remote system.
9319
9320 @end ifclear
9321
9322 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9323 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9324 Output the commands for the compiler, the binder and the linker
9325 on ^standard output^SYS$OUTPUT^,
9326 instead of ^standard error^SYS$ERROR^.
9327
9328 @item ^-f^/FORCE_COMPILE^
9329 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9330 Force recompilations. Recompile all sources, even though some object
9331 files may be up to date, but don't recompile predefined or GNAT internal
9332 files or locked files (files with a write-protected ALI file),
9333 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9334
9335 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9336 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9337 When using project files, if some errors or warnings are detected during
9338 parsing and verbose mode is not in effect (no use of switch
9339 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9340 file, rather than its simple file name.
9341
9342 @item ^-g^/DEBUG^
9343 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9344 Enable debugging. This switch is simply passed to the compiler and to the
9345 linker.
9346
9347 @item ^-i^/IN_PLACE^
9348 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9349 In normal mode, @command{gnatmake} compiles all object files and ALI files
9350 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9351 then instead object files and ALI files that already exist are overwritten
9352 in place. This means that once a large project is organized into separate
9353 directories in the desired manner, then @command{gnatmake} will automatically
9354 maintain and update this organization. If no ALI files are found on the
9355 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9356 the new object and ALI files are created in the
9357 directory containing the source being compiled. If another organization
9358 is desired, where objects and sources are kept in different directories,
9359 a useful technique is to create dummy ALI files in the desired directories.
9360 When detecting such a dummy file, @command{gnatmake} will be forced to
9361 recompile the corresponding source file, and it will be put the resulting
9362 object and ALI files in the directory where it found the dummy file.
9363
9364 @item ^-j^/PROCESSES=^@var{n}
9365 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9366 @cindex Parallel make
9367 Use @var{n} processes to carry out the (re)compilations. On a
9368 multiprocessor machine compilations will occur in parallel. In the
9369 event of compilation errors, messages from various compilations might
9370 get interspersed (but @command{gnatmake} will give you the full ordered
9371 list of failing compiles at the end). If this is problematic, rerun
9372 the make process with n set to 1 to get a clean list of messages.
9373
9374 @item ^-k^/CONTINUE_ON_ERROR^
9375 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9376 Keep going. Continue as much as possible after a compilation error. To
9377 ease the programmer's task in case of compilation errors, the list of
9378 sources for which the compile fails is given when @command{gnatmake}
9379 terminates.
9380
9381 If @command{gnatmake} is invoked with several @file{file_names} and with this
9382 switch, if there are compilation errors when building an executable,
9383 @command{gnatmake} will not attempt to build the following executables.
9384
9385 @item ^-l^/ACTIONS=LINK^
9386 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9387 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9388 and linking. Linking will not be performed if combined with
9389 @option{^-c^/ACTIONS=COMPILE^}
9390 but not with @option{^-b^/ACTIONS=BIND^}.
9391 When not combined with @option{^-b^/ACTIONS=BIND^}
9392 all the units in the closure of the main program must have been previously
9393 compiled and must be up to date, and the main program needs to have been bound.
9394 The root unit specified by @var{file_name}
9395 may be given without extension, with the source extension or, if no GNAT
9396 Project File is specified, with the ALI file extension.
9397
9398 @item ^-m^/MINIMAL_RECOMPILATION^
9399 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9400 Specify that the minimum necessary amount of recompilations
9401 be performed. In this mode @command{gnatmake} ignores time
9402 stamp differences when the only
9403 modifications to a source file consist in adding/removing comments,
9404 empty lines, spaces or tabs. This means that if you have changed the
9405 comments in a source file or have simply reformatted it, using this
9406 switch will tell @command{gnatmake} not to recompile files that depend on it
9407 (provided other sources on which these files depend have undergone no
9408 semantic modifications). Note that the debugging information may be
9409 out of date with respect to the sources if the @option{-m} switch causes
9410 a compilation to be switched, so the use of this switch represents a
9411 trade-off between compilation time and accurate debugging information.
9412
9413 @item ^-M^/DEPENDENCIES_LIST^
9414 @cindex Dependencies, producing list
9415 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9416 Check if all objects are up to date. If they are, output the object
9417 dependences to @file{stdout} in a form that can be directly exploited in
9418 a @file{Makefile}. By default, each source file is prefixed with its
9419 (relative or absolute) directory name. This name is whatever you
9420 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9421 and @option{^-I^/SEARCH^} switches. If you use
9422 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9423 @option{^-q^/QUIET^}
9424 (see below), only the source file names,
9425 without relative paths, are output. If you just specify the
9426 @option{^-M^/DEPENDENCIES_LIST^}
9427 switch, dependencies of the GNAT internal system files are omitted. This
9428 is typically what you want. If you also specify
9429 the @option{^-a^/ALL_FILES^} switch,
9430 dependencies of the GNAT internal files are also listed. Note that
9431 dependencies of the objects in external Ada libraries (see switch
9432 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9433 are never reported.
9434
9435 @item ^-n^/DO_OBJECT_CHECK^
9436 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9437 Don't compile, bind, or link. Checks if all objects are up to date.
9438 If they are not, the full name of the first file that needs to be
9439 recompiled is printed.
9440 Repeated use of this option, followed by compiling the indicated source
9441 file, will eventually result in recompiling all required units.
9442
9443 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9444 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9445 Output executable name. The name of the final executable program will be
9446 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9447 name for the executable will be the name of the input file in appropriate form
9448 for an executable file on the host system.
9449
9450 This switch cannot be used when invoking @command{gnatmake} with several
9451 @file{file_names}.
9452
9453 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9454 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9455 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9456 automatically missing object directories, library directories and exec
9457 directories.
9458
9459 @item ^-P^/PROJECT_FILE=^@var{project}
9460 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9461 Use project file @var{project}. Only one such switch can be used.
9462 @xref{gnatmake and Project Files}.
9463
9464 @item ^-q^/QUIET^
9465 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9466 Quiet. When this flag is not set, the commands carried out by
9467 @command{gnatmake} are displayed.
9468
9469 @item ^-s^/SWITCH_CHECK/^
9470 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9471 Recompile if compiler switches have changed since last compilation.
9472 All compiler switches but -I and -o are taken into account in the
9473 following way:
9474 orders between different ``first letter'' switches are ignored, but
9475 orders between same switches are taken into account. For example,
9476 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9477 is equivalent to @option{-O -g}.
9478
9479 This switch is recommended when Integrated Preprocessing is used.
9480
9481 @item ^-u^/UNIQUE^
9482 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9483 Unique. Recompile at most the main files. It implies -c. Combined with
9484 -f, it is equivalent to calling the compiler directly. Note that using
9485 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9486 (@pxref{Project Files and Main Subprograms}).
9487
9488 @item ^-U^/ALL_PROJECTS^
9489 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9490 When used without a project file or with one or several mains on the command
9491 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9492 on the command line, all sources of all project files are checked and compiled
9493 if not up to date, and libraries are rebuilt, if necessary.
9494
9495 @item ^-v^/REASONS^
9496 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9497 Verbose. Display the reason for all recompilations @command{gnatmake}
9498 decides are necessary, with the highest verbosity level.
9499
9500 @item ^-vl^/LOW_VERBOSITY^
9501 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9502 Verbosity level Low. Display fewer lines than in verbosity Medium.
9503
9504 @item ^-vm^/MEDIUM_VERBOSITY^
9505 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9506 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9507
9508 @item ^-vh^/HIGH_VERBOSITY^
9509 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9510 Verbosity level High. Equivalent to ^-v^/REASONS^.
9511
9512 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9513 Indicate the verbosity of the parsing of GNAT project files.
9514 @xref{Switches Related to Project Files}.
9515
9516 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9517 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9518 Indicate that sources that are not part of any Project File may be compiled.
9519 Normally, when using Project Files, only sources that are part of a Project
9520 File may be compile. When this switch is used, a source outside of all Project
9521 Files may be compiled. The ALI file and the object file will be put in the
9522 object directory of the main Project. The compilation switches used will only
9523 be those specified on the command line. Even when
9524 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9525 command line need to be sources of a project file.
9526
9527 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9528 Indicate that external variable @var{name} has the value @var{value}.
9529 The Project Manager will use this value for occurrences of
9530 @code{external(name)} when parsing the project file.
9531 @xref{Switches Related to Project Files}.
9532
9533 @item ^-z^/NOMAIN^
9534 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9535 No main subprogram. Bind and link the program even if the unit name
9536 given on the command line is a package name. The resulting executable
9537 will execute the elaboration routines of the package and its closure,
9538 then the finalization routines.
9539
9540 @end table
9541
9542 @table @asis
9543 @item @command{gcc} @asis{switches}
9544 @ifclear vms
9545 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9546 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9547 @end ifclear
9548 @ifset vms
9549 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9550 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9551 automatically treated as a compiler switch, and passed on to all
9552 compilations that are carried out.
9553 @end ifset
9554 @end table
9555
9556 @noindent
9557 Source and library search path switches:
9558
9559 @table @option
9560 @c !sort!
9561 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9562 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9563 When looking for source files also look in directory @var{dir}.
9564 The order in which source files search is undertaken is
9565 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9566
9567 @item ^-aL^/SKIP_MISSING=^@var{dir}
9568 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9569 Consider @var{dir} as being an externally provided Ada library.
9570 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9571 files have been located in directory @var{dir}. This allows you to have
9572 missing bodies for the units in @var{dir} and to ignore out of date bodies
9573 for the same units. You still need to specify
9574 the location of the specs for these units by using the switches
9575 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9576 or @option{^-I^/SEARCH=^@var{dir}}.
9577 Note: this switch is provided for compatibility with previous versions
9578 of @command{gnatmake}. The easier method of causing standard libraries
9579 to be excluded from consideration is to write-protect the corresponding
9580 ALI files.
9581
9582 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9583 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9584 When searching for library and object files, look in directory
9585 @var{dir}. The order in which library files are searched is described in
9586 @ref{Search Paths for gnatbind}.
9587
9588 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9589 @cindex Search paths, for @command{gnatmake}
9590 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9591 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9592 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9593
9594 @item ^-I^/SEARCH=^@var{dir}
9595 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9596 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9597 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9598
9599 @item ^-I-^/NOCURRENT_DIRECTORY^
9600 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9601 @cindex Source files, suppressing search
9602 Do not look for source files in the directory containing the source
9603 file named in the command line.
9604 Do not look for ALI or object files in the directory
9605 where @command{gnatmake} was invoked.
9606
9607 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9608 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9609 @cindex Linker libraries
9610 Add directory @var{dir} to the list of directories in which the linker
9611 will search for libraries. This is equivalent to
9612 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9613 @ifclear vms
9614 Furthermore, under Windows, the sources pointed to by the libraries path
9615 set in the registry are not searched for.
9616 @end ifclear
9617
9618 @item -nostdinc
9619 @cindex @option{-nostdinc} (@command{gnatmake})
9620 Do not look for source files in the system default directory.
9621
9622 @item -nostdlib
9623 @cindex @option{-nostdlib} (@command{gnatmake})
9624 Do not look for library files in the system default directory.
9625
9626 @item --RTS=@var{rts-path}
9627 @cindex @option{--RTS} (@command{gnatmake})
9628 Specifies the default location of the runtime library. GNAT looks for the
9629 runtime
9630 in the following directories, and stops as soon as a valid runtime is found
9631 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9632 @file{ada_object_path} present):
9633
9634 @itemize @bullet
9635 @item <current directory>/$rts_path
9636
9637 @item <default-search-dir>/$rts_path
9638
9639 @item <default-search-dir>/rts-$rts_path
9640 @end itemize
9641
9642 @noindent
9643 The selected path is handled like a normal RTS path.
9644
9645 @end table
9646
9647 @node Mode Switches for gnatmake
9648 @section Mode Switches for @command{gnatmake}
9649
9650 @noindent
9651 The mode switches (referred to as @code{mode_switches}) allow the
9652 inclusion of switches that are to be passed to the compiler itself, the
9653 binder or the linker. The effect of a mode switch is to cause all
9654 subsequent switches up to the end of the switch list, or up to the next
9655 mode switch, to be interpreted as switches to be passed on to the
9656 designated component of GNAT.
9657
9658 @table @option
9659 @c !sort!
9660 @item -cargs @var{switches}
9661 @cindex @option{-cargs} (@command{gnatmake})
9662 Compiler switches. Here @var{switches} is a list of switches
9663 that are valid switches for @command{gcc}. They will be passed on to
9664 all compile steps performed by @command{gnatmake}.
9665
9666 @item -bargs @var{switches}
9667 @cindex @option{-bargs} (@command{gnatmake})
9668 Binder switches. Here @var{switches} is a list of switches
9669 that are valid switches for @code{gnatbind}. They will be passed on to
9670 all bind steps performed by @command{gnatmake}.
9671
9672 @item -largs @var{switches}
9673 @cindex @option{-largs} (@command{gnatmake})
9674 Linker switches. Here @var{switches} is a list of switches
9675 that are valid switches for @command{gnatlink}. They will be passed on to
9676 all link steps performed by @command{gnatmake}.
9677
9678 @item -margs @var{switches}
9679 @cindex @option{-margs} (@command{gnatmake})
9680 Make switches. The switches are directly interpreted by @command{gnatmake},
9681 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9682 or @option{-largs}.
9683 @end table
9684
9685 @node Notes on the Command Line
9686 @section Notes on the Command Line
9687
9688 @noindent
9689 This section contains some additional useful notes on the operation
9690 of the @command{gnatmake} command.
9691
9692 @itemize @bullet
9693 @item
9694 @cindex Recompilation, by @command{gnatmake}
9695 If @command{gnatmake} finds no ALI files, it recompiles the main program
9696 and all other units required by the main program.
9697 This means that @command{gnatmake}
9698 can be used for the initial compile, as well as during subsequent steps of
9699 the development cycle.
9700
9701 @item
9702 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9703 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9704 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9705 warning.
9706
9707 @item
9708 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9709 is used to specify both source and
9710 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9711 instead if you just want to specify
9712 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9713 if you want to specify library paths
9714 only.
9715
9716 @item
9717 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9718 This may conveniently be used to exclude standard libraries from
9719 consideration and in particular it means that the use of the
9720 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9721 unless @option{^-a^/ALL_FILES^} is also specified.
9722
9723 @item
9724 @command{gnatmake} has been designed to make the use of Ada libraries
9725 particularly convenient. Assume you have an Ada library organized
9726 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9727 of your Ada compilation units,
9728 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9729 specs of these units, but no bodies. Then to compile a unit
9730 stored in @code{main.adb}, which uses this Ada library you would just type
9731
9732 @smallexample
9733 @ifclear vms
9734 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9735 @end ifclear
9736 @ifset vms
9737 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9738            /SKIP_MISSING=@i{[OBJ_DIR]} main
9739 @end ifset
9740 @end smallexample
9741
9742 @item
9743 Using @command{gnatmake} along with the
9744 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9745 switch provides a mechanism for avoiding unnecessary recompilations. Using
9746 this switch,
9747 you can update the comments/format of your
9748 source files without having to recompile everything. Note, however, that
9749 adding or deleting lines in a source files may render its debugging
9750 info obsolete. If the file in question is a spec, the impact is rather
9751 limited, as that debugging info will only be useful during the
9752 elaboration phase of your program. For bodies the impact can be more
9753 significant. In all events, your debugger will warn you if a source file
9754 is more recent than the corresponding object, and alert you to the fact
9755 that the debugging information may be out of date.
9756 @end itemize
9757
9758 @node How gnatmake Works
9759 @section How @command{gnatmake} Works
9760
9761 @noindent
9762 Generally @command{gnatmake} automatically performs all necessary
9763 recompilations and you don't need to worry about how it works. However,
9764 it may be useful to have some basic understanding of the @command{gnatmake}
9765 approach and in particular to understand how it uses the results of
9766 previous compilations without incorrectly depending on them.
9767
9768 First a definition: an object file is considered @dfn{up to date} if the
9769 corresponding ALI file exists and if all the source files listed in the
9770 dependency section of this ALI file have time stamps matching those in
9771 the ALI file. This means that neither the source file itself nor any
9772 files that it depends on have been modified, and hence there is no need
9773 to recompile this file.
9774
9775 @command{gnatmake} works by first checking if the specified main unit is up
9776 to date. If so, no compilations are required for the main unit. If not,
9777 @command{gnatmake} compiles the main program to build a new ALI file that
9778 reflects the latest sources. Then the ALI file of the main unit is
9779 examined to find all the source files on which the main program depends,
9780 and @command{gnatmake} recursively applies the above procedure on all these
9781 files.
9782
9783 This process ensures that @command{gnatmake} only trusts the dependencies
9784 in an existing ALI file if they are known to be correct. Otherwise it
9785 always recompiles to determine a new, guaranteed accurate set of
9786 dependencies. As a result the program is compiled ``upside down'' from what may
9787 be more familiar as the required order of compilation in some other Ada
9788 systems. In particular, clients are compiled before the units on which
9789 they depend. The ability of GNAT to compile in any order is critical in
9790 allowing an order of compilation to be chosen that guarantees that
9791 @command{gnatmake} will recompute a correct set of new dependencies if
9792 necessary.
9793
9794 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9795 imported by several of the executables, it will be recompiled at most once.
9796
9797 Note: when using non-standard naming conventions
9798 (@pxref{Using Other File Names}), changing through a configuration pragmas
9799 file the version of a source and invoking @command{gnatmake} to recompile may
9800 have no effect, if the previous version of the source is still accessible
9801 by @command{gnatmake}. It may be necessary to use the switch
9802 ^-f^/FORCE_COMPILE^.
9803
9804 @node Examples of gnatmake Usage
9805 @section Examples of @command{gnatmake} Usage
9806
9807 @table @code
9808 @item gnatmake hello.adb
9809 Compile all files necessary to bind and link the main program
9810 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9811 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9812
9813 @item gnatmake main1 main2 main3
9814 Compile all files necessary to bind and link the main programs
9815 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9816 (containing unit @code{Main2}) and @file{main3.adb}
9817 (containing unit @code{Main3}) and bind and link the resulting object files
9818 to generate three executable files @file{^main1^MAIN1.EXE^},
9819 @file{^main2^MAIN2.EXE^}
9820 and @file{^main3^MAIN3.EXE^}.
9821
9822 @ifclear vms
9823 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9824 @end ifclear
9825
9826 @ifset vms
9827 @item gnatmake Main_Unit /QUIET
9828 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9829 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9830 @end ifset
9831 Compile all files necessary to bind and link the main program unit
9832 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9833 be done with optimization level 2 and the order of elaboration will be
9834 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9835 displaying commands it is executing.
9836 @end table
9837
9838 @c *************************
9839 @node Improving Performance
9840 @chapter Improving Performance
9841 @cindex Improving performance
9842
9843 @noindent
9844 This chapter presents several topics related to program performance.
9845 It first describes some of the tradeoffs that need to be considered
9846 and some of the techniques for making your program run faster.
9847 It then documents the @command{gnatelim} tool and unused subprogram/data
9848 elimination feature, which can reduce the size of program executables.
9849
9850 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9851 driver (see @ref{The GNAT Driver and Project Files}).
9852
9853 @ifnottex
9854 @menu
9855 * Performance Considerations::
9856 * Text_IO Suggestions::
9857 * Reducing Size of Ada Executables with gnatelim::
9858 * Reducing Size of Executables with unused subprogram/data elimination::
9859 @end menu
9860 @end ifnottex
9861
9862 @c *****************************
9863 @node Performance Considerations
9864 @section Performance Considerations
9865
9866 @noindent
9867 The GNAT system provides a number of options that allow a trade-off
9868 between
9869
9870 @itemize @bullet
9871 @item
9872 performance of the generated code
9873
9874 @item
9875 speed of compilation
9876
9877 @item
9878 minimization of dependences and recompilation
9879
9880 @item
9881 the degree of run-time checking.
9882 @end itemize
9883
9884 @noindent
9885 The defaults (if no options are selected) aim at improving the speed
9886 of compilation and minimizing dependences, at the expense of performance
9887 of the generated code:
9888
9889 @itemize @bullet
9890 @item
9891 no optimization
9892
9893 @item
9894 no inlining of subprogram calls
9895
9896 @item
9897 all run-time checks enabled except overflow and elaboration checks
9898 @end itemize
9899
9900 @noindent
9901 These options are suitable for most program development purposes. This
9902 chapter describes how you can modify these choices, and also provides
9903 some guidelines on debugging optimized code.
9904
9905 @menu
9906 * Controlling Run-Time Checks::
9907 * Use of Restrictions::
9908 * Optimization Levels::
9909 * Debugging Optimized Code::
9910 * Inlining of Subprograms::
9911 * Other Optimization Switches::
9912 * Optimization and Strict Aliasing::
9913
9914 @ifset vms
9915 * Coverage Analysis::
9916 @end ifset
9917 @end menu
9918
9919 @node Controlling Run-Time Checks
9920 @subsection Controlling Run-Time Checks
9921
9922 @noindent
9923 By default, GNAT generates all run-time checks, except integer overflow
9924 checks, stack overflow checks, and checks for access before elaboration on
9925 subprogram calls. The latter are not required in default mode, because all
9926 necessary checking is done at compile time.
9927 @cindex @option{-gnatp} (@command{gcc})
9928 @cindex @option{-gnato} (@command{gcc})
9929 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9930 be modified. @xref{Run-Time Checks}.
9931
9932 Our experience is that the default is suitable for most development
9933 purposes.
9934
9935 We treat integer overflow specially because these
9936 are quite expensive and in our experience are not as important as other
9937 run-time checks in the development process. Note that division by zero
9938 is not considered an overflow check, and divide by zero checks are
9939 generated where required by default.
9940
9941 Elaboration checks are off by default, and also not needed by default, since
9942 GNAT uses a static elaboration analysis approach that avoids the need for
9943 run-time checking. This manual contains a full chapter discussing the issue
9944 of elaboration checks, and if the default is not satisfactory for your use,
9945 you should read this chapter.
9946
9947 For validity checks, the minimal checks required by the Ada Reference
9948 Manual (for case statements and assignments to array elements) are on
9949 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9950 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9951 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9952 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9953 are also suppressed entirely if @option{-gnatp} is used.
9954
9955 @cindex Overflow checks
9956 @cindex Checks, overflow
9957 @findex Suppress
9958 @findex Unsuppress
9959 @cindex pragma Suppress
9960 @cindex pragma Unsuppress
9961 Note that the setting of the switches controls the default setting of
9962 the checks. They may be modified using either @code{pragma Suppress} (to
9963 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9964 checks) in the program source.
9965
9966 @node Use of Restrictions
9967 @subsection Use of Restrictions
9968
9969 @noindent
9970 The use of pragma Restrictions allows you to control which features are
9971 permitted in your program. Apart from the obvious point that if you avoid
9972 relatively expensive features like finalization (enforceable by the use
9973 of pragma Restrictions (No_Finalization), the use of this pragma does not
9974 affect the generated code in most cases.
9975
9976 One notable exception to this rule is that the possibility of task abort
9977 results in some distributed overhead, particularly if finalization or
9978 exception handlers are used. The reason is that certain sections of code
9979 have to be marked as non-abortable.
9980
9981 If you use neither the @code{abort} statement, nor asynchronous transfer
9982 of control (@code{select @dots{} then abort}), then this distributed overhead
9983 is removed, which may have a general positive effect in improving
9984 overall performance.  Especially code involving frequent use of tasking
9985 constructs and controlled types will show much improved performance.
9986 The relevant restrictions pragmas are
9987
9988 @smallexample @c ada
9989    pragma Restrictions (No_Abort_Statements);
9990    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9991 @end smallexample
9992
9993 @noindent
9994 It is recommended that these restriction pragmas be used if possible. Note
9995 that this also means that you can write code without worrying about the
9996 possibility of an immediate abort at any point.
9997
9998 @node Optimization Levels
9999 @subsection Optimization Levels
10000 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10001
10002 @noindent
10003 Without any optimization ^option,^qualifier,^
10004 the compiler's goal is to reduce the cost of
10005 compilation and to make debugging produce the expected results.
10006 Statements are independent: if you stop the program with a breakpoint between
10007 statements, you can then assign a new value to any variable or change
10008 the program counter to any other statement in the subprogram and get exactly
10009 the results you would expect from the source code.
10010
10011 Turning on optimization makes the compiler attempt to improve the
10012 performance and/or code size at the expense of compilation time and
10013 possibly the ability to debug the program.
10014
10015 If you use multiple
10016 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10017 the last such option is the one that is effective.
10018
10019 @noindent
10020 The default is optimization off. This results in the fastest compile
10021 times, but GNAT makes absolutely no attempt to optimize, and the
10022 generated programs are considerably larger and slower than when
10023 optimization is enabled. You can use the
10024 @ifclear vms
10025 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10026 @option{-O2}, @option{-O3}, and @option{-Os})
10027 @end ifclear
10028 @ifset vms
10029 @code{OPTIMIZE} qualifier
10030 @end ifset
10031 to @command{gcc} to control the optimization level:
10032
10033 @table @option
10034 @item ^-O0^/OPTIMIZE=NONE^
10035 No optimization (the default);
10036 generates unoptimized code but has
10037 the fastest compilation time.
10038
10039 Note that many other compilers do fairly extensive optimization
10040 even if ``no optimization'' is specified. With gcc, it is
10041 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10042 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10043 really does mean no optimization at all. This difference between
10044 gcc and other compilers should be kept in mind when doing
10045 performance comparisons.
10046
10047 @item ^-O1^/OPTIMIZE=SOME^
10048 Moderate optimization;
10049 optimizes reasonably well but does not
10050 degrade compilation time significantly.
10051
10052 @item ^-O2^/OPTIMIZE=ALL^
10053 @ifset vms
10054 @itemx /OPTIMIZE=DEVELOPMENT
10055 @end ifset
10056 Full optimization;
10057 generates highly optimized code and has
10058 the slowest compilation time.
10059
10060 @item ^-O3^/OPTIMIZE=INLINING^
10061 Full optimization as in @option{-O2},
10062 and also attempts automatic inlining of small
10063 subprograms within a unit (@pxref{Inlining of Subprograms}).
10064
10065 @item ^-Os^/OPTIMIZE=SPACE^
10066 Optimize space usage of resulting program.
10067 @end table
10068
10069 @noindent
10070 Higher optimization levels perform more global transformations on the
10071 program and apply more expensive analysis algorithms in order to generate
10072 faster and more compact code. The price in compilation time, and the
10073 resulting improvement in execution time,
10074 both depend on the particular application and the hardware environment.
10075 You should experiment to find the best level for your application.
10076
10077 Since the precise set of optimizations done at each level will vary from
10078 release to release (and sometime from target to target), it is best to think
10079 of the optimization settings in general terms.
10080 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10081 the GNU Compiler Collection (GCC)}, for details about
10082 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10083 individually enable or disable specific optimizations.
10084
10085 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10086 been tested extensively at all optimization levels. There are some bugs
10087 which appear only with optimization turned on, but there have also been
10088 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10089 level of optimization does not improve the reliability of the code
10090 generator, which in practice is highly reliable at all optimization
10091 levels.
10092
10093 Note regarding the use of @option{-O3}: The use of this optimization level
10094 is generally discouraged with GNAT, since it often results in larger
10095 executables which run more slowly. See further discussion of this point
10096 in @ref{Inlining of Subprograms}.
10097
10098 @node Debugging Optimized Code
10099 @subsection Debugging Optimized Code
10100 @cindex Debugging optimized code
10101 @cindex Optimization and debugging
10102
10103 @noindent
10104 Although it is possible to do a reasonable amount of debugging at
10105 @ifclear vms
10106 nonzero optimization levels,
10107 the higher the level the more likely that
10108 @end ifclear
10109 @ifset vms
10110 @option{/OPTIMIZE} settings other than @code{NONE},
10111 such settings will make it more likely that
10112 @end ifset
10113 source-level constructs will have been eliminated by optimization.
10114 For example, if a loop is strength-reduced, the loop
10115 control variable may be completely eliminated and thus cannot be
10116 displayed in the debugger.
10117 This can only happen at @option{-O2} or @option{-O3}.
10118 Explicit temporary variables that you code might be eliminated at
10119 ^level^setting^ @option{-O1} or higher.
10120
10121 The use of the @option{^-g^/DEBUG^} switch,
10122 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10123 which is needed for source-level debugging,
10124 affects the size of the program executable on disk,
10125 and indeed the debugging information can be quite large.
10126 However, it has no effect on the generated code (and thus does not
10127 degrade performance)
10128
10129 Since the compiler generates debugging tables for a compilation unit before
10130 it performs optimizations, the optimizing transformations may invalidate some
10131 of the debugging data.  You therefore need to anticipate certain
10132 anomalous situations that may arise while debugging optimized code.
10133 These are the most common cases:
10134
10135 @enumerate
10136 @item
10137 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10138 commands show
10139 the PC bouncing back and forth in the code.  This may result from any of
10140 the following optimizations:
10141
10142 @itemize @bullet
10143 @item
10144 @i{Common subexpression elimination:} using a single instance of code for a
10145 quantity that the source computes several times.  As a result you
10146 may not be able to stop on what looks like a statement.
10147
10148 @item
10149 @i{Invariant code motion:} moving an expression that does not change within a
10150 loop, to the beginning of the loop.
10151
10152 @item
10153 @i{Instruction scheduling:} moving instructions so as to
10154 overlap loads and stores (typically) with other code, or in
10155 general to move computations of values closer to their uses. Often
10156 this causes you to pass an assignment statement without the assignment
10157 happening and then later bounce back to the statement when the
10158 value is actually needed.  Placing a breakpoint on a line of code
10159 and then stepping over it may, therefore, not always cause all the
10160 expected side-effects.
10161 @end itemize
10162
10163 @item
10164 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10165 two identical pieces of code are merged and the program counter suddenly
10166 jumps to a statement that is not supposed to be executed, simply because
10167 it (and the code following) translates to the same thing as the code
10168 that @emph{was} supposed to be executed.  This effect is typically seen in
10169 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10170 a @code{break} in a C @code{^switch^switch^} statement.
10171
10172 @item
10173 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10174 There are various reasons for this effect:
10175
10176 @itemize @bullet
10177 @item
10178 In a subprogram prologue, a parameter may not yet have been moved to its
10179 ``home''.
10180
10181 @item
10182 A variable may be dead, and its register re-used.  This is
10183 probably the most common cause.
10184
10185 @item
10186 As mentioned above, the assignment of a value to a variable may
10187 have been moved.
10188
10189 @item
10190 A variable may be eliminated entirely by value propagation or
10191 other means.  In this case, GCC may incorrectly generate debugging
10192 information for the variable
10193 @end itemize
10194
10195 @noindent
10196 In general, when an unexpected value appears for a local variable or parameter
10197 you should first ascertain if that value was actually computed by
10198 your program, as opposed to being incorrectly reported by the debugger.
10199 Record fields or
10200 array elements in an object designated by an access value
10201 are generally less of a problem, once you have ascertained that the access
10202 value is sensible.
10203 Typically, this means checking variables in the preceding code and in the
10204 calling subprogram to verify that the value observed is explainable from other
10205 values (one must apply the procedure recursively to those
10206 other values); or re-running the code and stopping a little earlier
10207 (perhaps before the call) and stepping to better see how the variable obtained
10208 the value in question; or continuing to step @emph{from} the point of the
10209 strange value to see if code motion had simply moved the variable's
10210 assignments later.
10211 @end enumerate
10212
10213 @noindent
10214 In light of such anomalies, a recommended technique is to use @option{-O0}
10215 early in the software development cycle, when extensive debugging capabilities
10216 are most needed, and then move to @option{-O1} and later @option{-O2} as
10217 the debugger becomes less critical.
10218 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10219 a release management issue.
10220 @ifclear vms
10221 Note that if you use @option{-g} you can then use the @command{strip} program
10222 on the resulting executable,
10223 which removes both debugging information and global symbols.
10224 @end ifclear
10225
10226 @node Inlining of Subprograms
10227 @subsection Inlining of Subprograms
10228
10229 @noindent
10230 A call to a subprogram in the current unit is inlined if all the
10231 following conditions are met:
10232
10233 @itemize @bullet
10234 @item
10235 The optimization level is at least @option{-O1}.
10236
10237 @item
10238 The called subprogram is suitable for inlining: It must be small enough
10239 and not contain something that @command{gcc} cannot support in inlined
10240 subprograms.
10241
10242 @item
10243 @cindex pragma Inline
10244 @findex Inline
10245 Either @code{pragma Inline} applies to the subprogram, or it is local
10246 to the unit and called once from within it, or it is small and automatic
10247 inlining (optimization level @option{-O3}) is specified.
10248 @end itemize
10249
10250 @noindent
10251 Calls to subprograms in @code{with}'ed units are normally not inlined.
10252 To achieve actual inlining (that is, replacement of the call by the code
10253 in the body of the subprogram), the following conditions must all be true.
10254
10255 @itemize @bullet
10256 @item
10257 The optimization level is at least @option{-O1}.
10258
10259 @item
10260 The called subprogram is suitable for inlining: It must be small enough
10261 and not contain something that @command{gcc} cannot support in inlined
10262 subprograms.
10263
10264 @item
10265 The call appears in a body (not in a package spec).
10266
10267 @item
10268 There is a @code{pragma Inline} for the subprogram.
10269
10270 @item
10271 @cindex @option{-gnatn} (@command{gcc})
10272 The @option{^-gnatn^/INLINE^} switch
10273 is used in the @command{gcc} command line
10274 @end itemize
10275
10276 Even if all these conditions are met, it may not be possible for
10277 the compiler to inline the call, due to the length of the body,
10278 or features in the body that make it impossible for the compiler
10279 to do the inlining.
10280
10281 Note that specifying the @option{-gnatn} switch causes additional
10282 compilation dependencies. Consider the following:
10283
10284 @smallexample @c ada
10285 @cartouche
10286 package R is
10287    procedure Q;
10288    pragma Inline (Q);
10289 end R;
10290 package body R is
10291    @dots{}
10292 end R;
10293
10294 with R;
10295 procedure Main is
10296 begin
10297    @dots{}
10298    R.Q;
10299 end Main;
10300 @end cartouche
10301 @end smallexample
10302
10303 @noindent
10304 With the default behavior (no @option{-gnatn} switch specified), the
10305 compilation of the @code{Main} procedure depends only on its own source,
10306 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10307 means that editing the body of @code{R} does not require recompiling
10308 @code{Main}.
10309
10310 On the other hand, the call @code{R.Q} is not inlined under these
10311 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10312 is compiled, the call will be inlined if the body of @code{Q} is small
10313 enough, but now @code{Main} depends on the body of @code{R} in
10314 @file{r.adb} as well as on the spec. This means that if this body is edited,
10315 the main program must be recompiled. Note that this extra dependency
10316 occurs whether or not the call is in fact inlined by @command{gcc}.
10317
10318 The use of front end inlining with @option{-gnatN} generates similar
10319 additional dependencies.
10320
10321 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10322 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10323 can be used to prevent
10324 all inlining. This switch overrides all other conditions and ensures
10325 that no inlining occurs. The extra dependences resulting from
10326 @option{-gnatn} will still be active, even if
10327 this switch is used to suppress the resulting inlining actions.
10328
10329 @cindex @option{-fno-inline-functions} (@command{gcc})
10330 Note: The @option{-fno-inline-functions} switch can be used to prevent
10331 automatic inlining of small subprograms if @option{-O3} is used.
10332
10333 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10334 Note: The @option{-fno-inline-functions-called-once} switch
10335 can be used to prevent inlining of subprograms local to the unit
10336 and called once from within it if @option{-O1} is used.
10337
10338 Note regarding the use of @option{-O3}: There is no difference in inlining
10339 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10340 pragma @code{Inline} assuming the use of @option{-gnatn}
10341 or @option{-gnatN} (the switches that activate inlining). If you have used
10342 pragma @code{Inline} in appropriate cases, then it is usually much better
10343 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10344 in this case only has the effect of inlining subprograms you did not
10345 think should be inlined. We often find that the use of @option{-O3} slows
10346 down code by performing excessive inlining, leading to increased instruction
10347 cache pressure from the increased code size. So the bottom line here is
10348 that you should not automatically assume that @option{-O3} is better than
10349 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10350 it actually improves performance.
10351
10352 @node Other Optimization Switches
10353 @subsection Other Optimization Switches
10354 @cindex Optimization Switches
10355
10356 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10357 @command{gcc} optimization switches are potentially usable. These switches
10358 have not been extensively tested with GNAT but can generally be expected
10359 to work. Examples of switches in this category are
10360 @option{-funroll-loops} and
10361 the various target-specific @option{-m} options (in particular, it has been
10362 observed that @option{-march=pentium4} can significantly improve performance
10363 on appropriate machines). For full details of these switches, see
10364 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10365 the GNU Compiler Collection (GCC)}.
10366
10367 @node Optimization and Strict Aliasing
10368 @subsection Optimization and Strict Aliasing
10369 @cindex Aliasing
10370 @cindex Strict Aliasing
10371 @cindex No_Strict_Aliasing
10372
10373 @noindent
10374 The strong typing capabilities of Ada allow an optimizer to generate
10375 efficient code in situations where other languages would be forced to
10376 make worst case assumptions preventing such optimizations. Consider
10377 the following example:
10378
10379 @smallexample @c ada
10380 @cartouche
10381 procedure R is
10382    type Int1 is new Integer;
10383    type Int2 is new Integer;
10384    type Int1A is access Int1;
10385    type Int2A is access Int2;
10386    Int1V : Int1A;
10387    Int2V : Int2A;
10388    @dots{}
10389
10390 begin
10391    @dots{}
10392    for J in Data'Range loop
10393       if Data (J) = Int1V.all then
10394          Int2V.all := Int2V.all + 1;
10395       end if;
10396    end loop;
10397    @dots{}
10398 end R;
10399 @end cartouche
10400 @end smallexample
10401
10402 @noindent
10403 In this example, since the variable @code{Int1V} can only access objects
10404 of type @code{Int1}, and @code{Int2V} can only access objects of type
10405 @code{Int2}, there is no possibility that the assignment to
10406 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10407 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10408 for all iterations of the loop and avoid the extra memory reference
10409 required to dereference it each time through the loop.
10410
10411 This kind of optimization, called strict aliasing analysis, is
10412 triggered by specifying an optimization level of @option{-O2} or
10413 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10414 when access values are involved.
10415
10416 However, although this optimization is always correct in terms of
10417 the formal semantics of the Ada Reference Manual, difficulties can
10418 arise if features like @code{Unchecked_Conversion} are used to break
10419 the typing system. Consider the following complete program example:
10420
10421 @smallexample @c ada
10422 @cartouche
10423 package p1 is
10424    type int1 is new integer;
10425    type int2 is new integer;
10426    type a1 is access int1;
10427    type a2 is access int2;
10428 end p1;
10429
10430 with p1; use p1;
10431 package p2 is
10432    function to_a2 (Input : a1) return a2;
10433 end p2;
10434
10435 with Unchecked_Conversion;
10436 package body p2 is
10437    function to_a2 (Input : a1) return a2 is
10438       function to_a2u is
10439         new Unchecked_Conversion (a1, a2);
10440    begin
10441       return to_a2u (Input);
10442    end to_a2;
10443 end p2;
10444
10445 with p2; use p2;
10446 with p1; use p1;
10447 with Text_IO; use Text_IO;
10448 procedure m is
10449    v1 : a1 := new int1;
10450    v2 : a2 := to_a2 (v1);
10451 begin
10452    v1.all := 1;
10453    v2.all := 0;
10454    put_line (int1'image (v1.all));
10455 end;
10456 @end cartouche
10457 @end smallexample
10458
10459 @noindent
10460 This program prints out 0 in @option{-O0} or @option{-O1}
10461 mode, but it prints out 1 in @option{-O2} mode. That's
10462 because in strict aliasing mode, the compiler can and
10463 does assume that the assignment to @code{v2.all} could not
10464 affect the value of @code{v1.all}, since different types
10465 are involved.
10466
10467 This behavior is not a case of non-conformance with the standard, since
10468 the Ada RM specifies that an unchecked conversion where the resulting
10469 bit pattern is not a correct value of the target type can result in an
10470 abnormal value and attempting to reference an abnormal value makes the
10471 execution of a program erroneous.  That's the case here since the result
10472 does not point to an object of type @code{int2}.  This means that the
10473 effect is entirely unpredictable.
10474
10475 However, although that explanation may satisfy a language
10476 lawyer, in practice an applications programmer expects an
10477 unchecked conversion involving pointers to create true
10478 aliases and the behavior of printing 1 seems plain wrong.
10479 In this case, the strict aliasing optimization is unwelcome.
10480
10481 Indeed the compiler recognizes this possibility, and the
10482 unchecked conversion generates a warning:
10483
10484 @smallexample
10485 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10486 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10487 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10488 @end smallexample
10489
10490 @noindent
10491 Unfortunately the problem is recognized when compiling the body of
10492 package @code{p2}, but the actual "bad" code is generated while
10493 compiling the body of @code{m} and this latter compilation does not see
10494 the suspicious @code{Unchecked_Conversion}.
10495
10496 As implied by the warning message, there are approaches you can use to
10497 avoid the unwanted strict aliasing optimization in a case like this.
10498
10499 One possibility is to simply avoid the use of @option{-O2}, but
10500 that is a bit drastic, since it throws away a number of useful
10501 optimizations that do not involve strict aliasing assumptions.
10502
10503 A less drastic approach is to compile the program using the
10504 option @option{-fno-strict-aliasing}. Actually it is only the
10505 unit containing the dereferencing of the suspicious pointer
10506 that needs to be compiled. So in this case, if we compile
10507 unit @code{m} with this switch, then we get the expected
10508 value of zero printed. Analyzing which units might need
10509 the switch can be painful, so a more reasonable approach
10510 is to compile the entire program with options @option{-O2}
10511 and @option{-fno-strict-aliasing}. If the performance is
10512 satisfactory with this combination of options, then the
10513 advantage is that the entire issue of possible "wrong"
10514 optimization due to strict aliasing is avoided.
10515
10516 To avoid the use of compiler switches, the configuration
10517 pragma @code{No_Strict_Aliasing} with no parameters may be
10518 used to specify that for all access types, the strict
10519 aliasing optimization should be suppressed.
10520
10521 However, these approaches are still overkill, in that they causes
10522 all manipulations of all access values to be deoptimized. A more
10523 refined approach is to concentrate attention on the specific
10524 access type identified as problematic.
10525
10526 First, if a careful analysis of uses of the pointer shows
10527 that there are no possible problematic references, then
10528 the warning can be suppressed by bracketing the
10529 instantiation of @code{Unchecked_Conversion} to turn
10530 the warning off:
10531
10532 @smallexample @c ada
10533    pragma Warnings (Off);
10534    function to_a2u is
10535      new Unchecked_Conversion (a1, a2);
10536    pragma Warnings (On);
10537 @end smallexample
10538
10539 @noindent
10540 Of course that approach is not appropriate for this particular
10541 example, since indeed there is a problematic reference. In this
10542 case we can take one of two other approaches.
10543
10544 The first possibility is to move the instantiation of unchecked
10545 conversion to the unit in which the type is declared. In
10546 this example, we would move the instantiation of
10547 @code{Unchecked_Conversion} from the body of package
10548 @code{p2} to the spec of package @code{p1}. Now the
10549 warning disappears. That's because any use of the
10550 access type knows there is a suspicious unchecked
10551 conversion, and the strict aliasing optimization
10552 is automatically suppressed for the type.
10553
10554 If it is not practical to move the unchecked conversion to the same unit
10555 in which the destination access type is declared (perhaps because the
10556 source type is not visible in that unit), you may use pragma
10557 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10558 same declarative sequence as the declaration of the access type:
10559
10560 @smallexample @c ada
10561    type a2 is access int2;
10562    pragma No_Strict_Aliasing (a2);
10563 @end smallexample
10564
10565 @noindent
10566 Here again, the compiler now knows that the strict aliasing optimization
10567 should be suppressed for any reference to type @code{a2} and the
10568 expected behavior is obtained.
10569
10570 Finally, note that although the compiler can generate warnings for
10571 simple cases of unchecked conversions, there are tricker and more
10572 indirect ways of creating type incorrect aliases which the compiler
10573 cannot detect. Examples are the use of address overlays and unchecked
10574 conversions involving composite types containing access types as
10575 components. In such cases, no warnings are generated, but there can
10576 still be aliasing problems. One safe coding practice is to forbid the
10577 use of address clauses for type overlaying, and to allow unchecked
10578 conversion only for primitive types. This is not really a significant
10579 restriction since any possible desired effect can be achieved by
10580 unchecked conversion of access values.
10581
10582 The aliasing analysis done in strict aliasing mode can certainly
10583 have significant benefits. We have seen cases of large scale
10584 application code where the time is increased by up to 5% by turning
10585 this optimization off. If you have code that includes significant
10586 usage of unchecked conversion, you might want to just stick with
10587 @option{-O1} and avoid the entire issue. If you get adequate
10588 performance at this level of optimization level, that's probably
10589 the safest approach. If tests show that you really need higher
10590 levels of optimization, then you can experiment with @option{-O2}
10591 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10592 has on size and speed of the code. If you really need to use
10593 @option{-O2} with strict aliasing in effect, then you should
10594 review any uses of unchecked conversion of access types,
10595 particularly if you are getting the warnings described above.
10596
10597 @ifset vms
10598 @node Coverage Analysis
10599 @subsection Coverage Analysis
10600
10601 @noindent
10602 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10603 the user to determine the distribution of execution time across a program,
10604 @pxref{Profiling} for details of usage.
10605 @end ifset
10606
10607
10608 @node Text_IO Suggestions
10609 @section @code{Text_IO} Suggestions
10610 @cindex @code{Text_IO} and performance
10611
10612 @noindent
10613 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10614 the requirement of maintaining page and line counts. If performance
10615 is critical, a recommendation is to use @code{Stream_IO} instead of
10616 @code{Text_IO} for volume output, since this package has less overhead.
10617
10618 If @code{Text_IO} must be used, note that by default output to the standard
10619 output and standard error files is unbuffered (this provides better
10620 behavior when output statements are used for debugging, or if the
10621 progress of a program is observed by tracking the output, e.g. by
10622 using the Unix @command{tail -f} command to watch redirected output.
10623
10624 If you are generating large volumes of output with @code{Text_IO} and
10625 performance is an important factor, use a designated file instead
10626 of the standard output file, or change the standard output file to
10627 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10628
10629
10630
10631 @node Reducing Size of Ada Executables with gnatelim
10632 @section Reducing Size of Ada Executables with @code{gnatelim}
10633 @findex gnatelim
10634
10635 @noindent
10636 This section describes @command{gnatelim}, a tool which detects unused
10637 subprograms and helps the compiler to create a smaller executable for your
10638 program.
10639
10640 @menu
10641 * About gnatelim::
10642 * Running gnatelim::
10643 * Processing Precompiled Libraries::
10644 * Correcting the List of Eliminate Pragmas::
10645 * Making Your Executables Smaller::
10646 * Summary of the gnatelim Usage Cycle::
10647 @end menu
10648
10649 @node About gnatelim
10650 @subsection About @code{gnatelim}
10651
10652 @noindent
10653 When a program shares a set of Ada
10654 packages with other programs, it may happen that this program uses
10655 only a fraction of the subprograms defined in these packages. The code
10656 created for these unused subprograms increases the size of the executable.
10657
10658 @code{gnatelim} tracks unused subprograms in an Ada program and
10659 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10660 subprograms that are declared but never called. By placing the list of
10661 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10662 recompiling your program, you may decrease the size of its executable,
10663 because the compiler will not generate the code for 'eliminated' subprograms.
10664 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10665 information about this pragma.
10666
10667 @code{gnatelim} needs as its input data the name of the main subprogram.
10668
10669 If a set of source files is specified as @code{gnatelim} arguments, it
10670 treats these files as a complete set of sources making up a program to
10671 analyse, and analyses only these sources.
10672
10673 After a full successful build of the main subprogram @code{gnatelim} can be
10674 called without  specifying sources to analyse, in this case it computes
10675 the source closure of the main unit from the @file{ALI} files.
10676
10677 The following command will create the set of @file{ALI} files needed for
10678 @code{gnatelim}:
10679
10680 @smallexample
10681 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10682 @end smallexample
10683
10684 Note that @code{gnatelim} does not need object files.
10685
10686 @node Running gnatelim
10687 @subsection Running @code{gnatelim}
10688
10689 @noindent
10690 @code{gnatelim} has the following command-line interface:
10691
10692 @smallexample
10693 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10694 @end smallexample
10695
10696 @noindent
10697 @var{main_unit_name} should be a name of a source file that contains the main
10698 subprogram of a program (partition).
10699
10700 Each @var{filename} is the name (including the extension) of a source
10701 file to process. ``Wildcards'' are allowed, and
10702 the file name may contain path information.
10703
10704 @samp{@var{gcc_switches}} is a list of switches for
10705 @command{gcc}. They will be passed on to all compiler invocations made by
10706 @command{gnatelim} to generate the ASIS trees. Here you can provide
10707 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10708 use the @option{-gnatec} switch to set the configuration file etc.
10709
10710 @code{gnatelim} has the following switches:
10711
10712 @table @option
10713 @c !sort!
10714 @item ^-files^/FILES^=@var{filename}
10715 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10716 Take the argument source files from the specified file. This file should be an
10717 ordinary text file containing file names separated by spaces or
10718 line breaks. You can use this switch more than once in the same call to
10719 @command{gnatelim}. You also can combine this switch with
10720 an explicit list of files.
10721
10722 @item ^-log^/LOG^
10723 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10724 Duplicate all the output sent to @file{stderr} into a log file. The log file
10725 is named @file{gnatelim.log} and is located in the current directory.
10726
10727 @item ^-log^/LOGFILE^=@var{filename}
10728 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10729 Duplicate all the output sent to @file{stderr} into a specified log file.
10730
10731 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10732 @item ^--no-elim-dispatch^/NO_DISPATCH^
10733 Do not generate pragmas for dispatching operations.
10734
10735 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10736 @item ^-o^/OUTPUT^=@var{report_file}
10737 Put @command{gnatelim} output into a specified file. If this file already exists,
10738 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10739 into @file{stderr}
10740
10741 @item ^-q^/QUIET^
10742 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10743 Quiet mode: by default @code{gnatelim} outputs to the standard error
10744 stream the number of program units left to be processed. This option turns
10745 this trace off.
10746
10747 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10748 @item ^-t^/TIME^
10749 Print out execution time.
10750
10751 @item ^-v^/VERBOSE^
10752 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10753 Verbose mode: @code{gnatelim} version information is printed as Ada
10754 comments to the standard output stream. Also, in addition to the number of
10755 program units left @code{gnatelim} will output the name of the current unit
10756 being processed.
10757
10758 @item ^-wq^/WARNINGS=QUIET^
10759 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10760 Quet warning mode - some warnings are suppressed. In particular warnings that
10761 indicate that the analysed set of sources is incomplete to make up a
10762 partition and that some subprogram bodies are missing are not generated.
10763 @end table
10764
10765 @node Processing Precompiled Libraries
10766 @subsection Processing Precompiled Libraries
10767
10768 @noindent
10769 If some program uses a precompiled Ada library, it can be processed by
10770 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10771 Eliminate pragma for a subprogram if the body of this subprogram has not
10772 been analysed, this is a typical case for subprograms from precompiled
10773 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10774 warnings about missing source files and non-analyzed subprogram bodies
10775 that can be generated when processing precompiled Ada libraries.
10776
10777 @node Correcting the List of Eliminate Pragmas
10778 @subsection Correcting the List of Eliminate Pragmas
10779
10780 @noindent
10781 In some rare cases @code{gnatelim} may try to eliminate
10782 subprograms that are actually called in the program. In this case, the
10783 compiler will generate an error message of the form:
10784
10785 @smallexample
10786 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10787 @end smallexample
10788
10789 @noindent
10790 You will need to manually remove the wrong @code{Eliminate} pragmas from
10791 the configuration file indicated in the error message. You should recompile
10792 your program from scratch after that, because you need a consistent
10793 configuration file(s) during the entire compilation.
10794
10795 @node Making Your Executables Smaller
10796 @subsection Making Your Executables Smaller
10797
10798 @noindent
10799 In order to get a smaller executable for your program you now have to
10800 recompile the program completely with the configuration file containing
10801 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10802 @file{gnat.adc} file located in your current directory, just do:
10803
10804 @smallexample
10805 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10806 @end smallexample
10807
10808 @noindent
10809 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10810 recompile everything
10811 with the set of pragmas @code{Eliminate} that you have obtained with
10812 @command{gnatelim}).
10813
10814 Be aware that the set of @code{Eliminate} pragmas is specific to each
10815 program. It is not recommended to merge sets of @code{Eliminate}
10816 pragmas created for different programs in one configuration file.
10817
10818 @node Summary of the gnatelim Usage Cycle
10819 @subsection Summary of the @code{gnatelim} Usage Cycle
10820
10821 @noindent
10822 Here is a quick summary of the steps to be taken in order to reduce
10823 the size of your executables with @code{gnatelim}. You may use
10824 other GNAT options to control the optimization level,
10825 to produce the debugging information, to set search path, etc.
10826
10827 @enumerate
10828 @item
10829 Create a complete set of @file{ALI} files (if the program has not been
10830 built already)
10831
10832 @smallexample
10833 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10834 @end smallexample
10835
10836 @item
10837 Generate a list of @code{Eliminate} pragmas in default configuration file
10838 @file{gnat.adc} in the current directory
10839 @smallexample
10840 @ifset vms
10841 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10842 @end ifset
10843 @ifclear vms
10844 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10845 @end ifclear
10846 @end smallexample
10847
10848 @item
10849 Recompile the application
10850
10851 @smallexample
10852 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10853 @end smallexample
10854
10855 @end enumerate
10856
10857 @node Reducing Size of Executables with unused subprogram/data elimination
10858 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10859 @findex unused subprogram/data elimination
10860
10861 @noindent
10862 This section describes how you can eliminate unused subprograms and data from
10863 your executable just by setting options at compilation time.
10864
10865 @menu
10866 * About unused subprogram/data elimination::
10867 * Compilation options::
10868 * Example of unused subprogram/data elimination::
10869 @end menu
10870
10871 @node About unused subprogram/data elimination
10872 @subsection About unused subprogram/data elimination
10873
10874 @noindent
10875 By default, an executable contains all code and data of its composing objects
10876 (directly linked or coming from statically linked libraries), even data or code
10877 never used by this executable.
10878
10879 This feature will allow you to eliminate such unused code from your
10880 executable, making it smaller (in disk and in memory).
10881
10882 This functionality is available on all Linux platforms except for the IA-64
10883 architecture and on all cross platforms using the ELF binary file format.
10884 In both cases GNU binutils version 2.16 or later are required to enable it.
10885
10886 @node Compilation options
10887 @subsection Compilation options
10888
10889 @noindent
10890 The operation of eliminating the unused code and data from the final executable
10891 is directly performed by the linker.
10892
10893 In order to do this, it has to work with objects compiled with the
10894 following options:
10895 @option{-ffunction-sections} @option{-fdata-sections}.
10896 @cindex @option{-ffunction-sections} (@command{gcc})
10897 @cindex @option{-fdata-sections} (@command{gcc})
10898 These options are usable with C and Ada files.
10899 They will place respectively each
10900 function or data in a separate section in the resulting object file.
10901
10902 Once the objects and static libraries are created with these options, the
10903 linker can perform the dead code elimination. You can do this by setting
10904 the @option{-Wl,--gc-sections} option to gcc command or in the
10905 @option{-largs} section of @command{gnatmake}. This will perform a
10906 garbage collection of code and data never referenced.
10907
10908 If the linker performs a partial link (@option{-r} ld linker option), then you
10909 will need to provide one or several entry point using the
10910 @option{-e} / @option{--entry} ld option.
10911
10912 Note that objects compiled without the @option{-ffunction-sections} and
10913 @option{-fdata-sections} options can still be linked with the executable.
10914 However, no dead code elimination will be performed on those objects (they will
10915 be linked as is).
10916
10917 The GNAT static library is now compiled with -ffunction-sections and
10918 -fdata-sections on some platforms. This allows you to eliminate the unused code
10919 and data of the GNAT library from your executable.
10920
10921 @node Example of unused subprogram/data elimination
10922 @subsection Example of unused subprogram/data elimination
10923
10924 @noindent
10925 Here is a simple example:
10926
10927 @smallexample @c ada
10928 with Aux;
10929
10930 procedure Test is
10931 begin
10932    Aux.Used (10);
10933 end Test;
10934
10935 package Aux is
10936    Used_Data   : Integer;
10937    Unused_Data : Integer;
10938
10939    procedure Used   (Data : Integer);
10940    procedure Unused (Data : Integer);
10941 end Aux;
10942
10943 package body Aux is
10944    procedure Used (Data : Integer) is
10945    begin
10946       Used_Data := Data;
10947    end Used;
10948
10949    procedure Unused (Data : Integer) is
10950    begin
10951       Unused_Data := Data;
10952    end Unused;
10953 end Aux;
10954 @end smallexample
10955
10956 @noindent
10957 @code{Unused} and @code{Unused_Data} are never referenced in this code
10958 excerpt, and hence they may be safely removed from the final executable.
10959
10960 @smallexample
10961 $ gnatmake test
10962
10963 $ nm test | grep used
10964 020015f0 T aux__unused
10965 02005d88 B aux__unused_data
10966 020015cc T aux__used
10967 02005d84 B aux__used_data
10968
10969 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10970      -largs -Wl,--gc-sections
10971
10972 $ nm test | grep used
10973 02005350 T aux__used
10974 0201ffe0 B aux__used_data
10975 @end smallexample
10976
10977 @noindent
10978 It can be observed that the procedure @code{Unused} and the object
10979 @code{Unused_Data} are removed by the linker when using the
10980 appropriate options.
10981
10982 @c ********************************
10983 @node Renaming Files Using gnatchop
10984 @chapter Renaming Files Using @code{gnatchop}
10985 @findex gnatchop
10986
10987 @noindent
10988 This chapter discusses how to handle files with multiple units by using
10989 the @code{gnatchop} utility. This utility is also useful in renaming
10990 files to meet the standard GNAT default file naming conventions.
10991
10992 @menu
10993 * Handling Files with Multiple Units::
10994 * Operating gnatchop in Compilation Mode::
10995 * Command Line for gnatchop::
10996 * Switches for gnatchop::
10997 * Examples of gnatchop Usage::
10998 @end menu
10999
11000 @node Handling Files with Multiple Units
11001 @section Handling Files with Multiple Units
11002
11003 @noindent
11004 The basic compilation model of GNAT requires that a file submitted to the
11005 compiler have only one unit and there be a strict correspondence
11006 between the file name and the unit name.
11007
11008 The @code{gnatchop} utility allows both of these rules to be relaxed,
11009 allowing GNAT to process files which contain multiple compilation units
11010 and files with arbitrary file names. @code{gnatchop}
11011 reads the specified file and generates one or more output files,
11012 containing one unit per file. The unit and the file name correspond,
11013 as required by GNAT.
11014
11015 If you want to permanently restructure a set of ``foreign'' files so that
11016 they match the GNAT rules, and do the remaining development using the
11017 GNAT structure, you can simply use @command{gnatchop} once, generate the
11018 new set of files and work with them from that point on.
11019
11020 Alternatively, if you want to keep your files in the ``foreign'' format,
11021 perhaps to maintain compatibility with some other Ada compilation
11022 system, you can set up a procedure where you use @command{gnatchop} each
11023 time you compile, regarding the source files that it writes as temporary
11024 files that you throw away.
11025
11026 Note that if your file containing multiple units starts with a byte order
11027 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11028 will each start with a copy of this BOM, meaning that they can be compiled
11029 automatically in UTF-8 mode without needing to specify an explicit encoding.
11030
11031 @node Operating gnatchop in Compilation Mode
11032 @section Operating gnatchop in Compilation Mode
11033
11034 @noindent
11035 The basic function of @code{gnatchop} is to take a file with multiple units
11036 and split it into separate files. The boundary between files is reasonably
11037 clear, except for the issue of comments and pragmas. In default mode, the
11038 rule is that any pragmas between units belong to the previous unit, except
11039 that configuration pragmas always belong to the following unit. Any comments
11040 belong to the following unit. These rules
11041 almost always result in the right choice of
11042 the split point without needing to mark it explicitly and most users will
11043 find this default to be what they want. In this default mode it is incorrect to
11044 submit a file containing only configuration pragmas, or one that ends in
11045 configuration pragmas, to @code{gnatchop}.
11046
11047 However, using a special option to activate ``compilation mode'',
11048 @code{gnatchop}
11049 can perform another function, which is to provide exactly the semantics
11050 required by the RM for handling of configuration pragmas in a compilation.
11051 In the absence of configuration pragmas (at the main file level), this
11052 option has no effect, but it causes such configuration pragmas to be handled
11053 in a quite different manner.
11054
11055 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11056 only configuration pragmas, then this file is appended to the
11057 @file{gnat.adc} file in the current directory. This behavior provides
11058 the required behavior described in the RM for the actions to be taken
11059 on submitting such a file to the compiler, namely that these pragmas
11060 should apply to all subsequent compilations in the same compilation
11061 environment. Using GNAT, the current directory, possibly containing a
11062 @file{gnat.adc} file is the representation
11063 of a compilation environment. For more information on the
11064 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11065
11066 Second, in compilation mode, if @code{gnatchop}
11067 is given a file that starts with
11068 configuration pragmas, and contains one or more units, then these
11069 configuration pragmas are prepended to each of the chopped files. This
11070 behavior provides the required behavior described in the RM for the
11071 actions to be taken on compiling such a file, namely that the pragmas
11072 apply to all units in the compilation, but not to subsequently compiled
11073 units.
11074
11075 Finally, if configuration pragmas appear between units, they are appended
11076 to the previous unit. This results in the previous unit being illegal,
11077 since the compiler does not accept configuration pragmas that follow
11078 a unit. This provides the required RM behavior that forbids configuration
11079 pragmas other than those preceding the first compilation unit of a
11080 compilation.
11081
11082 For most purposes, @code{gnatchop} will be used in default mode. The
11083 compilation mode described above is used only if you need exactly
11084 accurate behavior with respect to compilations, and you have files
11085 that contain multiple units and configuration pragmas. In this
11086 circumstance the use of @code{gnatchop} with the compilation mode
11087 switch provides the required behavior, and is for example the mode
11088 in which GNAT processes the ACVC tests.
11089
11090 @node Command Line for gnatchop
11091 @section Command Line for @code{gnatchop}
11092
11093 @noindent
11094 The @code{gnatchop} command has the form:
11095
11096 @smallexample
11097 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11098 @c      @ovar{directory}
11099 @c Expanding @ovar macro inline (explanation in macro def comments)
11100 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11101       @r{[}@var{directory}@r{]}
11102 @end smallexample
11103
11104 @noindent
11105 The only required argument is the file name of the file to be chopped.
11106 There are no restrictions on the form of this file name. The file itself
11107 contains one or more Ada units, in normal GNAT format, concatenated
11108 together. As shown, more than one file may be presented to be chopped.
11109
11110 When run in default mode, @code{gnatchop} generates one output file in
11111 the current directory for each unit in each of the files.
11112
11113 @var{directory}, if specified, gives the name of the directory to which
11114 the output files will be written. If it is not specified, all files are
11115 written to the current directory.
11116
11117 For example, given a
11118 file called @file{hellofiles} containing
11119
11120 @smallexample @c ada
11121 @group
11122 @cartouche
11123 procedure hello;
11124
11125 with Text_IO; use Text_IO;
11126 procedure hello is
11127 begin
11128    Put_Line ("Hello");
11129 end hello;
11130 @end cartouche
11131 @end group
11132 @end smallexample
11133
11134 @noindent
11135 the command
11136
11137 @smallexample
11138 $ gnatchop ^hellofiles^HELLOFILES.^
11139 @end smallexample
11140
11141 @noindent
11142 generates two files in the current directory, one called
11143 @file{hello.ads} containing the single line that is the procedure spec,
11144 and the other called @file{hello.adb} containing the remaining text. The
11145 original file is not affected. The generated files can be compiled in
11146 the normal manner.
11147
11148 @noindent
11149 When gnatchop is invoked on a file that is empty or that contains only empty
11150 lines and/or comments, gnatchop will not fail, but will not produce any
11151 new sources.
11152
11153 For example, given a
11154 file called @file{toto.txt} containing
11155
11156 @smallexample @c ada
11157 @group
11158 @cartouche
11159 --  Just a comment
11160 @end cartouche
11161 @end group
11162 @end smallexample
11163
11164 @noindent
11165 the command
11166
11167 @smallexample
11168 $ gnatchop ^toto.txt^TOT.TXT^
11169 @end smallexample
11170
11171 @noindent
11172 will not produce any new file and will result in the following warnings:
11173
11174 @smallexample
11175 toto.txt:1:01: warning: empty file, contains no compilation units
11176 no compilation units found
11177 no source files written
11178 @end smallexample
11179
11180 @node Switches for gnatchop
11181 @section Switches for @code{gnatchop}
11182
11183 @noindent
11184 @command{gnatchop} recognizes the following switches:
11185
11186 @table @option
11187 @c !sort!
11188
11189 @item --version
11190 @cindex @option{--version} @command{gnatchop}
11191 Display Copyright and version, then exit disregarding all other options.
11192
11193 @item --help
11194 @cindex @option{--help} @command{gnatchop}
11195 If @option{--version} was not used, display usage, then exit disregarding
11196 all other options.
11197
11198 @item ^-c^/COMPILATION^
11199 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11200 Causes @code{gnatchop} to operate in compilation mode, in which
11201 configuration pragmas are handled according to strict RM rules. See
11202 previous section for a full description of this mode.
11203
11204 @ifclear vms
11205 @item -gnat@var{xxx}
11206 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11207 used to parse the given file. Not all @var{xxx} options make sense,
11208 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11209 process a source file that uses Latin-2 coding for identifiers.
11210 @end ifclear
11211
11212 @item ^-h^/HELP^
11213 Causes @code{gnatchop} to generate a brief help summary to the standard
11214 output file showing usage information.
11215
11216 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11217 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11218 Limit generated file names to the specified number @code{mm}
11219 of characters.
11220 This is useful if the
11221 resulting set of files is required to be interoperable with systems
11222 which limit the length of file names.
11223 @ifset vms
11224 If no value is given, or
11225 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11226 a default of 39, suitable for OpenVMS Alpha
11227 Systems, is assumed
11228 @end ifset
11229 @ifclear vms
11230 No space is allowed between the @option{-k} and the numeric value. The numeric
11231 value may be omitted in which case a default of @option{-k8},
11232 suitable for use
11233 with DOS-like file systems, is used. If no @option{-k} switch
11234 is present then
11235 there is no limit on the length of file names.
11236 @end ifclear
11237
11238 @item ^-p^/PRESERVE^
11239 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11240 Causes the file ^modification^creation^ time stamp of the input file to be
11241 preserved and used for the time stamp of the output file(s). This may be
11242 useful for preserving coherency of time stamps in an environment where
11243 @code{gnatchop} is used as part of a standard build process.
11244
11245 @item ^-q^/QUIET^
11246 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11247 Causes output of informational messages indicating the set of generated
11248 files to be suppressed. Warnings and error messages are unaffected.
11249
11250 @item ^-r^/REFERENCE^
11251 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11252 @findex Source_Reference
11253 Generate @code{Source_Reference} pragmas. Use this switch if the output
11254 files are regarded as temporary and development is to be done in terms
11255 of the original unchopped file. This switch causes
11256 @code{Source_Reference} pragmas to be inserted into each of the
11257 generated files to refers back to the original file name and line number.
11258 The result is that all error messages refer back to the original
11259 unchopped file.
11260 In addition, the debugging information placed into the object file (when
11261 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11262 specified)
11263 also refers back to this original file so that tools like profilers and
11264 debuggers will give information in terms of the original unchopped file.
11265
11266 If the original file to be chopped itself contains
11267 a @code{Source_Reference}
11268 pragma referencing a third file, then gnatchop respects
11269 this pragma, and the generated @code{Source_Reference} pragmas
11270 in the chopped file refer to the original file, with appropriate
11271 line numbers. This is particularly useful when @code{gnatchop}
11272 is used in conjunction with @code{gnatprep} to compile files that
11273 contain preprocessing statements and multiple units.
11274
11275 @item ^-v^/VERBOSE^
11276 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11277 Causes @code{gnatchop} to operate in verbose mode. The version
11278 number and copyright notice are output, as well as exact copies of
11279 the gnat1 commands spawned to obtain the chop control information.
11280
11281 @item ^-w^/OVERWRITE^
11282 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11283 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11284 fatal error if there is already a file with the same name as a
11285 file it would otherwise output, in other words if the files to be
11286 chopped contain duplicated units. This switch bypasses this
11287 check, and causes all but the last instance of such duplicated
11288 units to be skipped.
11289
11290 @ifclear vms
11291 @item --GCC=@var{xxxx}
11292 @cindex @option{--GCC=} (@code{gnatchop})
11293 Specify the path of the GNAT parser to be used. When this switch is used,
11294 no attempt is made to add the prefix to the GNAT parser executable.
11295 @end ifclear
11296 @end table
11297
11298 @node Examples of gnatchop Usage
11299 @section Examples of @code{gnatchop} Usage
11300
11301 @table @code
11302 @ifset vms
11303 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11304 @end ifset
11305 @ifclear vms
11306 @item gnatchop -w hello_s.ada prerelease/files
11307 @end ifclear
11308
11309 Chops the source file @file{hello_s.ada}. The output files will be
11310 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11311 overwriting any
11312 files with matching names in that directory (no files in the current
11313 directory are modified).
11314
11315 @item gnatchop ^archive^ARCHIVE.^
11316 Chops the source file @file{^archive^ARCHIVE.^}
11317 into the current directory. One
11318 useful application of @code{gnatchop} is in sending sets of sources
11319 around, for example in email messages. The required sources are simply
11320 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11321 command), and then
11322 @command{gnatchop} is used at the other end to reconstitute the original
11323 file names.
11324
11325 @item gnatchop file1 file2 file3 direc
11326 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11327 the resulting files in the directory @file{direc}. Note that if any units
11328 occur more than once anywhere within this set of files, an error message
11329 is generated, and no files are written. To override this check, use the
11330 @option{^-w^/OVERWRITE^} switch,
11331 in which case the last occurrence in the last file will
11332 be the one that is output, and earlier duplicate occurrences for a given
11333 unit will be skipped.
11334 @end table
11335
11336 @node Configuration Pragmas
11337 @chapter Configuration Pragmas
11338 @cindex Configuration pragmas
11339 @cindex Pragmas, configuration
11340
11341 @noindent
11342 Configuration pragmas include those pragmas described as
11343 such in the Ada Reference Manual, as well as
11344 implementation-dependent pragmas that are configuration pragmas.
11345 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11346 for details on these additional GNAT-specific configuration pragmas.
11347 Most notably, the pragma @code{Source_File_Name}, which allows
11348 specifying non-default names for source files, is a configuration
11349 pragma. The following is a complete list of configuration pragmas
11350 recognized by GNAT:
11351
11352 @smallexample
11353    Ada_83
11354    Ada_95
11355    Ada_05
11356    Ada_2005
11357    Assertion_Policy
11358    Assume_No_Invalid_Values
11359    C_Pass_By_Copy
11360    Check_Name
11361    Check_Policy
11362    Compile_Time_Error
11363    Compile_Time_Warning
11364    Compiler_Unit
11365    Component_Alignment
11366    Convention_Identifier
11367    Debug_Policy
11368    Detect_Blocking
11369    Discard_Names
11370    Elaboration_Checks
11371    Eliminate
11372    Extend_System
11373    Extensions_Allowed
11374    External_Name_Casing
11375    Fast_Math
11376    Favor_Top_Level
11377    Float_Representation
11378    Implicit_Packing
11379    Initialize_Scalars
11380    Interrupt_State
11381    License
11382    Locking_Policy
11383    Long_Float
11384    No_Run_Time
11385    No_Strict_Aliasing
11386    Normalize_Scalars
11387    Optimize_Alignment
11388    Persistent_BSS
11389    Polling
11390    Priority_Specific_Dispatching
11391    Profile
11392    Profile_Warnings
11393    Propagate_Exceptions
11394    Queuing_Policy
11395    Ravenscar
11396    Restricted_Run_Time
11397    Restrictions
11398    Restrictions_Warnings
11399    Reviewable
11400    Source_File_Name
11401    Source_File_Name_Project
11402    Style_Checks
11403    Suppress
11404    Suppress_Exception_Locations
11405    Task_Dispatching_Policy
11406    Universal_Data
11407    Unsuppress
11408    Use_VADS_Size
11409    Validity_Checks
11410    Warnings
11411    Wide_Character_Encoding
11412
11413 @end smallexample
11414
11415 @menu
11416 * Handling of Configuration Pragmas::
11417 * The Configuration Pragmas Files::
11418 @end menu
11419
11420 @node Handling of Configuration Pragmas
11421 @section Handling of Configuration Pragmas
11422
11423 Configuration pragmas may either appear at the start of a compilation
11424 unit, in which case they apply only to that unit, or they may apply to
11425 all compilations performed in a given compilation environment.
11426
11427 GNAT also provides the @code{gnatchop} utility to provide an automatic
11428 way to handle configuration pragmas following the semantics for
11429 compilations (that is, files with multiple units), described in the RM.
11430 See @ref{Operating gnatchop in Compilation Mode} for details.
11431 However, for most purposes, it will be more convenient to edit the
11432 @file{gnat.adc} file that contains configuration pragmas directly,
11433 as described in the following section.
11434
11435 @node The Configuration Pragmas Files
11436 @section The Configuration Pragmas Files
11437 @cindex @file{gnat.adc}
11438
11439 @noindent
11440 In GNAT a compilation environment is defined by the current
11441 directory at the time that a compile command is given. This current
11442 directory is searched for a file whose name is @file{gnat.adc}. If
11443 this file is present, it is expected to contain one or more
11444 configuration pragmas that will be applied to the current compilation.
11445 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11446 considered.
11447
11448 Configuration pragmas may be entered into the @file{gnat.adc} file
11449 either by running @code{gnatchop} on a source file that consists only of
11450 configuration pragmas, or more conveniently  by
11451 direct editing of the @file{gnat.adc} file, which is a standard format
11452 source file.
11453
11454 In addition to @file{gnat.adc}, additional files containing configuration
11455 pragmas may be applied to the current compilation using the switch
11456 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11457 contains only configuration pragmas. These configuration pragmas are
11458 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11459 is present and switch @option{-gnatA} is not used).
11460
11461 It is allowed to specify several switches @option{-gnatec}, all of which
11462 will be taken into account.
11463
11464 If you are using project file, a separate mechanism is provided using
11465 project attributes, see @ref{Specifying Configuration Pragmas} for more
11466 details.
11467
11468 @ifset vms
11469 Of special interest to GNAT OpenVMS Alpha is the following
11470 configuration pragma:
11471
11472 @smallexample @c ada
11473 @cartouche
11474 pragma Extend_System (Aux_DEC);
11475 @end cartouche
11476 @end smallexample
11477
11478 @noindent
11479 In the presence of this pragma, GNAT adds to the definition of the
11480 predefined package SYSTEM all the additional types and subprograms that are
11481 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11482 @end ifset
11483
11484 @node Handling Arbitrary File Naming Conventions Using gnatname
11485 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11486 @cindex Arbitrary File Naming Conventions
11487
11488 @menu
11489 * Arbitrary File Naming Conventions::
11490 * Running gnatname::
11491 * Switches for gnatname::
11492 * Examples of gnatname Usage::
11493 @end menu
11494
11495 @node Arbitrary File Naming Conventions
11496 @section Arbitrary File Naming Conventions
11497
11498 @noindent
11499 The GNAT compiler must be able to know the source file name of a compilation
11500 unit.  When using the standard GNAT default file naming conventions
11501 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11502 does not need additional information.
11503
11504 @noindent
11505 When the source file names do not follow the standard GNAT default file naming
11506 conventions, the GNAT compiler must be given additional information through
11507 a configuration pragmas file (@pxref{Configuration Pragmas})
11508 or a project file.
11509 When the non-standard file naming conventions are well-defined,
11510 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11511 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11512 if the file naming conventions are irregular or arbitrary, a number
11513 of pragma @code{Source_File_Name} for individual compilation units
11514 must be defined.
11515 To help maintain the correspondence between compilation unit names and
11516 source file names within the compiler,
11517 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11518 set of files.
11519
11520 @node Running gnatname
11521 @section Running @code{gnatname}
11522
11523 @noindent
11524 The usual form of the @code{gnatname} command is
11525
11526 @smallexample
11527 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11528 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11529 @c Expanding @ovar macro inline (explanation in macro def comments)
11530 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11531       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11532 @end smallexample
11533
11534 @noindent
11535 All of the arguments are optional. If invoked without any argument,
11536 @code{gnatname} will display its usage.
11537
11538 @noindent
11539 When used with at least one naming pattern, @code{gnatname} will attempt to
11540 find all the compilation units in files that follow at least one of the
11541 naming patterns. To find these compilation units,
11542 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11543 regular files.
11544
11545 @noindent
11546 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11547 Each Naming Pattern is enclosed between double quotes.
11548 A Naming Pattern is a regular expression similar to the wildcard patterns
11549 used in file names by the Unix shells or the DOS prompt.
11550
11551 @noindent
11552 @code{gnatname} may be called with several sections of directories/patterns.
11553 Sections are separated by switch @code{--and}. In each section, there must be
11554 at least one pattern. If no directory is specified in a section, the current
11555 directory (or the project directory is @code{-P} is used) is implied.
11556 The options other that the directory switches and the patterns apply globally
11557 even if they are in different sections.
11558
11559 @noindent
11560 Examples of Naming Patterns are
11561
11562 @smallexample
11563    "*.[12].ada"
11564    "*.ad[sb]*"
11565    "body_*"    "spec_*"
11566 @end smallexample
11567
11568 @noindent
11569 For a more complete description of the syntax of Naming Patterns,
11570 see the second kind of regular expressions described in @file{g-regexp.ads}
11571 (the ``Glob'' regular expressions).
11572
11573 @noindent
11574 When invoked with no switch @code{-P}, @code{gnatname} will create a
11575 configuration pragmas file @file{gnat.adc} in the current working directory,
11576 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11577 unit.
11578
11579 @node Switches for gnatname
11580 @section Switches for @code{gnatname}
11581
11582 @noindent
11583 Switches for @code{gnatname} must precede any specified Naming Pattern.
11584
11585 @noindent
11586 You may specify any of the following switches to @code{gnatname}:
11587
11588 @table @option
11589 @c !sort!
11590
11591 @item --version
11592 @cindex @option{--version} @command{gnatname}
11593 Display Copyright and version, then exit disregarding all other options.
11594
11595 @item --help
11596 @cindex @option{--help} @command{gnatname}
11597 If @option{--version} was not used, display usage, then exit disregarding
11598 all other options.
11599
11600 @item --and
11601 Start another section of directories/patterns.
11602
11603 @item ^-c^/CONFIG_FILE=^@file{file}
11604 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11605 Create a configuration pragmas file @file{file} (instead of the default
11606 @file{gnat.adc}).
11607 @ifclear vms
11608 There may be zero, one or more space between @option{-c} and
11609 @file{file}.
11610 @end ifclear
11611 @file{file} may include directory information. @file{file} must be
11612 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11613 When a switch @option{^-c^/CONFIG_FILE^} is
11614 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11615
11616 @item ^-d^/SOURCE_DIRS=^@file{dir}
11617 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11618 Look for source files in directory @file{dir}. There may be zero, one or more
11619 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11620 When a switch @option{^-d^/SOURCE_DIRS^}
11621 is specified, the current working directory will not be searched for source
11622 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11623 or @option{^-D^/DIR_FILES^} switch.
11624 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11625 If @file{dir} is a relative path, it is relative to the directory of
11626 the configuration pragmas file specified with switch
11627 @option{^-c^/CONFIG_FILE^},
11628 or to the directory of the project file specified with switch
11629 @option{^-P^/PROJECT_FILE^} or,
11630 if neither switch @option{^-c^/CONFIG_FILE^}
11631 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11632 current working directory. The directory
11633 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11634
11635 @item ^-D^/DIRS_FILE=^@file{file}
11636 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11637 Look for source files in all directories listed in text file @file{file}.
11638 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11639 and @file{file}.
11640 @file{file} must be an existing, readable text file.
11641 Each nonempty line in @file{file} must be a directory.
11642 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11643 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11644 @file{file}.
11645
11646 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11647 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11648 Foreign patterns. Using this switch, it is possible to add sources of languages
11649 other than Ada to the list of sources of a project file.
11650 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11651 For example,
11652 @smallexample
11653 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11654 @end smallexample
11655 @noindent
11656 will look for Ada units in all files with the @file{.ada} extension,
11657 and will add to the list of file for project @file{prj.gpr} the C files
11658 with extension @file{.^c^C^}.
11659
11660 @item ^-h^/HELP^
11661 @cindex @option{^-h^/HELP^} (@code{gnatname})
11662 Output usage (help) information. The output is written to @file{stdout}.
11663
11664 @item ^-P^/PROJECT_FILE=^@file{proj}
11665 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11666 Create or update project file @file{proj}. There may be zero, one or more space
11667 between @option{-P} and @file{proj}. @file{proj} may include directory
11668 information. @file{proj} must be writable.
11669 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11670 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11671 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11672
11673 @item ^-v^/VERBOSE^
11674 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11675 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11676 This includes name of the file written, the name of the directories to search
11677 and, for each file in those directories whose name matches at least one of
11678 the Naming Patterns, an indication of whether the file contains a unit,
11679 and if so the name of the unit.
11680
11681 @item ^-v -v^/VERBOSE /VERBOSE^
11682 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11683 Very Verbose mode. In addition to the output produced in verbose mode,
11684 for each file in the searched directories whose name matches none of
11685 the Naming Patterns, an indication is given that there is no match.
11686
11687 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11688 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11689 Excluded patterns. Using this switch, it is possible to exclude some files
11690 that would match the name patterns. For example,
11691 @smallexample
11692 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11693 @end smallexample
11694 @noindent
11695 will look for Ada units in all files with the @file{.ada} extension,
11696 except those whose names end with @file{_nt.ada}.
11697
11698 @end table
11699
11700 @node Examples of gnatname Usage
11701 @section Examples of @code{gnatname} Usage
11702
11703 @ifset vms
11704 @smallexample
11705 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11706 @end smallexample
11707 @end ifset
11708
11709 @ifclear vms
11710 @smallexample
11711 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11712 @end smallexample
11713 @end ifclear
11714
11715 @noindent
11716 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11717 and be writable. In addition, the directory
11718 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11719 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11720
11721 @ifclear vms
11722 Note the optional spaces after @option{-c} and @option{-d}.
11723 @end ifclear
11724
11725 @smallexample
11726 @ifclear vms
11727 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11728   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11729 @end ifclear
11730 @ifset vms
11731 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11732   /EXCLUDED_PATTERN=*_nt_body.ada
11733   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11734   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11735 @end ifset
11736 @end smallexample
11737
11738 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11739 even in conjunction with one or several switches
11740 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11741 are used in this example.
11742
11743 @c *****************************************
11744 @c * G N A T  P r o j e c t  M a n a g e r *
11745 @c *****************************************
11746 @node GNAT Project Manager
11747 @chapter GNAT Project Manager
11748
11749 @menu
11750 * Introduction::
11751 * Examples of Project Files::
11752 * Project File Syntax::
11753 * Objects and Sources in Project Files::
11754 * Importing Projects::
11755 * Project Extension::
11756 * Project Hierarchy Extension::
11757 * External References in Project Files::
11758 * Packages in Project Files::
11759 * Variables from Imported Projects::
11760 * Naming Schemes::
11761 * Library Projects::
11762 * Stand-alone Library Projects::
11763 * Switches Related to Project Files::
11764 * Tools Supporting Project Files::
11765 * An Extended Example::
11766 * Project File Complete Syntax::
11767 @end menu
11768
11769 @c ****************
11770 @c * Introduction *
11771 @c ****************
11772
11773 @node Introduction
11774 @section Introduction
11775
11776 @noindent
11777 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11778 you to manage complex builds involving a number of source files, directories,
11779 and compilation options for different system configurations. In particular,
11780 project files allow you to specify:
11781 @itemize @bullet
11782 @item
11783 The directory or set of directories containing the source files, and/or the
11784 names of the specific source files themselves
11785 @item
11786 The directory in which the compiler's output
11787 (@file{ALI} files, object files, tree files) is to be placed
11788 @item
11789 The directory in which the executable programs is to be placed
11790 @item
11791 ^Switch^Switch^ settings for any of the project-enabled tools
11792 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11793 @code{gnatfind}); you can apply these settings either globally or to individual
11794 compilation units.
11795 @item
11796 The source files containing the main subprogram(s) to be built
11797 @item
11798 The source programming language(s) (currently Ada and/or C)
11799 @item
11800 Source file naming conventions; you can specify these either globally or for
11801 individual compilation units
11802 @end itemize
11803
11804 @menu
11805 * Project Files::
11806 @end menu
11807
11808 @node Project Files
11809 @subsection Project Files
11810
11811 @noindent
11812 Project files are written in a syntax close to that of Ada, using  familiar
11813 notions such as packages, context clauses, declarations, default values,
11814 assignments, and inheritance. Finally, project files can be built
11815 hierarchically from other project files, simplifying complex system
11816 integration and project reuse.
11817
11818 A @dfn{project} is a specific set of values for various compilation properties.
11819 The settings for a given project are described by means of
11820 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11821 Property values in project files are either strings or lists of strings.
11822 Properties that are not explicitly set receive default values.  A project
11823 file may interrogate the values of @dfn{external variables} (user-defined
11824 command-line switches or environment variables), and it may specify property
11825 settings conditionally, based on the value of such variables.
11826
11827 In simple cases, a project's source files depend only on other source files
11828 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11829 used in
11830 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11831 the Project Manager also allows more sophisticated arrangements,
11832 where the source files in one project depend on source files in other
11833 projects:
11834 @itemize @bullet
11835 @item
11836 One project can @emph{import} other projects containing needed source files.
11837 @item
11838 You can organize GNAT projects in a hierarchy: a @emph{child} project
11839 can extend a @emph{parent} project, inheriting the parent's source files and
11840 optionally overriding any of them with alternative versions
11841 @end itemize
11842
11843 @noindent
11844 More generally, the Project Manager lets you structure large development
11845 efforts into hierarchical subsystems, where build decisions are delegated
11846 to the subsystem level, and thus different compilation environments
11847 (^switch^switch^ settings) used for different subsystems.
11848
11849 The Project Manager is invoked through the
11850 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11851 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11852 @ifclear vms
11853 There may be zero, one or more spaces between @option{-P} and
11854 @option{@emph{projectfile}}.
11855 @end ifclear
11856 If you want to define (on the command line) an external variable that is
11857 queried by the project file, you must use the
11858 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11859 The Project Manager parses and interprets the project file, and drives the
11860 invoked tool based on the project settings.
11861
11862 The Project Manager supports a wide range of development strategies,
11863 for systems of all sizes.  Here are some typical practices that are
11864 easily handled:
11865 @itemize @bullet
11866 @item
11867 Using a common set of source files, but generating object files in different
11868 directories via different ^switch^switch^ settings
11869 @item
11870 Using a mostly-shared set of source files, but with different versions of
11871 some unit or units
11872 @end itemize
11873
11874 @noindent
11875 The destination of an executable can be controlled inside a project file
11876 using the @option{^-o^-o^}
11877 ^switch^switch^.
11878 In the absence of such a ^switch^switch^ either inside
11879 the project file or on the command line, any executable files generated by
11880 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11881 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11882 in the object directory of the project.
11883
11884 You can use project files to achieve some of the effects of a source
11885 versioning system (for example, defining separate projects for
11886 the different sets of sources that comprise different releases) but the
11887 Project Manager is independent of any source configuration management tools
11888 that might be used by the developers.
11889
11890 The next section introduces the main features of GNAT's project facility
11891 through a sequence of examples; subsequent sections will present the syntax
11892 and semantics in more detail. A more formal description of the project
11893 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11894 Reference Manual}.
11895
11896 @c *****************************
11897 @c * Examples of Project Files *
11898 @c *****************************
11899
11900 @node Examples of Project Files
11901 @section Examples of Project Files
11902 @noindent
11903 This section illustrates some of the typical uses of project files and
11904 explains their basic structure and behavior.
11905
11906 @menu
11907 * Common Sources with Different ^Switches^Switches^ and Directories::
11908 * Using External Variables::
11909 * Importing Other Projects::
11910 * Extending a Project::
11911 @end menu
11912
11913 @node Common Sources with Different ^Switches^Switches^ and Directories
11914 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11915
11916 @menu
11917 * Source Files::
11918 * Specifying the Object Directory::
11919 * Specifying the Exec Directory::
11920 * Project File Packages::
11921 * Specifying ^Switch^Switch^ Settings::
11922 * Main Subprograms::
11923 * Executable File Names::
11924 * Source File Naming Conventions::
11925 * Source Language(s)::
11926 @end menu
11927
11928 @noindent
11929 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11930 @file{proc.adb} are in the @file{/common} directory.  The file
11931 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11932 package @code{Pack}.  We want to compile these source files under two sets
11933 of ^switches^switches^:
11934 @itemize @bullet
11935 @item
11936 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11937 and the @option{^-gnata^-gnata^},
11938 @option{^-gnato^-gnato^},
11939 and @option{^-gnatE^-gnatE^} switches to the
11940 compiler; the compiler's output is to appear in @file{/common/debug}
11941 @item
11942 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11943 to the compiler; the compiler's output is to appear in @file{/common/release}
11944 @end itemize
11945
11946 @noindent
11947 The GNAT project files shown below, respectively @file{debug.gpr} and
11948 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11949
11950 Schematically:
11951 @smallexample
11952 @group
11953 ^/common^[COMMON]^
11954   debug.gpr
11955   release.gpr
11956   pack.ads
11957   pack.adb
11958   proc.adb
11959 @end group
11960 @group
11961 ^/common/debug^[COMMON.DEBUG]^
11962   proc.ali, proc.o
11963   pack.ali, pack.o
11964 @end group
11965 @group
11966 ^/common/release^[COMMON.RELEASE]^
11967   proc.ali, proc.o
11968   pack.ali, pack.o
11969 @end group
11970 @end smallexample
11971 Here are the corresponding project files:
11972
11973 @smallexample @c projectfile
11974 @group
11975 project Debug is
11976   for Object_Dir use "debug";
11977   for Main use ("proc");
11978
11979   package Builder is
11980     for ^Default_Switches^Default_Switches^ ("Ada")
11981         use ("^-g^-g^");
11982     for Executable ("proc.adb") use "proc1";
11983   end Builder;
11984 @end group
11985
11986 @group
11987   package Compiler is
11988     for ^Default_Switches^Default_Switches^ ("Ada")
11989        use ("-fstack-check",
11990             "^-gnata^-gnata^",
11991             "^-gnato^-gnato^",
11992             "^-gnatE^-gnatE^");
11993   end Compiler;
11994 end Debug;
11995 @end group
11996 @end smallexample
11997
11998 @smallexample @c projectfile
11999 @group
12000 project Release is
12001   for Object_Dir use "release";
12002   for Exec_Dir use ".";
12003   for Main use ("proc");
12004
12005   package Compiler is
12006     for ^Default_Switches^Default_Switches^ ("Ada")
12007         use ("^-O2^-O2^");
12008   end Compiler;
12009 end Release;
12010 @end group
12011 @end smallexample
12012
12013 @noindent
12014 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
12015 insensitive), and analogously the project defined by @file{release.gpr} is
12016 @code{"Release"}.  For consistency the file should have the same name as the
12017 project, and the project file's extension should be @code{"gpr"}. These
12018 conventions are not required, but a warning is issued if they are not followed.
12019
12020 If the current directory is @file{^/temp^[TEMP]^}, then the command
12021 @smallexample
12022 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12023 @end smallexample
12024
12025 @noindent
12026 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12027 as well as the @code{^proc1^PROC1.EXE^} executable,
12028 using the ^switch^switch^ settings defined in the project file.
12029
12030 Likewise, the command
12031 @smallexample
12032 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12033 @end smallexample
12034
12035 @noindent
12036 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12037 and the @code{^proc^PROC.EXE^}
12038 executable in @file{^/common^[COMMON]^},
12039 using the ^switch^switch^ settings from the project file.
12040
12041 @node Source Files
12042 @unnumberedsubsubsec Source Files
12043
12044 @noindent
12045 If a project file does not explicitly specify a set of source directories or
12046 a set of source files, then by default the project's source files are the
12047 Ada source files in the project file directory.  Thus @file{pack.ads},
12048 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12049
12050 @node Specifying the Object Directory
12051 @unnumberedsubsubsec Specifying the Object Directory
12052
12053 @noindent
12054 Several project properties are modeled by Ada-style @emph{attributes};
12055 a property is defined by supplying the equivalent of an Ada attribute
12056 definition clause in the project file.
12057 A project's object directory is another such a property; the corresponding
12058 attribute is @code{Object_Dir}, and its value is also a string expression,
12059 specified either as absolute or relative. In the later case,
12060 it is relative to the project file directory. Thus the compiler's
12061 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12062 (for the @code{Debug} project)
12063 and to @file{^/common/release^[COMMON.RELEASE]^}
12064 (for the @code{Release} project).
12065 If @code{Object_Dir} is not specified, then the default is the project file
12066 directory itself.
12067
12068 @node Specifying the Exec Directory
12069 @unnumberedsubsubsec Specifying the Exec Directory
12070
12071 @noindent
12072 A project's exec directory is another property; the corresponding
12073 attribute is @code{Exec_Dir}, and its value is also a string expression,
12074 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12075 then the default is the object directory (which may also be the project file
12076 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12077 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12078 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12079 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12080
12081 @node Project File Packages
12082 @unnumberedsubsubsec Project File Packages
12083
12084 @noindent
12085 A GNAT tool that is integrated with the Project Manager is modeled by a
12086 corresponding package in the project file. In the example above,
12087 The @code{Debug} project defines the packages @code{Builder}
12088 (for @command{gnatmake}) and @code{Compiler};
12089 the @code{Release} project defines only the @code{Compiler} package.
12090
12091 The Ada-like package syntax is not to be taken literally.  Although packages in
12092 project files bear a surface resemblance to packages in Ada source code, the
12093 notation is simply a way to convey a grouping of properties for a named
12094 entity.  Indeed, the package names permitted in project files are restricted
12095 to a predefined set, corresponding to the project-aware tools, and the contents
12096 of packages are limited to a small set of constructs.
12097 The packages in the example above contain attribute definitions.
12098
12099 @node Specifying ^Switch^Switch^ Settings
12100 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12101
12102 @noindent
12103 ^Switch^Switch^ settings for a project-aware tool can be specified through
12104 attributes in the package that corresponds to the tool.
12105 The example above illustrates one of the relevant attributes,
12106 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12107 in both project files.
12108 Unlike simple attributes like @code{Source_Dirs},
12109 @code{^Default_Switches^Default_Switches^} is
12110 known as an @emph{associative array}.  When you define this attribute, you must
12111 supply an ``index'' (a literal string), and the effect of the attribute
12112 definition is to set the value of the array at the specified index.
12113 For the @code{^Default_Switches^Default_Switches^} attribute,
12114 the index is a programming language (in our case, Ada),
12115 and the value specified (after @code{use}) must be a list
12116 of string expressions.
12117
12118 The attributes permitted in project files are restricted to a predefined set.
12119 Some may appear at project level, others in packages.
12120 For any attribute that is an associative array, the index must always be a
12121 literal string, but the restrictions on this string (e.g., a file name or a
12122 language name) depend on the individual attribute.
12123 Also depending on the attribute, its specified value will need to be either a
12124 string or a string list.
12125
12126 In the @code{Debug} project, we set the switches for two tools,
12127 @command{gnatmake} and the compiler, and thus we include the two corresponding
12128 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12129 attribute with index @code{"Ada"}.
12130 Note that the package corresponding to
12131 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12132 similar, but only includes the @code{Compiler} package.
12133
12134 In project @code{Debug} above, the ^switches^switches^ starting with
12135 @option{-gnat} that are specified in package @code{Compiler}
12136 could have been placed in package @code{Builder}, since @command{gnatmake}
12137 transmits all such ^switches^switches^ to the compiler.
12138
12139 @node Main Subprograms
12140 @unnumberedsubsubsec Main Subprograms
12141
12142 @noindent
12143 One of the specifiable properties of a project is a list of files that contain
12144 main subprograms.  This property is captured in the @code{Main} attribute,
12145 whose value is a list of strings.  If a project defines the @code{Main}
12146 attribute, it is not necessary to identify the main subprogram(s) when
12147 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12148
12149 @node Executable File Names
12150 @unnumberedsubsubsec Executable File Names
12151
12152 @noindent
12153 By default, the executable file name corresponding to a main source is
12154 deduced from the main source file name. Through the attributes
12155 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12156 it is possible to change this default.
12157 In project @code{Debug} above, the executable file name
12158 for main source @file{^proc.adb^PROC.ADB^} is
12159 @file{^proc1^PROC1.EXE^}.
12160 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12161 of the executable files, when no attribute @code{Executable} applies:
12162 its value replace the platform-specific executable suffix.
12163 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12164 specify a non-default executable file name when several mains are built at once
12165 in a single @command{gnatmake} command.
12166
12167 @node Source File Naming Conventions
12168 @unnumberedsubsubsec Source File Naming Conventions
12169
12170 @noindent
12171 Since the project files above do not specify any source file naming
12172 conventions, the GNAT defaults are used.  The mechanism for defining source
12173 file naming conventions -- a package named @code{Naming} --
12174 is described below (@pxref{Naming Schemes}).
12175
12176 @node Source Language(s)
12177 @unnumberedsubsubsec Source Language(s)
12178
12179 @noindent
12180 Since the project files do not specify a @code{Languages} attribute, by
12181 default the GNAT tools assume that the language of the project file is Ada.
12182 More generally, a project can comprise source files
12183 in Ada, C, and/or other languages.
12184
12185 @node Using External Variables
12186 @subsection Using External Variables
12187
12188 @noindent
12189 Instead of supplying different project files for debug and release, we can
12190 define a single project file that queries an external variable (set either
12191 on the command line or via an ^environment variable^logical name^) in order to
12192 conditionally define the appropriate settings.  Again, assume that the
12193 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12194 located in directory @file{^/common^[COMMON]^}.  The following project file,
12195 @file{build.gpr}, queries the external variable named @code{STYLE} and
12196 defines an object directory and ^switch^switch^ settings based on whether
12197 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12198 the default is @code{"deb"}.
12199
12200 @smallexample @c projectfile
12201 @group
12202 project Build is
12203   for Main use ("proc");
12204
12205   type Style_Type is ("deb", "rel");
12206   Style : Style_Type := external ("STYLE", "deb");
12207
12208   case Style is
12209     when "deb" =>
12210       for Object_Dir use "debug";
12211
12212     when "rel" =>
12213       for Object_Dir use "release";
12214       for Exec_Dir use ".";
12215   end case;
12216 @end group
12217
12218 @group
12219   package Builder is
12220
12221     case Style is
12222       when "deb" =>
12223         for ^Default_Switches^Default_Switches^ ("Ada")
12224             use ("^-g^-g^");
12225         for Executable ("proc") use "proc1";
12226       when others =>
12227         null;
12228     end case;
12229
12230   end Builder;
12231 @end group
12232
12233 @group
12234   package Compiler is
12235
12236     case Style is
12237       when "deb" =>
12238         for ^Default_Switches^Default_Switches^ ("Ada")
12239             use ("^-gnata^-gnata^",
12240                  "^-gnato^-gnato^",
12241                  "^-gnatE^-gnatE^");
12242
12243       when "rel" =>
12244         for ^Default_Switches^Default_Switches^ ("Ada")
12245             use ("^-O2^-O2^");
12246     end case;
12247
12248   end Compiler;
12249
12250 end Build;
12251 @end group
12252 @end smallexample
12253
12254 @noindent
12255 @code{Style_Type} is an example of a @emph{string type}, which is the project
12256 file analog of an Ada enumeration type but whose components are string literals
12257 rather than identifiers.  @code{Style} is declared as a variable of this type.
12258
12259 The form @code{external("STYLE", "deb")} is known as an
12260 @emph{external reference}; its first argument is the name of an
12261 @emph{external variable}, and the second argument is a default value to be
12262 used if the external variable doesn't exist.  You can define an external
12263 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12264 or you can use ^an environment variable^a logical name^
12265 as an external variable.
12266
12267 Each @code{case} construct is expanded by the Project Manager based on the
12268 value of @code{Style}. Thus the command
12269 @ifclear vms
12270 @smallexample
12271 gnatmake -P/common/build.gpr -XSTYLE=deb
12272 @end smallexample
12273 @end ifclear
12274
12275 @ifset vms
12276 @smallexample
12277 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12278 @end smallexample
12279 @end ifset
12280
12281 @noindent
12282 is equivalent to the @command{gnatmake} invocation using the project file
12283 @file{debug.gpr} in the earlier example.  So is the command
12284 @smallexample
12285 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12286 @end smallexample
12287
12288 @noindent
12289 since @code{"deb"} is the default for @code{STYLE}.
12290
12291 Analogously,
12292
12293 @ifclear vms
12294 @smallexample
12295 gnatmake -P/common/build.gpr -XSTYLE=rel
12296 @end smallexample
12297 @end ifclear
12298
12299 @ifset vms
12300 @smallexample
12301 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12302 @end smallexample
12303 @end ifset
12304
12305 @noindent
12306 is equivalent to the @command{gnatmake} invocation using the project file
12307 @file{release.gpr} in the earlier example.
12308
12309 @node Importing Other Projects
12310 @subsection Importing Other Projects
12311 @cindex @code{ADA_PROJECT_PATH}
12312 @cindex @code{GPR_PROJECT_PATH}
12313
12314 @noindent
12315 A compilation unit in a source file in one project may depend on compilation
12316 units in source files in other projects.  To compile this unit under
12317 control of a project file, the
12318 dependent project must @emph{import} the projects containing the needed source
12319 files.
12320 This effect is obtained using syntax similar to an Ada @code{with} clause,
12321 but where @code{with}ed entities are strings that denote project files.
12322
12323 As an example, suppose that the two projects @code{GUI_Proj} and
12324 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12325 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12326 and @file{^/comm^[COMM]^}, respectively.
12327 Suppose that the source files for @code{GUI_Proj} are
12328 @file{gui.ads} and @file{gui.adb}, and that the source files for
12329 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12330 files is located in its respective project file directory.  Schematically:
12331
12332 @smallexample
12333 @group
12334 ^/gui^[GUI]^
12335   gui_proj.gpr
12336   gui.ads
12337   gui.adb
12338 @end group
12339
12340 @group
12341 ^/comm^[COMM]^
12342   comm_proj.gpr
12343   comm.ads
12344   comm.adb
12345 @end group
12346 @end smallexample
12347
12348 @noindent
12349 We want to develop an application in directory @file{^/app^[APP]^} that
12350 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12351 the corresponding project files (e.g.@: the ^switch^switch^ settings
12352 and object directory).
12353 Skeletal code for a main procedure might be something like the following:
12354
12355 @smallexample @c ada
12356 @group
12357 with GUI, Comm;
12358 procedure App_Main is
12359    @dots{}
12360 begin
12361    @dots{}
12362 end App_Main;
12363 @end group
12364 @end smallexample
12365
12366 @noindent
12367 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12368 effect:
12369
12370 @smallexample @c projectfile
12371 @group
12372 with "/gui/gui_proj", "/comm/comm_proj";
12373 project App_Proj is
12374    for Main use ("app_main");
12375 end App_Proj;
12376 @end group
12377 @end smallexample
12378
12379 @noindent
12380 Building an executable is achieved through the command:
12381 @smallexample
12382 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12383 @end smallexample
12384 @noindent
12385 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12386 in the directory where @file{app_proj.gpr} resides.
12387
12388 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12389 (as illustrated above) the @code{with} clause can omit the extension.
12390
12391 Our example specified an absolute path for each imported project file.
12392 Alternatively, the directory name of an imported object can be omitted
12393 if either
12394 @itemize @bullet
12395 @item
12396 The imported project file is in the same directory as the importing project
12397 file, or
12398 @item
12399 You have defined one or two ^environment variables^logical names^
12400 that includes the directory containing
12401 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12402 @code{ADA_PROJECT_PATH} is the same as
12403 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12404 directory names separated by colons (semicolons on Windows).
12405 @end itemize
12406
12407 @noindent
12408 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12409 to include @file{^/gui^[GUI]^} and
12410 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12411 as follows:
12412
12413 @smallexample @c projectfile
12414 @group
12415 with "gui_proj", "comm_proj";
12416 project App_Proj is
12417    for Main use ("app_main");
12418 end App_Proj;
12419 @end group
12420 @end smallexample
12421
12422 @noindent
12423 Importing other projects can create ambiguities.
12424 For example, the same unit might be present in different imported projects, or
12425 it might be present in both the importing project and in an imported project.
12426 Both of these conditions are errors.  Note that in the current version of
12427 the Project Manager, it is illegal to have an ambiguous unit even if the
12428 unit is never referenced by the importing project.  This restriction may be
12429 relaxed in a future release.
12430
12431 @node Extending a Project
12432 @subsection Extending a Project
12433
12434 @noindent
12435 In large software systems it is common to have multiple
12436 implementations of a common interface; in Ada terms, multiple versions of a
12437 package body for the same spec.  For example, one implementation
12438 might be safe for use in tasking programs, while another might only be used
12439 in sequential applications.  This can be modeled in GNAT using the concept
12440 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12441 another project (the ``parent'') then by default all source files of the
12442 parent project are inherited by the child, but the child project can
12443 override any of the parent's source files with new versions, and can also
12444 add new files.  This facility is the project analog of a type extension in
12445 Object-Oriented Programming.  Project hierarchies are permitted (a child
12446 project may be the parent of yet another project), and a project that
12447 inherits one project can also import other projects.
12448
12449 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12450 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12451 @file{pack.adb}, and @file{proc.adb}:
12452
12453 @smallexample
12454 @group
12455 ^/seq^[SEQ]^
12456   pack.ads
12457   pack.adb
12458   proc.adb
12459   seq_proj.gpr
12460 @end group
12461 @end smallexample
12462
12463 @noindent
12464 Note that the project file can simply be empty (that is, no attribute or
12465 package is defined):
12466
12467 @smallexample @c projectfile
12468 @group
12469 project Seq_Proj is
12470 end Seq_Proj;
12471 @end group
12472 @end smallexample
12473
12474 @noindent
12475 implying that its source files are all the Ada source files in the project
12476 directory.
12477
12478 Suppose we want to supply an alternate version of @file{pack.adb}, in
12479 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12480 @file{pack.ads} and @file{proc.adb}.  We can define a project
12481 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12482
12483 @smallexample
12484 @group
12485 ^/tasking^[TASKING]^
12486   pack.adb
12487   tasking_proj.gpr
12488 @end group
12489
12490 @group
12491 project Tasking_Proj extends "/seq/seq_proj" is
12492 end Tasking_Proj;
12493 @end group
12494 @end smallexample
12495
12496 @noindent
12497 The version of @file{pack.adb} used in a build depends on which project file
12498 is specified.
12499
12500 Note that we could have obtained the desired behavior using project import
12501 rather than project inheritance; a @code{base} project would contain the
12502 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12503 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12504 would import @code{base} and add a different version of @file{pack.adb}.  The
12505 choice depends on whether other sources in the original project need to be
12506 overridden.  If they do, then project extension is necessary, otherwise,
12507 importing is sufficient.
12508
12509 @noindent
12510 In a project file that extends another project file, it is possible to
12511 indicate that an inherited source is not part of the sources of the extending
12512 project. This is necessary sometimes when a package spec has been overloaded
12513 and no longer requires a body: in this case, it is necessary to indicate that
12514 the inherited body is not part of the sources of the project, otherwise there
12515 will be a compilation error when compiling the spec.
12516
12517 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12518 Its value is a string list: a list of file names. It is also possible to use
12519 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12520 the file name of a text file containing a list of file names, one per line.
12521
12522 @smallexample @c @projectfile
12523 project B extends "a" is
12524    for Source_Files use ("pkg.ads");
12525    --  New spec of Pkg does not need a completion
12526    for Excluded_Source_Files use ("pkg.adb");
12527 end B;
12528 @end smallexample
12529
12530 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12531 is still needed: if it is possible to build using @command{gnatmake} when such
12532 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12533 it is possible to remove the source completely from a system that includes
12534 project P.
12535
12536 @c ***********************
12537 @c * Project File Syntax *
12538 @c ***********************
12539
12540 @node Project File Syntax
12541 @section Project File Syntax
12542
12543 @menu
12544 * Basic Syntax::
12545 * Qualified Projects::
12546 * Packages::
12547 * Expressions::
12548 * String Types::
12549 * Variables::
12550 * Attributes::
12551 * Associative Array Attributes::
12552 * case Constructions::
12553 @end menu
12554
12555 @noindent
12556 This section describes the structure of project files.
12557
12558 A project may be an @emph{independent project}, entirely defined by a single
12559 project file. Any Ada source file in an independent project depends only
12560 on the predefined library and other Ada source files in the same project.
12561
12562 @noindent
12563 A project may also @dfn{depend on} other projects, in either or both of
12564 the following ways:
12565 @itemize @bullet
12566 @item It may import any number of projects
12567 @item It may extend at most one other project
12568 @end itemize
12569
12570 @noindent
12571 The dependence relation is a directed acyclic graph (the subgraph reflecting
12572 the ``extends'' relation is a tree).
12573
12574 A project's @dfn{immediate sources} are the source files directly defined by
12575 that project, either implicitly by residing in the project file's directory,
12576 or explicitly through any of the source-related attributes described below.
12577 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12578 of @var{proj} together with the immediate sources (unless overridden) of any
12579 project on which @var{proj} depends (either directly or indirectly).
12580
12581 @node Basic Syntax
12582 @subsection Basic Syntax
12583
12584 @noindent
12585 As seen in the earlier examples, project files have an Ada-like syntax.
12586 The minimal project file is:
12587 @smallexample @c projectfile
12588 @group
12589 project Empty is
12590
12591 end Empty;
12592 @end group
12593 @end smallexample
12594
12595 @noindent
12596 The identifier @code{Empty} is the name of the project.
12597 This project name must be present after the reserved
12598 word @code{end} at the end of the project file, followed by a semi-colon.
12599
12600 Any name in a project file, such as the project name or a variable name,
12601 has the same syntax as an Ada identifier.
12602
12603 The reserved words of project files are the Ada 95 reserved words plus
12604 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12605 reserved words currently used in project file syntax are:
12606
12607 @itemize @bullet
12608 @item
12609 @code{all}
12610 @item
12611 @code{at}
12612 @item
12613 @code{case}
12614 @item
12615 @code{end}
12616 @item
12617 @code{for}
12618 @item
12619 @code{is}
12620 @item
12621 @code{limited}
12622 @item
12623 @code{null}
12624 @item
12625 @code{others}
12626 @item
12627 @code{package}
12628 @item
12629 @code{renames}
12630 @item
12631 @code{type}
12632 @item
12633 @code{use}
12634 @item
12635 @code{when}
12636 @item
12637 @code{with}
12638 @end itemize
12639
12640 @noindent
12641 Comments in project files have the same syntax as in Ada, two consecutive
12642 hyphens through the end of the line.
12643
12644 @node Qualified Projects
12645 @subsection Qualified Projects
12646
12647 @noindent
12648 Before the reserved @code{project}, there may be one or two "qualifiers", that
12649 is identifiers or other reserved words, to qualify the project.
12650
12651 The current list of qualifiers is:
12652
12653 @itemize @bullet
12654 @item
12655 @code{abstract}: qualify a project with no sources. A qualified abstract
12656 project must either have no declaration of attributes @code{Source_Dirs},
12657 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12658 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12659 as empty. If it extends another project, the project it extends must also be a
12660 qualified abstract project.
12661
12662 @item
12663 @code{standard}: a standard project is a non library project with sources.
12664
12665 @item
12666 @code{aggregate}: for future extension
12667
12668 @item
12669 @code{aggregate library}: for future extension
12670
12671 @item
12672 @code{library}: a library project must declare both attributes
12673 @code{Library_Name} and @code{Library_Dir}.
12674
12675 @item
12676 @code{configuration}: a configuration project cannot be in a project tree.
12677 @end itemize
12678
12679 @node Packages
12680 @subsection Packages
12681
12682 @noindent
12683 A project file may contain @emph{packages}. The name of a package must be one
12684 of the identifiers from the following list. A package
12685 with a given name may only appear once in a project file. Package names are
12686 case insensitive. The following package names are legal:
12687
12688 @itemize @bullet
12689 @item
12690 @code{Naming}
12691 @item
12692 @code{Builder}
12693 @item
12694 @code{Compiler}
12695 @item
12696 @code{Binder}
12697 @item
12698 @code{Linker}
12699 @item
12700 @code{Finder}
12701 @item
12702 @code{Cross_Reference}
12703 @item
12704 @code{Check}
12705 @item
12706 @code{Eliminate}
12707 @item
12708 @code{Pretty_Printer}
12709 @item
12710 @code{Metrics}
12711 @item
12712 @code{gnatls}
12713 @item
12714 @code{gnatstub}
12715 @item
12716 @code{IDE}
12717 @item
12718 @code{Language_Processing}
12719 @end itemize
12720
12721 @noindent
12722 In its simplest form, a package may be empty:
12723
12724 @smallexample @c projectfile
12725 @group
12726 project Simple is
12727   package Builder is
12728   end Builder;
12729 end Simple;
12730 @end group
12731 @end smallexample
12732
12733 @noindent
12734 A package may contain @emph{attribute declarations},
12735 @emph{variable declarations} and @emph{case constructions}, as will be
12736 described below.
12737
12738 When there is ambiguity between a project name and a package name,
12739 the name always designates the project. To avoid possible confusion, it is
12740 always a good idea to avoid naming a project with one of the
12741 names allowed for packages or any name that starts with @code{gnat}.
12742
12743 @node Expressions
12744 @subsection Expressions
12745
12746 @noindent
12747 An @emph{expression} is either a @emph{string expression} or a
12748 @emph{string list expression}.
12749
12750 A @emph{string expression} is either a @emph{simple string expression} or a
12751 @emph{compound string expression}.
12752
12753 A @emph{simple string expression} is one of the following:
12754 @itemize @bullet
12755 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12756 @item A string-valued variable reference (@pxref{Variables})
12757 @item A string-valued attribute reference (@pxref{Attributes})
12758 @item An external reference (@pxref{External References in Project Files})
12759 @end itemize
12760
12761 @noindent
12762 A @emph{compound string expression} is a concatenation of string expressions,
12763 using the operator @code{"&"}
12764 @smallexample
12765        Path & "/" & File_Name & ".ads"
12766 @end smallexample
12767
12768 @noindent
12769 A @emph{string list expression} is either a
12770 @emph{simple string list expression} or a
12771 @emph{compound string list expression}.
12772
12773 A @emph{simple string list expression} is one of the following:
12774 @itemize @bullet
12775 @item A parenthesized list of zero or more string expressions,
12776 separated by commas
12777 @smallexample
12778    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12779    Empty_List := ();
12780 @end smallexample
12781 @item A string list-valued variable reference
12782 @item A string list-valued attribute reference
12783 @end itemize
12784
12785 @noindent
12786 A @emph{compound string list expression} is the concatenation (using
12787 @code{"&"}) of a simple string list expression and an expression.  Note that
12788 each term in a compound string list expression, except the first, may be
12789 either a string expression or a string list expression.
12790
12791 @smallexample @c projectfile
12792 @group
12793    File_Name_List := () & File_Name; --  One string in this list
12794    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12795    --  Two strings
12796    Big_List := File_Name_List & Extended_File_Name_List;
12797    --  Concatenation of two string lists: three strings
12798    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12799    --  Illegal: must start with a string list
12800 @end group
12801 @end smallexample
12802
12803 @node String Types
12804 @subsection String Types
12805
12806 @noindent
12807 A @emph{string type declaration} introduces a discrete set of string literals.
12808 If a string variable is declared to have this type, its value
12809 is restricted to the given set of literals.
12810
12811 Here is an example of a string type declaration:
12812
12813 @smallexample @c projectfile
12814    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12815 @end smallexample
12816
12817 @noindent
12818 Variables of a string type are called @emph{typed variables}; all other
12819 variables are called @emph{untyped variables}. Typed variables are
12820 particularly useful in @code{case} constructions, to support conditional
12821 attribute declarations.
12822 (@pxref{case Constructions}).
12823
12824 The string literals in the list are case sensitive and must all be different.
12825 They may include any graphic characters allowed in Ada, including spaces.
12826
12827 A string type may only be declared at the project level, not inside a package.
12828
12829 A string type may be referenced by its name if it has been declared in the same
12830 project file, or by an expanded name whose prefix is the name of the project
12831 in which it is declared.
12832
12833 @node Variables
12834 @subsection Variables
12835
12836 @noindent
12837 A variable may be declared at the project file level, or within a package.
12838 Here are some examples of variable declarations:
12839
12840 @smallexample @c projectfile
12841 @group
12842    This_OS : OS := external ("OS"); --  a typed variable declaration
12843    That_OS := "GNU/Linux";          --  an untyped variable declaration
12844 @end group
12845 @end smallexample
12846
12847 @noindent
12848 The syntax of a @emph{typed variable declaration} is identical to the Ada
12849 syntax for an object declaration. By contrast, the syntax of an untyped
12850 variable declaration is identical to an Ada assignment statement. In fact,
12851 variable declarations in project files have some of the characteristics of
12852 an assignment, in that successive declarations for the same variable are
12853 allowed. Untyped variable declarations do establish the expected kind of the
12854 variable (string or string list), and successive declarations for it must
12855 respect the initial kind.
12856
12857 @noindent
12858 A string variable declaration (typed or untyped) declares a variable
12859 whose value is a string. This variable may be used as a string expression.
12860 @smallexample @c projectfile
12861    File_Name       := "readme.txt";
12862    Saved_File_Name := File_Name & ".saved";
12863 @end smallexample
12864
12865 @noindent
12866 A string list variable declaration declares a variable whose value is a list
12867 of strings. The list may contain any number (zero or more) of strings.
12868
12869 @smallexample @c projectfile
12870    Empty_List := ();
12871    List_With_One_Element := ("^-gnaty^-gnaty^");
12872    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12873    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12874                  "pack2.ada", "util_.ada", "util.ada");
12875 @end smallexample
12876
12877 @noindent
12878 The same typed variable may not be declared more than once at project level,
12879 and it may not be declared more than once in any package; it is in effect
12880 a constant.
12881
12882 The same untyped variable may be declared several times. Declarations are
12883 elaborated in the order in which they appear, so  the new value replaces
12884 the old one, and any subsequent reference to the variable uses the new value.
12885 However, as noted above, if a variable has been declared as a string, all
12886 subsequent
12887 declarations must give it a string value. Similarly, if a variable has
12888 been declared as a string list, all subsequent declarations
12889 must give it a string list value.
12890
12891 A @emph{variable reference} may take several forms:
12892
12893 @itemize @bullet
12894 @item The simple variable name, for a variable in the current package (if any)
12895 or in the current project
12896 @item An expanded name, whose prefix is a context name.
12897 @end itemize
12898
12899 @noindent
12900 A @emph{context} may be one of the following:
12901
12902 @itemize @bullet
12903 @item The name of an existing package in the current project
12904 @item The name of an imported project of the current project
12905 @item The name of an ancestor project (i.e., a project extended by the current
12906 project, either directly or indirectly)
12907 @item An expanded name whose prefix is an imported/parent project name, and
12908 whose selector is a package name in that project.
12909 @end itemize
12910
12911 @noindent
12912 A variable reference may be used in an expression.
12913
12914 @node Attributes
12915 @subsection Attributes
12916
12917 @noindent
12918 A project (and its packages) may have @emph{attributes} that define
12919 the project's properties.  Some attributes have values that are strings;
12920 others have values that are string lists.
12921
12922 There are two categories of attributes: @emph{simple attributes}
12923 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12924
12925 Legal project attribute names, and attribute names for each legal package are
12926 listed below. Attributes names are case-insensitive.
12927
12928 The following attributes are defined on projects (all are simple attributes):
12929
12930 @multitable @columnfractions .4 .3
12931 @item @emph{Attribute Name}
12932 @tab @emph{Value}
12933 @item @code{Source_Files}
12934 @tab string list
12935 @item @code{Source_Dirs}
12936 @tab string list
12937 @item @code{Source_List_File}
12938 @tab string
12939 @item @code{Object_Dir}
12940 @tab string
12941 @item @code{Exec_Dir}
12942 @tab string
12943 @item @code{Excluded_Source_Dirs}
12944 @tab string list
12945 @item @code{Excluded_Source_Files}
12946 @tab string list
12947 @item @code{Excluded_Source_List_File}
12948 @tab string
12949 @item @code{Languages}
12950 @tab string list
12951 @item @code{Main}
12952 @tab string list
12953 @item @code{Library_Dir}
12954 @tab string
12955 @item @code{Library_Name}
12956 @tab string
12957 @item @code{Library_Kind}
12958 @tab string
12959 @item @code{Library_Version}
12960 @tab string
12961 @item @code{Library_Interface}
12962 @tab string
12963 @item @code{Library_Auto_Init}
12964 @tab string
12965 @item @code{Library_Options}
12966 @tab string list
12967 @item @code{Library_Src_Dir}
12968 @tab string
12969 @item @code{Library_ALI_Dir}
12970 @tab string
12971 @item @code{Library_GCC}
12972 @tab string
12973 @item @code{Library_Symbol_File}
12974 @tab string
12975 @item @code{Library_Symbol_Policy}
12976 @tab string
12977 @item @code{Library_Reference_Symbol_File}
12978 @tab string
12979 @item @code{Externally_Built}
12980 @tab string
12981 @end multitable
12982
12983 @noindent
12984 The following attributes are defined for package  @code{Naming}
12985 (@pxref{Naming Schemes}):
12986
12987 @multitable @columnfractions .4 .2 .2 .2
12988 @item Attribute Name @tab Category @tab Index @tab Value
12989 @item @code{Spec_Suffix}
12990 @tab associative array
12991 @tab language name
12992 @tab string
12993 @item @code{Body_Suffix}
12994 @tab associative array
12995 @tab language name
12996 @tab string
12997 @item @code{Separate_Suffix}
12998 @tab simple attribute
12999 @tab n/a
13000 @tab string
13001 @item @code{Casing}
13002 @tab simple attribute
13003 @tab n/a
13004 @tab string
13005 @item @code{Dot_Replacement}
13006 @tab simple attribute
13007 @tab n/a
13008 @tab string
13009 @item @code{Spec}
13010 @tab associative array
13011 @tab Ada unit name
13012 @tab string
13013 @item @code{Body}
13014 @tab associative array
13015 @tab Ada unit name
13016 @tab string
13017 @item @code{Specification_Exceptions}
13018 @tab associative array
13019 @tab language name
13020 @tab string list
13021 @item @code{Implementation_Exceptions}
13022 @tab associative array
13023 @tab language name
13024 @tab string list
13025 @end multitable
13026
13027 @noindent
13028 The following attributes are defined for packages @code{Builder},
13029 @code{Compiler}, @code{Binder},
13030 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13031 (@pxref{^Switches^Switches^ and Project Files}).
13032
13033 @multitable @columnfractions .4 .2 .2 .2
13034 @item Attribute Name @tab Category @tab Index @tab Value
13035 @item @code{^Default_Switches^Default_Switches^}
13036 @tab associative array
13037 @tab language name
13038 @tab string list
13039 @item @code{^Switches^Switches^}
13040 @tab associative array
13041 @tab file name
13042 @tab string list
13043 @end multitable
13044
13045 @noindent
13046 In addition, package @code{Compiler} has a single string attribute
13047 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13048 string attribute @code{Global_Configuration_Pragmas}.
13049
13050 @noindent
13051 Each simple attribute has a default value: the empty string (for string-valued
13052 attributes) and the empty list (for string list-valued attributes).
13053
13054 An attribute declaration defines a new value for an attribute.
13055
13056 Examples of simple attribute declarations:
13057
13058 @smallexample @c projectfile
13059    for Object_Dir use "objects";
13060    for Source_Dirs use ("units", "test/drivers");
13061 @end smallexample
13062
13063 @noindent
13064 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13065 attribute definition clause in Ada.
13066
13067 Attributes references may be appear in expressions.
13068 The general form for such a reference is @code{<entity>'<attribute>}:
13069 Associative array attributes are functions. Associative
13070 array attribute references must have an argument that is a string literal.
13071
13072 Examples are:
13073
13074 @smallexample @c projectfile
13075   project'Object_Dir
13076   Naming'Dot_Replacement
13077   Imported_Project'Source_Dirs
13078   Imported_Project.Naming'Casing
13079   Builder'^Default_Switches^Default_Switches^("Ada")
13080 @end smallexample
13081
13082 @noindent
13083 The prefix of an attribute may be:
13084 @itemize @bullet
13085 @item @code{project} for an attribute of the current project
13086 @item The name of an existing package of the current project
13087 @item The name of an imported project
13088 @item The name of a parent project that is extended by the current project
13089 @item An expanded name whose prefix is imported/parent project name,
13090 and whose selector is a package name
13091 @end itemize
13092
13093 @noindent
13094 Example:
13095 @smallexample @c projectfile
13096 @group
13097    project Prj is
13098      for Source_Dirs use project'Source_Dirs & "units";
13099      for Source_Dirs use project'Source_Dirs & "test/drivers"
13100    end Prj;
13101 @end group
13102 @end smallexample
13103
13104 @noindent
13105 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13106 has the default value: an empty string list. After this declaration,
13107 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13108 After the second attribute declaration @code{Source_Dirs} is a string list of
13109 two elements: @code{"units"} and @code{"test/drivers"}.
13110
13111 Note: this example is for illustration only. In practice,
13112 the project file would contain only one attribute declaration:
13113
13114 @smallexample @c projectfile
13115    for Source_Dirs use ("units", "test/drivers");
13116 @end smallexample
13117
13118 @node Associative Array Attributes
13119 @subsection Associative Array Attributes
13120
13121 @noindent
13122 Some attributes are defined as @emph{associative arrays}. An associative
13123 array may be regarded as a function that takes a string as a parameter
13124 and delivers a string or string list value as its result.
13125
13126 Here are some examples of single associative array attribute associations:
13127
13128 @smallexample @c projectfile
13129    for Body ("main") use "Main.ada";
13130    for ^Switches^Switches^ ("main.ada")
13131        use ("^-v^-v^",
13132             "^-gnatv^-gnatv^");
13133    for ^Switches^Switches^ ("main.ada")
13134             use Builder'^Switches^Switches^ ("main.ada")
13135               & "^-g^-g^";
13136 @end smallexample
13137
13138 @noindent
13139 Like untyped variables and simple attributes, associative array attributes
13140 may be declared several times. Each declaration supplies a new value for the
13141 attribute, and replaces the previous setting.
13142
13143 @noindent
13144 An associative array attribute may be declared as a full associative array
13145 declaration, with the value of the same attribute in an imported or extended
13146 project.
13147
13148 @smallexample @c projectfile
13149    package Builder is
13150       for Default_Switches use Default.Builder'Default_Switches;
13151    end Builder;
13152 @end smallexample
13153
13154 @noindent
13155 In this example, @code{Default} must be either a project imported by the
13156 current project, or the project that the current project extends. If the
13157 attribute is in a package (in this case, in package @code{Builder}), the same
13158 package needs to be specified.
13159
13160 @noindent
13161 A full associative array declaration replaces any other declaration for the
13162 attribute, including other full associative array declaration. Single
13163 associative array associations may be declare after a full associative
13164 declaration, modifying the value for a single association of the attribute.
13165
13166 @node case Constructions
13167 @subsection @code{case} Constructions
13168
13169 @noindent
13170 A @code{case} construction is used in a project file to effect conditional
13171 behavior.
13172 Here is a typical example:
13173
13174 @smallexample @c projectfile
13175 @group
13176 project MyProj is
13177    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13178
13179    OS : OS_Type := external ("OS", "GNU/Linux");
13180 @end group
13181
13182 @group
13183    package Compiler is
13184      case OS is
13185        when "GNU/Linux" | "Unix" =>
13186          for ^Default_Switches^Default_Switches^ ("Ada")
13187              use ("^-gnath^-gnath^");
13188        when "NT" =>
13189          for ^Default_Switches^Default_Switches^ ("Ada")
13190              use ("^-gnatP^-gnatP^");
13191        when others =>
13192      end case;
13193    end Compiler;
13194 end MyProj;
13195 @end group
13196 @end smallexample
13197
13198 @noindent
13199 The syntax of a @code{case} construction is based on the Ada case statement
13200 (although there is no @code{null} construction for empty alternatives).
13201
13202 The case expression must be a typed string variable.
13203 Each alternative comprises the reserved word @code{when}, either a list of
13204 literal strings separated by the @code{"|"} character or the reserved word
13205 @code{others},  and the @code{"=>"} token.
13206 Each literal string must belong to the string type that is the type of the
13207 case variable.
13208 An @code{others} alternative, if present, must occur last.
13209
13210 After each @code{=>}, there are zero or more constructions.  The only
13211 constructions allowed in a case construction are other case constructions,
13212 attribute declarations and variable declarations. String type declarations and
13213 package declarations are not allowed. Variable declarations are restricted to
13214 variables that have already been declared before the case construction.
13215
13216 The value of the case variable is often given by an external reference
13217 (@pxref{External References in Project Files}).
13218
13219 @c ****************************************
13220 @c * Objects and Sources in Project Files *
13221 @c ****************************************
13222
13223 @node Objects and Sources in Project Files
13224 @section Objects and Sources in Project Files
13225
13226 @menu
13227 * Object Directory::
13228 * Exec Directory::
13229 * Source Directories::
13230 * Source File Names::
13231 @end menu
13232
13233 @noindent
13234 Each project has exactly one object directory and one or more source
13235 directories. The source directories must contain at least one source file,
13236 unless  the project file explicitly specifies that no source files are present
13237 (@pxref{Source File Names}).
13238
13239 @node Object Directory
13240 @subsection Object Directory
13241
13242 @noindent
13243 The object directory for a project is the directory containing the compiler's
13244 output (such as @file{ALI} files and object files) for the project's immediate
13245 sources.
13246
13247 The object directory is given by the value of the attribute @code{Object_Dir}
13248 in the project file.
13249
13250 @smallexample @c projectfile
13251    for Object_Dir use "objects";
13252 @end smallexample
13253
13254 @noindent
13255 The attribute @code{Object_Dir} has a string value, the path name of the object
13256 directory. The path name may be absolute or relative to the directory of the
13257 project file. This directory must already exist, and be readable and writable.
13258
13259 By default, when the attribute @code{Object_Dir} is not given an explicit value
13260 or when its value is the empty string, the object directory is the same as the
13261 directory containing the project file.
13262
13263 @node Exec Directory
13264 @subsection Exec Directory
13265
13266 @noindent
13267 The exec directory for a project is the directory containing the executables
13268 for the project's main subprograms.
13269
13270 The exec directory is given by the value of the attribute @code{Exec_Dir}
13271 in the project file.
13272
13273 @smallexample @c projectfile
13274    for Exec_Dir use "executables";
13275 @end smallexample
13276
13277 @noindent
13278 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13279 directory. The path name may be absolute or relative to the directory of the
13280 project file. This directory must already exist, and be writable.
13281
13282 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13283 or when its value is the empty string, the exec directory is the same as the
13284 object directory of the project file.
13285
13286 @node Source Directories
13287 @subsection Source Directories
13288
13289 @noindent
13290 The source directories of a project are specified by the project file
13291 attribute @code{Source_Dirs}.
13292
13293 This attribute's value is a string list. If the attribute is not given an
13294 explicit value, then there is only one source directory, the one where the
13295 project file resides.
13296
13297 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13298 as in
13299
13300 @smallexample @c projectfile
13301     for Source_Dirs use ();
13302 @end smallexample
13303
13304 @noindent
13305 indicates that the project contains no source files.
13306
13307 Otherwise, each string in the string list designates one or more
13308 source directories.
13309
13310 @smallexample @c projectfile
13311    for Source_Dirs use ("sources", "test/drivers");
13312 @end smallexample
13313
13314 @noindent
13315 If a string in the list ends with @code{"/**"},  then the directory whose path
13316 name precedes the two asterisks, as well as all its subdirectories
13317 (recursively), are source directories.
13318
13319 @smallexample @c projectfile
13320    for Source_Dirs use ("/system/sources/**");
13321 @end smallexample
13322
13323 @noindent
13324 Here the directory @code{/system/sources} and all of its subdirectories
13325 (recursively) are source directories.
13326
13327 To specify that the source directories are the directory of the project file
13328 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13329 @smallexample @c projectfile
13330    for Source_Dirs use ("./**");
13331 @end smallexample
13332
13333 @noindent
13334 Each of the source directories must exist and be readable.
13335
13336 @node Source File Names
13337 @subsection Source File Names
13338
13339 @noindent
13340 In a project that contains source files, their names may be specified by the
13341 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13342 (a string). Source file names never include any directory information.
13343
13344 If the attribute @code{Source_Files} is given an explicit value, then each
13345 element of the list is a source file name.
13346
13347 @smallexample @c projectfile
13348    for Source_Files use ("main.adb");
13349    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13350 @end smallexample
13351
13352 @noindent
13353 If the attribute @code{Source_Files} is not given an explicit value,
13354 but the attribute @code{Source_List_File} is given a string value,
13355 then the source file names are contained in the text file whose path name
13356 (absolute or relative to the directory of the project file) is the
13357 value of the attribute @code{Source_List_File}.
13358
13359 Each line in the file that is not empty or is not a comment
13360 contains a source file name.
13361
13362 @smallexample @c projectfile
13363    for Source_List_File use "source_list.txt";
13364 @end smallexample
13365
13366 @noindent
13367 By default, if neither the attribute @code{Source_Files} nor the attribute
13368 @code{Source_List_File} is given an explicit value, then each file in the
13369 source directories that conforms to the project's naming scheme
13370 (@pxref{Naming Schemes}) is an immediate source of the project.
13371
13372 A warning is issued if both attributes @code{Source_Files} and
13373 @code{Source_List_File} are given explicit values. In this case, the attribute
13374 @code{Source_Files} prevails.
13375
13376 Each source file name must be the name of one existing source file
13377 in one of the source directories.
13378
13379 A @code{Source_Files} attribute whose value is an empty list
13380 indicates that there are no source files in the project.
13381
13382 If the order of the source directories is known statically, that is if
13383 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13384 be several files with the same source file name. In this case, only the file
13385 in the first directory is considered as an immediate source of the project
13386 file. If the order of the source directories is not known statically, it is
13387 an error to have several files with the same source file name.
13388
13389 Projects can be specified to have no Ada source
13390 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13391 list, or the @code{"Ada"} may be absent from @code{Languages}:
13392
13393 @smallexample @c projectfile
13394    for Source_Dirs use ();
13395    for Source_Files use ();
13396    for Languages use ("C", "C++");
13397 @end smallexample
13398
13399 @noindent
13400 Otherwise, a project must contain at least one immediate source.
13401
13402 Projects with no source files are useful as template packages
13403 (@pxref{Packages in Project Files}) for other projects; in particular to
13404 define a package @code{Naming} (@pxref{Naming Schemes}).
13405
13406 @c ****************************
13407 @c * Importing Projects *
13408 @c ****************************
13409
13410 @node  Importing Projects
13411 @section Importing Projects
13412 @cindex @code{ADA_PROJECT_PATH}
13413 @cindex @code{GPR_PROJECT_PATH}
13414
13415 @noindent
13416 An immediate source of a project P may depend on source files that
13417 are neither immediate sources of P nor in the predefined library.
13418 To get this effect, P must @emph{import} the projects that contain the needed
13419 source files.
13420
13421 @smallexample @c projectfile
13422 @group
13423   with "project1", "utilities.gpr";
13424   with "/namings/apex.gpr";
13425   project Main is
13426     @dots{}
13427 @end group
13428 @end smallexample
13429
13430 @noindent
13431 As can be seen in this example, the syntax for importing projects is similar
13432 to the syntax for importing compilation units in Ada. However, project files
13433 use literal strings instead of names, and the @code{with} clause identifies
13434 project files rather than packages.
13435
13436 Each literal string is the file name or path name (absolute or relative) of a
13437 project file. If a string corresponds to a file name, with no path or a
13438 relative path, then its location is determined by the @emph{project path}. The
13439 latter can be queried using @code{gnatls -v}. It contains:
13440
13441 @itemize @bullet
13442 @item
13443 In first position, the directory containing the current project file.
13444 @item
13445 In last position, the default project directory. This default project directory
13446 is part of the GNAT installation and is the standard place to install project
13447 files giving access to standard support libraries.
13448 @ifclear vms
13449 @ref{Installing a library}
13450 @end ifclear
13451
13452 @item
13453 In between, all the directories referenced in the
13454 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13455 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13456 @end itemize
13457
13458 @noindent
13459 If a relative pathname is used, as in
13460
13461 @smallexample @c projectfile
13462   with "tests/proj";
13463 @end smallexample
13464
13465 @noindent
13466 then the full path for the project is constructed by concatenating this
13467 relative path to those in the project path, in order, until a matching file is
13468 found. Any symbolic link will be fully resolved in the directory of the
13469 importing project file before the imported project file is examined.
13470
13471 If the @code{with}'ed project file name does not have an extension,
13472 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13473 then the file name as specified in the @code{with} clause (no extension) will
13474 be used. In the above example, if a file @code{project1.gpr} is found, then it
13475 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13476 then it will be used; if neither file exists, this is an error.
13477
13478 A warning is issued if the name of the project file does not match the
13479 name of the project; this check is case insensitive.
13480
13481 Any source file that is an immediate source of the imported project can be
13482 used by the immediate sources of the importing project, transitively. Thus
13483 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13484 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13485 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13486 because if and when @code{B} ceases to import @code{C}, some sources in
13487 @code{A} will no longer compile.
13488
13489 A side effect of this capability is that normally cyclic dependencies are not
13490 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13491 is not allowed to import @code{A}. However, there are cases when cyclic
13492 dependencies would be beneficial. For these cases, another form of import
13493 between projects exists, the @code{limited with}: a project @code{A} that
13494 imports a project @code{B} with a straight @code{with} may also be imported,
13495 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13496 to @code{A} include at least one @code{limited with}.
13497
13498 @smallexample @c 0projectfile
13499 with "../b/b.gpr";
13500 with "../c/c.gpr";
13501 project A is
13502 end A;
13503
13504 limited with "../a/a.gpr";
13505 project B is
13506 end B;
13507
13508 with "../d/d.gpr";
13509 project C is
13510 end C;
13511
13512 limited with "../a/a.gpr";
13513 project D is
13514 end D;
13515 @end smallexample
13516
13517 @noindent
13518 In the above legal example, there are two project cycles:
13519 @itemize @bullet
13520 @item A-> B-> A
13521 @item A -> C -> D -> A
13522 @end itemize
13523
13524 @noindent
13525 In each of these cycle there is one @code{limited with}: import of @code{A}
13526 from @code{B} and import of @code{A} from @code{D}.
13527
13528 The difference between straight @code{with} and @code{limited with} is that
13529 the name of a project imported with a @code{limited with} cannot be used in the
13530 project that imports it. In particular, its packages cannot be renamed and
13531 its variables cannot be referred to.
13532
13533 An exception to the above rules for @code{limited with} is that for the main
13534 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13535 @code{limited with} is equivalent to a straight @code{with}. For example,
13536 in the example above, projects @code{B} and @code{D} could not be main
13537 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13538 each have a @code{limited with} that is the only one in a cycle of importing
13539 projects.
13540
13541 @c *********************
13542 @c * Project Extension *
13543 @c *********************
13544
13545 @node Project Extension
13546 @section Project Extension
13547
13548 @noindent
13549 During development of a large system, it is sometimes necessary to use
13550 modified versions of some of the source files, without changing the original
13551 sources. This can be achieved through the @emph{project extension} facility.
13552
13553 @smallexample @c projectfile
13554    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13555 @end smallexample
13556
13557 @noindent
13558 A project extension declaration introduces an extending project
13559 (the @emph{child}) and a project being extended (the @emph{parent}).
13560
13561 By default, a child project inherits all the sources of its parent.
13562 However, inherited sources can be overridden: a unit in a parent is hidden
13563 by a unit of the same name in the child.
13564
13565 Inherited sources are considered to be sources (but not immediate sources)
13566 of the child project; see @ref{Project File Syntax}.
13567
13568 An inherited source file retains any switches specified in the parent project.
13569
13570 For example if the project @code{Utilities} contains the spec and the
13571 body of an Ada package @code{Util_IO}, then the project
13572 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13573 The original body of @code{Util_IO} will not be considered in program builds.
13574 However, the package spec will still be found in the project
13575 @code{Utilities}.
13576
13577 A child project can have only one parent, except when it is qualified as
13578 abstract. But it may import any number of other projects.
13579
13580 A project is not allowed to import directly or indirectly at the same time a
13581 child project and any of its ancestors.
13582
13583 @c *******************************
13584 @c * Project Hierarchy Extension *
13585 @c *******************************
13586
13587 @node Project Hierarchy Extension
13588 @section Project Hierarchy Extension
13589
13590 @noindent
13591 When extending a large system spanning multiple projects, it is often
13592 inconvenient to extend every project in the hierarchy that is impacted by a
13593 small change introduced. In such cases, it is possible to create a virtual
13594 extension of entire hierarchy using @code{extends all} relationship.
13595
13596 When the project is extended using @code{extends all} inheritance, all projects
13597 that are imported by it, both directly and indirectly, are considered virtually
13598 extended. That is, the Project Manager creates "virtual projects"
13599 that extend every project in the hierarchy; all these virtual projects have
13600 no sources of their own and have as object directory the object directory of
13601 the root of "extending all" project.
13602
13603 It is possible to explicitly extend one or more projects in the hierarchy
13604 in order to modify the sources. These extending projects must be imported by
13605 the "extending all" project, which will replace the corresponding virtual
13606 projects with the explicit ones.
13607
13608 When building such a project hierarchy extension, the Project Manager will
13609 ensure that both modified sources and sources in virtual extending projects
13610 that depend on them, are recompiled.
13611
13612 By means of example, consider the following hierarchy of projects.
13613
13614 @enumerate
13615 @item
13616 project A, containing package P1
13617 @item
13618 project B importing A and containing package P2 which depends on P1
13619 @item
13620 project C importing B and containing package P3 which depends on P2
13621 @end enumerate
13622
13623 @noindent
13624 We want to modify packages P1 and P3.
13625
13626 This project hierarchy will need to be extended as follows:
13627
13628 @enumerate
13629 @item
13630 Create project A1 that extends A, placing modified P1 there:
13631
13632 @smallexample @c 0projectfile
13633 project A1 extends "(@dots{})/A" is
13634 end A1;
13635 @end smallexample
13636
13637 @item
13638 Create project C1 that "extends all" C and imports A1, placing modified
13639 P3 there:
13640
13641 @smallexample @c 0projectfile
13642 with "(@dots{})/A1";
13643 project C1 extends all "(@dots{})/C" is
13644 end C1;
13645 @end smallexample
13646 @end enumerate
13647
13648 When you build project C1, your entire modified project space will be
13649 recompiled, including the virtual project B1 that has been impacted by the
13650 "extending all" inheritance of project C.
13651
13652 Note that if a Library Project in the hierarchy is virtually extended,
13653 the virtual project that extends the Library Project is not a Library Project.
13654
13655 @c ****************************************
13656 @c * External References in Project Files *
13657 @c ****************************************
13658
13659 @node  External References in Project Files
13660 @section External References in Project Files
13661
13662 @noindent
13663 A project file may contain references to external variables; such references
13664 are called @emph{external references}.
13665
13666 An external variable is either defined as part of the environment (an
13667 environment variable in Unix, for example) or else specified on the command
13668 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13669 If both, then the command line value is used.
13670
13671 The value of an external reference is obtained by means of the built-in
13672 function @code{external}, which returns a string value.
13673 This function has two forms:
13674 @itemize @bullet
13675 @item @code{external (external_variable_name)}
13676 @item @code{external (external_variable_name, default_value)}
13677 @end itemize
13678
13679 @noindent
13680 Each parameter must be a string literal.  For example:
13681
13682 @smallexample @c projectfile
13683    external ("USER")
13684    external ("OS", "GNU/Linux")
13685 @end smallexample
13686
13687 @noindent
13688 In the form with one parameter, the function returns the value of
13689 the external variable given as parameter. If this name is not present in the
13690 environment, the function returns an empty string.
13691
13692 In the form with two string parameters, the second argument is
13693 the value returned when the variable given as the first argument is not
13694 present in the environment. In the example above, if @code{"OS"} is not
13695 the name of ^an environment variable^a logical name^ and is not passed on
13696 the command line, then the returned value is @code{"GNU/Linux"}.
13697
13698 An external reference may be part of a string expression or of a string
13699 list expression, and can therefore appear in a variable declaration or
13700 an attribute declaration.
13701
13702 @smallexample @c projectfile
13703 @group
13704    type Mode_Type is ("Debug", "Release");
13705    Mode : Mode_Type := external ("MODE");
13706    case Mode is
13707      when "Debug" =>
13708         @dots{}
13709 @end group
13710 @end smallexample
13711
13712 @c *****************************
13713 @c * Packages in Project Files *
13714 @c *****************************
13715
13716 @node  Packages in Project Files
13717 @section Packages in Project Files
13718
13719 @noindent
13720 A @emph{package} defines the settings for project-aware tools within a
13721 project.
13722 For each such tool one can declare a package; the names for these
13723 packages are preset (@pxref{Packages}).
13724 A package may contain variable declarations, attribute declarations, and case
13725 constructions.
13726
13727 @smallexample @c projectfile
13728 @group
13729    project Proj is
13730       package Builder is  -- used by gnatmake
13731          for ^Default_Switches^Default_Switches^ ("Ada")
13732              use ("^-v^-v^",
13733                   "^-g^-g^");
13734       end Builder;
13735    end Proj;
13736 @end group
13737 @end smallexample
13738
13739 @noindent
13740 The syntax of package declarations mimics that of package in Ada.
13741
13742 Most of the packages have an attribute
13743 @code{^Default_Switches^Default_Switches^}.
13744 This attribute is an associative array, and its value is a string list.
13745 The index of the associative array is the name of a programming language (case
13746 insensitive). This attribute indicates the ^switch^switch^
13747 or ^switches^switches^ to be used
13748 with the corresponding tool.
13749
13750 Some packages also have another attribute, @code{^Switches^Switches^},
13751 an associative array whose value is a string list.
13752 The index is the name of a source file.
13753 This attribute indicates the ^switch^switch^
13754 or ^switches^switches^ to be used by the corresponding
13755 tool when dealing with this specific file.
13756
13757 Further information on these ^switch^switch^-related attributes is found in
13758 @ref{^Switches^Switches^ and Project Files}.
13759
13760 A package may be declared as a @emph{renaming} of another package; e.g., from
13761 the project file for an imported project.
13762
13763 @smallexample @c projectfile
13764 @group
13765   with "/global/apex.gpr";
13766   project Example is
13767     package Naming renames Apex.Naming;
13768     @dots{}
13769   end Example;
13770 @end group
13771 @end smallexample
13772
13773 @noindent
13774 Packages that are renamed in other project files often come from project files
13775 that have no sources: they are just used as templates. Any modification in the
13776 template will be reflected automatically in all the project files that rename
13777 a package from the template.
13778
13779 In addition to the tool-oriented packages, you can also declare a package
13780 named @code{Naming} to establish specialized source file naming conventions
13781 (@pxref{Naming Schemes}).
13782
13783 @c ************************************
13784 @c * Variables from Imported Projects *
13785 @c ************************************
13786
13787 @node Variables from Imported Projects
13788 @section Variables from Imported Projects
13789
13790 @noindent
13791 An attribute or variable defined in an imported or parent project can
13792 be used in expressions in the importing / extending project.
13793 Such an attribute or variable is denoted by an expanded name whose prefix
13794 is either the name of the project or the expanded name of a package within
13795 a project.
13796
13797 @smallexample @c projectfile
13798 @group
13799   with "imported";
13800   project Main extends "base" is
13801      Var1 := Imported.Var;
13802      Var2 := Base.Var & ".new";
13803 @end group
13804
13805 @group
13806      package Builder is
13807         for ^Default_Switches^Default_Switches^ ("Ada")
13808             use Imported.Builder'Ada_^Switches^Switches^ &
13809                 "^-gnatg^-gnatg^" &
13810                 "^-v^-v^";
13811      end Builder;
13812 @end group
13813
13814 @group
13815      package Compiler is
13816         for ^Default_Switches^Default_Switches^ ("Ada")
13817             use Base.Compiler'Ada_^Switches^Switches^;
13818      end Compiler;
13819   end Main;
13820 @end group
13821 @end smallexample
13822
13823 @noindent
13824 In this example:
13825
13826 @itemize @bullet
13827 @item
13828 The value of @code{Var1} is a copy of the variable @code{Var} defined
13829 in the project file @file{"imported.gpr"}
13830 @item
13831 the value of @code{Var2} is a copy of the value of variable @code{Var}
13832 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13833 @item
13834 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13835 @code{Builder} is a string list that includes in its value a copy of the value
13836 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13837 in project file @file{imported.gpr} plus two new elements:
13838 @option{"^-gnatg^-gnatg^"}
13839 and @option{"^-v^-v^"};
13840 @item
13841 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13842 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13843 defined in the @code{Compiler} package in project file @file{base.gpr},
13844 the project being extended.
13845 @end itemize
13846
13847 @c ******************
13848 @c * Naming Schemes *
13849 @c ******************
13850
13851 @node  Naming Schemes
13852 @section Naming Schemes
13853
13854 @noindent
13855 Sometimes an Ada software system is ported from a foreign compilation
13856 environment to GNAT, and the file names do not use the default GNAT
13857 conventions. Instead of changing all the file names (which for a variety
13858 of reasons might not be possible), you can define the relevant file
13859 naming scheme in the @code{Naming} package in your project file.
13860
13861 @noindent
13862 Note that the use of pragmas described in
13863 @ref{Alternative File Naming Schemes} by mean of a configuration
13864 pragmas file is not supported when using project files. You must use
13865 the features described in this paragraph. You can however use specify
13866 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13867
13868 @ifclear vms
13869 For example, the following
13870 package models the Apex file naming rules:
13871
13872 @smallexample @c projectfile
13873 @group
13874   package Naming is
13875     for Casing               use "lowercase";
13876     for Dot_Replacement      use ".";
13877     for Spec_Suffix ("Ada")  use ".1.ada";
13878     for Body_Suffix ("Ada")  use ".2.ada";
13879   end Naming;
13880 @end group
13881 @end smallexample
13882 @end ifclear
13883
13884 @ifset vms
13885 For example, the following package models the HP Ada file naming rules:
13886
13887 @smallexample @c projectfile
13888 @group
13889   package Naming is
13890     for Casing               use "lowercase";
13891     for Dot_Replacement      use "__";
13892     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13893     for Body_Suffix ("Ada")  use ".^ada^ada^";
13894   end Naming;
13895 @end group
13896 @end smallexample
13897
13898 @noindent
13899 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13900 names in lower case)
13901 @end ifset
13902
13903 @noindent
13904 You can define the following attributes in package @code{Naming}:
13905
13906 @table @code
13907
13908 @item @code{Casing}
13909 This must be a string with one of the three values @code{"lowercase"},
13910 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13911
13912 @noindent
13913 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13914
13915 @item @code{Dot_Replacement}
13916 This must be a string whose value satisfies the following conditions:
13917
13918 @itemize @bullet
13919 @item It must not be empty
13920 @item It cannot start or end with an alphanumeric character
13921 @item It cannot be a single underscore
13922 @item It cannot start with an underscore followed by an alphanumeric
13923 @item It cannot contain a dot @code{'.'} except if the entire string
13924 is @code{"."}
13925 @end itemize
13926
13927 @noindent
13928 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13929
13930 @item @code{Spec_Suffix}
13931 This is an associative array (indexed by the programming language name, case
13932 insensitive) whose value is a string that must satisfy the following
13933 conditions:
13934
13935 @itemize @bullet
13936 @item It must not be empty
13937 @item It must include at least one dot
13938 @end itemize
13939 @noindent
13940 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13941 @code{"^.ads^.ADS^"}.
13942
13943 @item @code{Body_Suffix}
13944 This is an associative array (indexed by the programming language name, case
13945 insensitive) whose value is a string that must satisfy the following
13946 conditions:
13947
13948 @itemize @bullet
13949 @item It must not be empty
13950 @item It must include at least one dot
13951 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13952 @end itemize
13953 @noindent
13954 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13955 same string, then a file name that ends with the longest of these two suffixes
13956 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13957 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13958
13959 If the suffix does not start with a '.', a file with a name exactly equal
13960 to the suffix will also be part of the project (for instance if you define
13961 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13962 of the project. This is not interesting in general when using projects to
13963 compile. However, it might become useful when a project is also used to
13964 find the list of source files in an editor, like the GNAT Programming System
13965 (GPS).
13966
13967 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13968 @code{"^.adb^.ADB^"}.
13969
13970 @item @code{Separate_Suffix}
13971 This must be a string whose value satisfies the same conditions as
13972 @code{Body_Suffix}. The same "longest suffix" rules apply.
13973
13974 @noindent
13975 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13976 value as @code{Body_Suffix ("Ada")}.
13977
13978 @item @code{Spec}
13979 @noindent
13980 You can use the associative array attribute @code{Spec}  to define
13981 the source file name for an individual Ada compilation unit's spec. The array
13982 index must be a string literal that identifies the Ada unit (case insensitive).
13983 The value of this attribute must be a string that identifies the file that
13984 contains this unit's spec (case sensitive or insensitive depending on the
13985 operating system).
13986
13987 @smallexample @c projectfile
13988    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13989 @end smallexample
13990
13991 When the source file contains several units, you can indicate at what
13992 position the unit occurs in the file, with the following. The first unit
13993 in the file has index 1
13994
13995 @smallexample @c projectfile
13996   for Body ("top") use "foo.a" at 1;
13997   for Body ("foo") use "foo.a" at 2;
13998 @end smallexample
13999
14000 @item @code{Body}
14001
14002 You can use the associative array attribute @code{Body} to
14003 define the source file name for an individual Ada compilation unit's body
14004 (possibly a subunit).  The array index must be a string literal that identifies
14005 the Ada unit (case insensitive).  The value of this attribute must be a string
14006 that identifies the file that contains this unit's body or subunit (case
14007 sensitive or insensitive depending on the operating system).
14008
14009 @smallexample @c projectfile
14010    for Body ("MyPack.MyChild") use "mypack.mychild.body";
14011 @end smallexample
14012 @end table
14013
14014 @c ********************
14015 @c * Library Projects *
14016 @c ********************
14017
14018 @node Library Projects
14019 @section Library Projects
14020
14021 @noindent
14022 @emph{Library projects} are projects whose object code is placed in a library.
14023 (Note that this facility is not yet supported on all platforms).
14024
14025 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14026 single archive, which might either be a shared or a static library. This
14027 library can later on be linked with multiple executables, potentially
14028 reducing their sizes.
14029
14030 If your project file specifies languages other than Ada, but you are still
14031 using @code{gnatmake} to compile and link, the latter will not try to
14032 compile your sources other than Ada (you should use @code{gprbuild} if that
14033 is your intent). However, @code{gnatmake} will automatically link all object
14034 files found in the object directory, whether or not they were compiled from
14035 an Ada source file. This specific behavior only applies when multiple
14036 languages are specified.
14037
14038 To create a library project, you need to define in its project file
14039 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14040 Additionally, you may define other library-related attributes such as
14041 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14042 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14043
14044 The @code{Library_Name} attribute has a string value. There is no restriction
14045 on the name of a library. It is the responsibility of the developer to
14046 choose a name that will be accepted by the platform. It is recommended to
14047 choose names that could be Ada identifiers; such names are almost guaranteed
14048 to be acceptable on all platforms.
14049
14050 The @code{Library_Dir} attribute has a string value that designates the path
14051 (absolute or relative) of the directory where the library will reside.
14052 It must designate an existing directory. When the project is not externally
14053 built, this directory must be writable, different from the project's object
14054 directory and from any source directory in the project tree.
14055
14056 If both @code{Library_Name} and @code{Library_Dir} are specified and
14057 are legal, then the project file defines a library project.  The optional
14058 library-related attributes are checked only for such project files.
14059
14060 The @code{Library_Kind} attribute has a string value that must be one of the
14061 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14062 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14063 attribute is not specified, the library is a static library, that is
14064 an archive of object files that can be potentially linked into a
14065 static executable. Otherwise, the library may be dynamic or
14066 relocatable, that is a library that is loaded only at the start of execution.
14067
14068 If you need to build both a static and a dynamic library, you should use two
14069 different object directories, since in some cases some extra code needs to
14070 be generated for the latter. For such cases, it is recommended to either use
14071 two different project files, or a single one which uses external variables
14072 to indicate what kind of library should be build.
14073
14074 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14075 directory where the ALI files of the library will be copied. When it is
14076 not specified, the ALI files are copied to the directory specified in
14077 attribute @code{Library_Dir}. Except when the project is externally built, the
14078 directory specified by @code{Library_ALI_Dir} must be writable and different
14079 from the project's object directory and from any source directory in the
14080 project tree.
14081
14082 The @code{Library_Version} attribute has a string value whose interpretation
14083 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14084 used only for dynamic/relocatable libraries as the internal name of the
14085 library (the @code{"soname"}). If the library file name (built from the
14086 @code{Library_Name}) is different from the @code{Library_Version}, then the
14087 library file will be a symbolic link to the actual file whose name will be
14088 @code{Library_Version}.
14089
14090 Example (on Unix):
14091
14092 @smallexample @c projectfile
14093 @group
14094 project Plib is
14095
14096    Version := "1";
14097
14098    for Library_Dir use "lib_dir";
14099    for Library_Name use "dummy";
14100    for Library_Kind use "relocatable";
14101    for Library_Version use "libdummy.so." & Version;
14102
14103 end Plib;
14104 @end group
14105 @end smallexample
14106
14107 @noindent
14108 Directory @file{lib_dir} will contain the internal library file whose name
14109 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14110 @file{libdummy.so.1}.
14111
14112 When @command{gnatmake} detects that a project file
14113 is a library project file, it will check all immediate sources of the project
14114 and rebuild the library if any of the sources have been recompiled.
14115
14116 Standard project files can import library project files. In such cases,
14117 the libraries will only be rebuilt if some of its sources are recompiled
14118 because they are in the closure of some other source in an importing project.
14119 Sources of the library project files that are not in such a closure will
14120 not be checked, unless the full library is checked, because one of its sources
14121 needs to be recompiled.
14122
14123 For instance, assume the project file @code{A} imports the library project file
14124 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14125 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14126 @file{l2.ads}, @file{l2.adb}.
14127
14128 If @file{l1.adb} has been modified, then the library associated with @code{L}
14129 will be rebuilt when compiling all the immediate sources of @code{A} only
14130 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14131 @code{"with L1;"}.
14132
14133 To be sure that all the sources in the library associated with @code{L} are
14134 up to date, and that all the sources of project @code{A} are also up to date,
14135 the following two commands needs to be used:
14136
14137 @smallexample
14138 gnatmake -Pl.gpr
14139 gnatmake -Pa.gpr
14140 @end smallexample
14141
14142 When a library is built or rebuilt, an attempt is made first to delete all
14143 files in the library directory.
14144 All @file{ALI} files will also be copied from the object directory to the
14145 library directory. To build executables, @command{gnatmake} will use the
14146 library rather than the individual object files.
14147
14148 @ifclear vms
14149 It is also possible to create library project files for third-party libraries
14150 that are precompiled and cannot be compiled locally thanks to the
14151 @code{externally_built} attribute. (See @ref{Installing a library}).
14152 @end ifclear
14153
14154 @c *******************************
14155 @c * Stand-alone Library Projects *
14156 @c *******************************
14157
14158 @node Stand-alone Library Projects
14159 @section Stand-alone Library Projects
14160
14161 @noindent
14162 A Stand-alone Library is a library that contains the necessary code to
14163 elaborate the Ada units that are included in the library. A Stand-alone
14164 Library is suitable to be used in an executable when the main is not
14165 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14166 subprogram.
14167
14168 A Stand-alone Library Project is a Library Project where the library is
14169 a Stand-alone Library.
14170
14171 To be a Stand-alone Library Project, in addition to the two attributes
14172 that make a project a Library Project (@code{Library_Name} and
14173 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14174 @code{Library_Interface} must be defined.
14175
14176 @smallexample @c projectfile
14177 @group
14178    for Library_Dir use "lib_dir";
14179    for Library_Name use "dummy";
14180    for Library_Interface use ("int1", "int1.child");
14181 @end group
14182 @end smallexample
14183
14184 Attribute @code{Library_Interface} has a nonempty string list value,
14185 each string in the list designating a unit contained in an immediate source
14186 of the project file.
14187
14188 When a Stand-alone Library is built, first the binder is invoked to build
14189 a package whose name depends on the library name
14190 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14191 This binder-generated package includes initialization and
14192 finalization procedures whose
14193 names depend on the library name (dummyinit and dummyfinal in the example
14194 above). The object corresponding to this package is included in the library.
14195
14196 A dynamic or relocatable Stand-alone Library is automatically initialized
14197 if automatic initialization of Stand-alone Libraries is supported on the
14198 platform and if attribute @code{Library_Auto_Init} is not specified or
14199 is specified with the value "true". A static Stand-alone Library is never
14200 automatically initialized.
14201
14202 Single string attribute @code{Library_Auto_Init} may be specified with only
14203 two possible values: "false" or "true" (case-insensitive). Specifying
14204 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14205 initialization of dynamic or relocatable libraries.
14206
14207 When a non-automatically initialized Stand-alone Library is used
14208 in an executable, its initialization procedure must be called before
14209 any service of the library is used.
14210 When the main subprogram is in Ada, it may mean that the initialization
14211 procedure has to be called during elaboration of another package.
14212
14213 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14214 (those that are listed in attribute @code{Library_Interface}) are copied to
14215 the Library Directory. As a consequence, only the Interface Units may be
14216 imported from Ada units outside of the library. If other units are imported,
14217 the binding phase will fail.
14218
14219 When a Stand-Alone Library is bound, the switches that are specified in
14220 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14221 used in the call to @command{gnatbind}.
14222
14223 The string list attribute @code{Library_Options} may be used to specified
14224 additional switches to the call to @command{gcc} to link the library.
14225
14226 The attribute @code{Library_Src_Dir}, may be specified for a
14227 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14228 single string value. Its value must be the path (absolute or relative to the
14229 project directory) of an existing directory. This directory cannot be the
14230 object directory or one of the source directories, but it can be the same as
14231 the library directory. The sources of the Interface
14232 Units of the library, necessary to an Ada client of the library, will be
14233 copied to the designated directory, called Interface Copy directory.
14234 These sources includes the specs of the Interface Units, but they may also
14235 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14236 are used, or when there is a generic units in the spec. Before the sources
14237 are copied to the Interface Copy directory, an attempt is made to delete all
14238 files in the Interface Copy directory.
14239
14240 @c *************************************
14241 @c * Switches Related to Project Files *
14242 @c *************************************
14243 @node Switches Related to Project Files
14244 @section Switches Related to Project Files
14245
14246 @noindent
14247 The following switches are used by GNAT tools that support project files:
14248
14249 @table @option
14250
14251 @item ^-P^/PROJECT_FILE=^@var{project}
14252 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14253 Indicates the name of a project file. This project file will be parsed with
14254 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14255 if any, and using the external references indicated
14256 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14257 @ifclear vms
14258 There may zero, one or more spaces between @option{-P} and @var{project}.
14259 @end ifclear
14260
14261 @noindent
14262 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14263
14264 @noindent
14265 Since the Project Manager parses the project file only after all the switches
14266 on the command line are checked, the order of the switches
14267 @option{^-P^/PROJECT_FILE^},
14268 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14269 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14270
14271 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14272 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14273 Indicates that external variable @var{name} has the value @var{value}.
14274 The Project Manager will use this value for occurrences of
14275 @code{external(name)} when parsing the project file.
14276
14277 @ifclear vms
14278 @noindent
14279 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14280 put between quotes.
14281 @smallexample
14282   -XOS=NT
14283   -X"user=John Doe"
14284 @end smallexample
14285 @end ifclear
14286
14287 @noindent
14288 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14289 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14290 @var{name}, only the last one is used.
14291
14292 @noindent
14293 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14294 takes precedence over the value of the same name in the environment.
14295
14296 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14297 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14298 Indicates the verbosity of the parsing of GNAT project files.
14299
14300 @ifclear vms
14301 @option{-vP0} means Default;
14302 @option{-vP1} means Medium;
14303 @option{-vP2} means High.
14304 @end ifclear
14305
14306 @ifset vms
14307 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14308 HIGH.
14309 @end ifset
14310
14311 @noindent
14312 The default is ^Default^DEFAULT^: no output for syntactically correct
14313 project files.
14314 @noindent
14315 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14316 only the last one is used.
14317
14318 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14319 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14320 Add directory <dir> at the beginning of the project search path, in order,
14321 after the current working directory.
14322
14323 @ifclear vms
14324 @item -eL
14325 @cindex @option{-eL} (any project-aware tool)
14326 Follow all symbolic links when processing project files.
14327 @end ifclear
14328
14329 @item ^--subdirs^/SUBDIRS^=<subdir>
14330 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14331 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14332 directories (except the source directories) are the subdirectories <subdir>
14333 of the directories specified in the project files. This applies in particular
14334 to object directories, library directories and exec directories. If the
14335 subdirectories do not exist, they are created automatically.
14336
14337 @end table
14338
14339 @c **********************************
14340 @c * Tools Supporting Project Files *
14341 @c **********************************
14342
14343 @node  Tools Supporting Project Files
14344 @section Tools Supporting Project Files
14345
14346 @menu
14347 * gnatmake and Project Files::
14348 * The GNAT Driver and Project Files::
14349 @end menu
14350
14351 @node gnatmake and Project Files
14352 @subsection gnatmake and Project Files
14353
14354 @noindent
14355 This section covers several topics related to @command{gnatmake} and
14356 project files: defining ^switches^switches^ for @command{gnatmake}
14357 and for the tools that it invokes; specifying configuration pragmas;
14358 the use of the @code{Main} attribute; building and rebuilding library project
14359 files.
14360
14361 @menu
14362 * ^Switches^Switches^ and Project Files::
14363 * Specifying Configuration Pragmas::
14364 * Project Files and Main Subprograms::
14365 * Library Project Files::
14366 @end menu
14367
14368 @node ^Switches^Switches^ and Project Files
14369 @subsubsection ^Switches^Switches^ and Project Files
14370
14371 @ifset vms
14372 It is not currently possible to specify VMS style qualifiers in the project
14373 files; only Unix style ^switches^switches^ may be specified.
14374 @end ifset
14375
14376 @noindent
14377 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14378 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14379 attribute, a @code{^Switches^Switches^} attribute, or both;
14380 as their names imply, these ^switch^switch^-related
14381 attributes affect the ^switches^switches^ that are used for each of these GNAT
14382 components when
14383 @command{gnatmake} is invoked.  As will be explained below, these
14384 component-specific ^switches^switches^ precede
14385 the ^switches^switches^ provided on the @command{gnatmake} command line.
14386
14387 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14388 array indexed by language name (case insensitive) whose value is a string list.
14389 For example:
14390
14391 @smallexample @c projectfile
14392 @group
14393 package Compiler is
14394   for ^Default_Switches^Default_Switches^ ("Ada")
14395       use ("^-gnaty^-gnaty^",
14396            "^-v^-v^");
14397 end Compiler;
14398 @end group
14399 @end smallexample
14400
14401 @noindent
14402 The @code{^Switches^Switches^} attribute is also an associative array,
14403 indexed by a file name (which may or may not be case sensitive, depending
14404 on the operating system) whose value is a string list.  For example:
14405
14406 @smallexample @c projectfile
14407 @group
14408 package Builder is
14409    for ^Switches^Switches^ ("main1.adb")
14410        use ("^-O2^-O2^");
14411    for ^Switches^Switches^ ("main2.adb")
14412        use ("^-g^-g^");
14413 end Builder;
14414 @end group
14415 @end smallexample
14416
14417 @noindent
14418 For the @code{Builder} package, the file names must designate source files
14419 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14420 file names must designate @file{ALI} or source files for main subprograms.
14421 In each case just the file name without an explicit extension is acceptable.
14422
14423 For each tool used in a program build (@command{gnatmake}, the compiler, the
14424 binder, and the linker), the corresponding package @dfn{contributes} a set of
14425 ^switches^switches^ for each file on which the tool is invoked, based on the
14426 ^switch^switch^-related attributes defined in the package.
14427 In particular, the ^switches^switches^
14428 that each of these packages contributes for a given file @var{f} comprise:
14429
14430 @itemize @bullet
14431 @item
14432 the value of attribute @code{^Switches^Switches^ (@var{f})},
14433 if it is specified in the package for the given file,
14434 @item
14435 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14436 if it is specified in the package.
14437 @end itemize
14438
14439 @noindent
14440 If neither of these attributes is defined in the package, then the package does
14441 not contribute any ^switches^switches^ for the given file.
14442
14443 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14444 two sets, in the following order: those contributed for the file
14445 by the @code{Builder} package;
14446 and the switches passed on the command line.
14447
14448 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14449 the ^switches^switches^ passed to the tool comprise three sets,
14450 in the following order:
14451
14452 @enumerate
14453 @item
14454 the applicable ^switches^switches^ contributed for the file
14455 by the @code{Builder} package in the project file supplied on the command line;
14456
14457 @item
14458 those contributed for the file by the package (in the relevant project file --
14459 see below) corresponding to the tool; and
14460
14461 @item
14462 the applicable switches passed on the command line.
14463 @end enumerate
14464
14465 @noindent
14466 The term @emph{applicable ^switches^switches^} reflects the fact that
14467 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14468 tools, depending on the individual ^switch^switch^.
14469
14470 @command{gnatmake} may invoke the compiler on source files from different
14471 projects. The Project Manager will use the appropriate project file to
14472 determine the @code{Compiler} package for each source file being compiled.
14473 Likewise for the @code{Binder} and @code{Linker} packages.
14474
14475 As an example, consider the following package in a project file:
14476
14477 @smallexample @c projectfile
14478 @group
14479 project Proj1 is
14480    package Compiler is
14481       for ^Default_Switches^Default_Switches^ ("Ada")
14482           use ("^-g^-g^");
14483       for ^Switches^Switches^ ("a.adb")
14484           use ("^-O1^-O1^");
14485       for ^Switches^Switches^ ("b.adb")
14486           use ("^-O2^-O2^",
14487                "^-gnaty^-gnaty^");
14488    end Compiler;
14489 end Proj1;
14490 @end group
14491 @end smallexample
14492
14493 @noindent
14494 If @command{gnatmake} is invoked with this project file, and it needs to
14495 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14496 @file{a.adb} will be compiled with the ^switch^switch^
14497 @option{^-O1^-O1^},
14498 @file{b.adb} with ^switches^switches^
14499 @option{^-O2^-O2^}
14500 and @option{^-gnaty^-gnaty^},
14501 and @file{c.adb} with @option{^-g^-g^}.
14502
14503 The following example illustrates the ordering of the ^switches^switches^
14504 contributed by different packages:
14505
14506 @smallexample @c projectfile
14507 @group
14508 project Proj2 is
14509    package Builder is
14510       for ^Switches^Switches^ ("main.adb")
14511           use ("^-g^-g^",
14512                "^-O1^-)1^",
14513                "^-f^-f^");
14514    end Builder;
14515 @end group
14516
14517 @group
14518    package Compiler is
14519       for ^Switches^Switches^ ("main.adb")
14520           use ("^-O2^-O2^");
14521    end Compiler;
14522 end Proj2;
14523 @end group
14524 @end smallexample
14525
14526 @noindent
14527 If you issue the command:
14528
14529 @smallexample
14530     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14531 @end smallexample
14532
14533 @noindent
14534 then the compiler will be invoked on @file{main.adb} with the following
14535 sequence of ^switches^switches^
14536
14537 @smallexample
14538    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14539 @end smallexample
14540
14541 with the last @option{^-O^-O^}
14542 ^switch^switch^ having precedence over the earlier ones;
14543 several other ^switches^switches^
14544 (such as @option{^-c^-c^}) are added implicitly.
14545
14546 The ^switches^switches^
14547 @option{^-g^-g^}
14548 and @option{^-O1^-O1^} are contributed by package
14549 @code{Builder},  @option{^-O2^-O2^} is contributed
14550 by the package @code{Compiler}
14551 and @option{^-O0^-O0^} comes from the command line.
14552
14553 The @option{^-g^-g^}
14554 ^switch^switch^ will also be passed in the invocation of
14555 @command{Gnatlink.}
14556
14557 A final example illustrates switch contributions from packages in different
14558 project files:
14559
14560 @smallexample @c projectfile
14561 @group
14562 project Proj3 is
14563    for Source_Files use ("pack.ads", "pack.adb");
14564    package Compiler is
14565       for ^Default_Switches^Default_Switches^ ("Ada")
14566           use ("^-gnata^-gnata^");
14567    end Compiler;
14568 end Proj3;
14569 @end group
14570
14571 @group
14572 with "Proj3";
14573 project Proj4 is
14574    for Source_Files use ("foo_main.adb", "bar_main.adb");
14575    package Builder is
14576       for ^Switches^Switches^ ("foo_main.adb")
14577           use ("^-s^-s^",
14578                "^-g^-g^");
14579    end Builder;
14580 end Proj4;
14581 @end group
14582
14583 @group
14584 -- Ada source file:
14585 with Pack;
14586 procedure Foo_Main is
14587    @dots{}
14588 end Foo_Main;
14589 @end group
14590 @end smallexample
14591
14592 If the command is
14593 @smallexample
14594 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14595 @end smallexample
14596
14597 @noindent
14598 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14599 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14600 @option{^-gnato^-gnato^} (passed on the command line).
14601 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14602 are @option{^-g^-g^} from @code{Proj4.Builder},
14603 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14604 and @option{^-gnato^-gnato^} from the command line.
14605
14606 @noindent
14607 When using @command{gnatmake} with project files, some ^switches^switches^ or
14608 arguments may be expressed as relative paths. As the working directory where
14609 compilation occurs may change, these relative paths are converted to absolute
14610 paths. For the ^switches^switches^ found in a project file, the relative paths
14611 are relative to the project file directory, for the switches on the command
14612 line, they are relative to the directory where @command{gnatmake} is invoked.
14613 The ^switches^switches^ for which this occurs are:
14614 ^-I^-I^,
14615 ^-A^-A^,
14616 ^-L^-L^,
14617 ^-aO^-aO^,
14618 ^-aL^-aL^,
14619 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14620 ^switch^switch^
14621 ^-o^-o^, object files specified in package @code{Linker} or after
14622 -largs on the command line). The exception to this rule is the ^switch^switch^
14623 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14624
14625 @node Specifying Configuration Pragmas
14626 @subsubsection Specifying Configuration Pragmas
14627
14628 When using @command{gnatmake} with project files, if there exists a file
14629 @file{gnat.adc} that contains configuration pragmas, this file will be
14630 ignored.
14631
14632 Configuration pragmas can be defined by means of the following attributes in
14633 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14634 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14635
14636 Both these attributes are single string attributes. Their values is the path
14637 name of a file containing configuration pragmas. If a path name is relative,
14638 then it is relative to the project directory of the project file where the
14639 attribute is defined.
14640
14641 When compiling a source, the configuration pragmas used are, in order,
14642 those listed in the file designated by attribute
14643 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14644 project file, if it is specified, and those listed in the file designated by
14645 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14646 the project file of the source, if it exists.
14647
14648 @node Project Files and Main Subprograms
14649 @subsubsection Project Files and Main Subprograms
14650
14651 @noindent
14652 When using a project file, you can invoke @command{gnatmake}
14653 with one or several main subprograms, by specifying their source files on the
14654 command line.
14655
14656 @smallexample
14657     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14658 @end smallexample
14659
14660 @noindent
14661 Each of these needs to be a source file of the same project, except
14662 when the switch ^-u^/UNIQUE^ is used.
14663
14664 @noindent
14665 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14666 same project, one of the project in the tree rooted at the project specified
14667 on the command line. The package @code{Builder} of this common project, the
14668 "main project" is the one that is considered by @command{gnatmake}.
14669
14670 @noindent
14671 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14672 imported directly or indirectly by the project specified on the command line.
14673 Note that if such a source file is not part of the project specified on the
14674 command line, the ^switches^switches^ found in package @code{Builder} of the
14675 project specified on the command line, if any, that are transmitted
14676 to the compiler will still be used, not those found in the project file of
14677 the source file.
14678
14679 @noindent
14680 When using a project file, you can also invoke @command{gnatmake} without
14681 explicitly specifying any main, and the effect depends on whether you have
14682 defined the @code{Main} attribute.  This attribute has a string list value,
14683 where each element in the list is the name of a source file (the file
14684 extension is optional) that contains a unit that can be a main subprogram.
14685
14686 If the @code{Main} attribute is defined in a project file as a non-empty
14687 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14688 line, then invoking @command{gnatmake} with this project file but without any
14689 main on the command line is equivalent to invoking @command{gnatmake} with all
14690 the file names in the @code{Main} attribute on the command line.
14691
14692 Example:
14693 @smallexample @c projectfile
14694 @group
14695    project Prj is
14696       for Main use ("main1", "main2", "main3");
14697    end Prj;
14698 @end group
14699 @end smallexample
14700
14701 @noindent
14702 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14703 is equivalent to
14704 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14705
14706 When the project attribute @code{Main} is not specified, or is specified
14707 as an empty string list, or when the switch @option{-u} is used on the command
14708 line, then invoking @command{gnatmake} with no main on the command line will
14709 result in all immediate sources of the project file being checked, and
14710 potentially recompiled. Depending on the presence of the switch @option{-u},
14711 sources from other project files on which the immediate sources of the main
14712 project file depend are also checked and potentially recompiled. In other
14713 words, the @option{-u} switch is applied to all of the immediate sources of the
14714 main project file.
14715
14716 When no main is specified on the command line and attribute @code{Main} exists
14717 and includes several mains, or when several mains are specified on the
14718 command line, the default ^switches^switches^ in package @code{Builder} will
14719 be used for all mains, even if there are specific ^switches^switches^
14720 specified for one or several mains.
14721
14722 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14723 the specific ^switches^switches^ for each main, if they are specified.
14724
14725 @node Library Project Files
14726 @subsubsection Library Project Files
14727
14728 @noindent
14729 When @command{gnatmake} is invoked with a main project file that is a library
14730 project file, it is not allowed to specify one or more mains on the command
14731 line.
14732
14733 @noindent
14734 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14735 ^-l^/ACTION=LINK^ have special meanings.
14736
14737 @itemize @bullet
14738 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14739 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14740 library.
14741
14742 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14743 to @command{gnatmake} that the binder generated file should be compiled
14744 (in the case of a stand-alone library) and that the library should be built.
14745
14746 @end itemize
14747
14748 @node The GNAT Driver and Project Files
14749 @subsection The GNAT Driver and Project Files
14750
14751 @noindent
14752 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14753 can benefit from project files:
14754 (@command{^gnatbind^gnatbind^},
14755 @command{^gnatcheck^gnatcheck^},
14756 @command{^gnatclean^gnatclean^},
14757 @command{^gnatelim^gnatelim^},
14758 @command{^gnatfind^gnatfind^},
14759 @command{^gnatlink^gnatlink^},
14760 @command{^gnatls^gnatls^},
14761 @command{^gnatmetric^gnatmetric^},
14762 @command{^gnatpp^gnatpp^},
14763 @command{^gnatstub^gnatstub^},
14764 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
14765 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14766 They must be invoked through the @command{gnat} driver.
14767
14768 The @command{gnat} driver is a wrapper that accepts a number of commands and
14769 calls the corresponding tool. It was designed initially for VMS platforms (to
14770 convert VMS qualifiers to Unix-style switches), but it is now available on all
14771 GNAT platforms.
14772
14773 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14774 (case insensitive):
14775
14776 @itemize @bullet
14777 @item
14778 BIND to invoke @command{^gnatbind^gnatbind^}
14779 @item
14780 CHOP to invoke @command{^gnatchop^gnatchop^}
14781 @item
14782 CLEAN to invoke @command{^gnatclean^gnatclean^}
14783 @item
14784 COMP or COMPILE to invoke the compiler
14785 @item
14786 ELIM to invoke @command{^gnatelim^gnatelim^}
14787 @item
14788 FIND to invoke @command{^gnatfind^gnatfind^}
14789 @item
14790 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14791 @item
14792 LINK to invoke @command{^gnatlink^gnatlink^}
14793 @item
14794 LS or LIST to invoke @command{^gnatls^gnatls^}
14795 @item
14796 MAKE to invoke @command{^gnatmake^gnatmake^}
14797 @item
14798 NAME to invoke @command{^gnatname^gnatname^}
14799 @item
14800 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14801 @item
14802 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14803 @item
14804 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14805 @item
14806 STUB to invoke @command{^gnatstub^gnatstub^}
14807 @item
14808 XREF to invoke @command{^gnatxref^gnatxref^}
14809 @end itemize
14810
14811 @noindent
14812 (note that the compiler is invoked using the command
14813 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14814
14815 @noindent
14816 On non-VMS platforms, between @command{gnat} and the command, two
14817 special switches may be used:
14818
14819 @itemize @bullet
14820 @item
14821 @command{-v} to display the invocation of the tool.
14822 @item
14823 @command{-dn} to prevent the @command{gnat} driver from removing
14824 the temporary files it has created. These temporary files are
14825 configuration files and temporary file list files.
14826 @end itemize
14827
14828 @noindent
14829 The command may be followed by switches and arguments for the invoked
14830 tool.
14831
14832 @smallexample
14833   gnat bind -C main.ali
14834   gnat ls -a main
14835   gnat chop foo.txt
14836 @end smallexample
14837
14838 @noindent
14839 Switches may also be put in text files, one switch per line, and the text
14840 files may be specified with their path name preceded by '@@'.
14841
14842 @smallexample
14843    gnat bind @@args.txt main.ali
14844 @end smallexample
14845
14846 @noindent
14847 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14848 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14849 (@option{^-P^/PROJECT_FILE^},
14850 @option{^-X^/EXTERNAL_REFERENCE^} and
14851 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14852 the switches of the invoking tool.
14853
14854 @noindent
14855 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14856 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14857 the immediate sources of the specified project file.
14858
14859 @noindent
14860 When GNAT METRIC is used with a project file, but with no source
14861 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14862 with all the immediate sources of the specified project file and with
14863 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14864 of the project.
14865
14866 @noindent
14867 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14868 a project file, no source is specified on the command line and
14869 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14870 the underlying tool (^gnatpp^gnatpp^ or
14871 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14872 not only for the immediate sources of the main project.
14873 @ifclear vms
14874 (-U stands for Universal or Union of the project files of the project tree)
14875 @end ifclear
14876
14877 @noindent
14878 For each of the following commands, there is optionally a corresponding
14879 package in the main project.
14880
14881 @itemize @bullet
14882 @item
14883 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14884
14885 @item
14886 package @code{Check} for command CHECK (invoking
14887 @code{^gnatcheck^gnatcheck^})
14888
14889 @item
14890 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14891
14892 @item
14893 package @code{Cross_Reference} for command XREF (invoking
14894 @code{^gnatxref^gnatxref^})
14895
14896 @item
14897 package @code{Eliminate} for command ELIM (invoking
14898 @code{^gnatelim^gnatelim^})
14899
14900 @item
14901 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14902
14903 @item
14904 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14905
14906 @item
14907 package @code{Gnatstub} for command STUB
14908 (invoking @code{^gnatstub^gnatstub^})
14909
14910 @item
14911 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14912
14913 @item
14914 package @code{Check} for command CHECK
14915 (invoking @code{^gnatcheck^gnatcheck^})
14916
14917 @item
14918 package @code{Metrics} for command METRIC
14919 (invoking @code{^gnatmetric^gnatmetric^})
14920
14921 @item
14922 package @code{Pretty_Printer} for command PP or PRETTY
14923 (invoking @code{^gnatpp^gnatpp^})
14924
14925 @end itemize
14926
14927 @noindent
14928 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14929 a simple variable with a string list value. It contains ^switches^switches^
14930 for the invocation of @code{^gnatls^gnatls^}.
14931
14932 @smallexample @c projectfile
14933 @group
14934 project Proj1 is
14935    package gnatls is
14936       for ^Switches^Switches^
14937           use ("^-a^-a^",
14938                "^-v^-v^");
14939    end gnatls;
14940 end Proj1;
14941 @end group
14942 @end smallexample
14943
14944 @noindent
14945 All other packages have two attribute @code{^Switches^Switches^} and
14946 @code{^Default_Switches^Default_Switches^}.
14947
14948 @noindent
14949 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14950 source file name, that has a string list value: the ^switches^switches^ to be
14951 used when the tool corresponding to the package is invoked for the specific
14952 source file.
14953
14954 @noindent
14955 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14956 indexed by  the programming language that has a string list value.
14957 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14958 ^switches^switches^ for the invocation of the tool corresponding
14959 to the package, except if a specific @code{^Switches^Switches^} attribute
14960 is specified for the source file.
14961
14962 @smallexample @c projectfile
14963 @group
14964 project Proj is
14965
14966    for Source_Dirs use ("./**");
14967
14968    package gnatls is
14969       for ^Switches^Switches^ use
14970           ("^-a^-a^",
14971            "^-v^-v^");
14972    end gnatls;
14973 @end group
14974 @group
14975
14976    package Compiler is
14977       for ^Default_Switches^Default_Switches^ ("Ada")
14978           use ("^-gnatv^-gnatv^",
14979                "^-gnatwa^-gnatwa^");
14980    end Binder;
14981 @end group
14982 @group
14983
14984    package Binder is
14985       for ^Default_Switches^Default_Switches^ ("Ada")
14986           use ("^-C^-C^",
14987                "^-e^-e^");
14988    end Binder;
14989 @end group
14990 @group
14991
14992    package Linker is
14993       for ^Default_Switches^Default_Switches^ ("Ada")
14994           use ("^-C^-C^");
14995       for ^Switches^Switches^ ("main.adb")
14996           use ("^-C^-C^",
14997                "^-v^-v^",
14998                "^-v^-v^");
14999    end Linker;
15000 @end group
15001 @group
15002
15003    package Finder is
15004       for ^Default_Switches^Default_Switches^ ("Ada")
15005            use ("^-a^-a^",
15006                 "^-f^-f^");
15007    end Finder;
15008 @end group
15009 @group
15010
15011    package Cross_Reference is
15012       for ^Default_Switches^Default_Switches^ ("Ada")
15013           use ("^-a^-a^",
15014                "^-f^-f^",
15015                "^-d^-d^",
15016                "^-u^-u^");
15017    end Cross_Reference;
15018 end Proj;
15019 @end group
15020 @end smallexample
15021
15022 @noindent
15023 With the above project file, commands such as
15024
15025 @smallexample
15026    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15027    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15028    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15029    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15030    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15031 @end smallexample
15032
15033 @noindent
15034 will set up the environment properly and invoke the tool with the switches
15035 found in the package corresponding to the tool:
15036 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15037 except @code{^Switches^Switches^ ("main.adb")}
15038 for @code{^gnatlink^gnatlink^}.
15039 It is also possible to invoke some of the tools,
15040 (@code{^gnatcheck^gnatcheck^},
15041 @code{^gnatmetric^gnatmetric^},
15042 and @code{^gnatpp^gnatpp^})
15043 on a set of project units thanks to the combination of the switches
15044 @option{-P}, @option{-U} and possibly the main unit when one is interested
15045 in its closure. For instance,
15046 @smallexample
15047 gnat metric -Pproj
15048 @end smallexample
15049 will compute the metrics for all the immediate units of project
15050 @code{proj}.
15051 @smallexample
15052 gnat metric -Pproj -U
15053 @end smallexample
15054 will compute the metrics for all the units of the closure of projects
15055 rooted at @code{proj}.
15056 @smallexample
15057 gnat metric -Pproj -U main_unit
15058 @end smallexample
15059 will compute the metrics for the closure of units rooted at
15060 @code{main_unit}. This last possibility relies implicitly
15061 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
15062 tool invoked by the the @command{gnat} driver are explicitly  specified
15063 either directly or through the tool @option{-files} option, then the tool
15064 is called only for these explicitly specified files.
15065
15066 @c **********************
15067 @node An Extended Example
15068 @section An Extended Example
15069
15070 @noindent
15071 Suppose that we have two programs, @var{prog1} and @var{prog2},
15072 whose sources are in corresponding directories. We would like
15073 to build them with a single @command{gnatmake} command, and we want to place
15074 their object files into @file{build} subdirectories of the source directories.
15075 Furthermore, we want to have to have two separate subdirectories
15076 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15077 the object files compiled with different set of compilation flags.
15078
15079 In other words, we have the following structure:
15080
15081 @smallexample
15082 @group
15083    main
15084      |- prog1
15085      |    |- build
15086      |         | debug
15087      |         | release
15088      |- prog2
15089           |- build
15090                | debug
15091                | release
15092 @end group
15093 @end smallexample
15094
15095 @noindent
15096 Here are the project files that we must place in a directory @file{main}
15097 to maintain this structure:
15098
15099 @enumerate
15100
15101 @item We create a @code{Common} project with a package @code{Compiler} that
15102 specifies the compilation ^switches^switches^:
15103
15104 @smallexample
15105 File "common.gpr":
15106 @group
15107 @b{project} Common @b{is}
15108
15109    @b{for} Source_Dirs @b{use} (); -- No source files
15110 @end group
15111
15112 @group
15113    @b{type} Build_Type @b{is} ("release", "debug");
15114    Build : Build_Type := External ("BUILD", "debug");
15115 @end group
15116 @group
15117    @b{package} Compiler @b{is}
15118       @b{case} Build @b{is}
15119          @b{when} "release" =>
15120            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15121                    @b{use} ("^-O2^-O2^");
15122          @b{when} "debug"   =>
15123            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15124                    @b{use} ("^-g^-g^");
15125       @b{end case};
15126    @b{end} Compiler;
15127
15128 @b{end} Common;
15129 @end group
15130 @end smallexample
15131
15132 @item We create separate projects for the two programs:
15133
15134 @smallexample
15135 @group
15136 File "prog1.gpr":
15137
15138 @b{with} "common";
15139 @b{project} Prog1 @b{is}
15140
15141     @b{for} Source_Dirs @b{use} ("prog1");
15142     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15143
15144     @b{package} Compiler @b{renames} Common.Compiler;
15145
15146 @b{end} Prog1;
15147 @end group
15148 @end smallexample
15149
15150 @smallexample
15151 @group
15152 File "prog2.gpr":
15153
15154 @b{with} "common";
15155 @b{project} Prog2 @b{is}
15156
15157     @b{for} Source_Dirs @b{use} ("prog2");
15158     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15159
15160     @b{package} Compiler @b{renames} Common.Compiler;
15161
15162 @end group
15163 @b{end} Prog2;
15164 @end smallexample
15165
15166 @item We create a wrapping project @code{Main}:
15167
15168 @smallexample
15169 @group
15170 File "main.gpr":
15171
15172 @b{with} "common";
15173 @b{with} "prog1";
15174 @b{with} "prog2";
15175 @b{project} Main @b{is}
15176
15177    @b{package} Compiler @b{renames} Common.Compiler;
15178
15179 @b{end} Main;
15180 @end group
15181 @end smallexample
15182
15183 @item Finally we need to create a dummy procedure that @code{with}s (either
15184 explicitly or implicitly) all the sources of our two programs.
15185
15186 @end enumerate
15187
15188 @noindent
15189 Now we can build the programs using the command
15190
15191 @smallexample
15192    gnatmake ^-P^/PROJECT_FILE=^main dummy
15193 @end smallexample
15194
15195 @noindent
15196 for the Debug mode, or
15197
15198 @ifclear vms
15199 @smallexample
15200    gnatmake -Pmain -XBUILD=release
15201 @end smallexample
15202 @end ifclear
15203
15204 @ifset vms
15205 @smallexample
15206    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15207 @end smallexample
15208 @end ifset
15209
15210 @noindent
15211 for the Release mode.
15212
15213 @c ********************************
15214 @c * Project File Complete Syntax *
15215 @c ********************************
15216
15217 @node Project File Complete Syntax
15218 @section Project File Complete Syntax
15219
15220 @smallexample
15221 project ::=
15222   context_clause project_declaration
15223
15224 context_clause ::=
15225   @{with_clause@}
15226
15227 with_clause ::=
15228   @b{with} path_name @{ , path_name @} ;
15229
15230 path_name ::=
15231    string_literal
15232
15233 project_declaration ::=
15234   simple_project_declaration | project_extension
15235
15236 simple_project_declaration ::=
15237   @b{project} <project_>simple_name @b{is}
15238     @{declarative_item@}
15239   @b{end} <project_>simple_name;
15240
15241 project_extension ::=
15242   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15243     @{declarative_item@}
15244   @b{end} <project_>simple_name;
15245
15246 declarative_item ::=
15247   package_declaration |
15248   typed_string_declaration |
15249   other_declarative_item
15250
15251 package_declaration ::=
15252   package_spec | package_renaming
15253
15254 package_spec ::=
15255   @b{package} package_identifier @b{is}
15256     @{simple_declarative_item@}
15257   @b{end} package_identifier ;
15258
15259 package_identifier ::=
15260   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15261   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15262   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15263
15264 package_renaming ::==
15265   @b{package} package_identifier @b{renames}
15266        <project_>simple_name.package_identifier ;
15267
15268 typed_string_declaration ::=
15269   @b{type} <typed_string_>_simple_name @b{is}
15270    ( string_literal @{, string_literal@} );
15271
15272 other_declarative_item ::=
15273   attribute_declaration |
15274   typed_variable_declaration |
15275   variable_declaration |
15276   case_construction
15277
15278 attribute_declaration ::=
15279   full_associative_array_declaration |
15280   @b{for} attribute_designator @b{use} expression ;
15281
15282 full_associative_array_declaration ::=
15283   @b{for} <associative_array_attribute_>simple_name @b{use}
15284   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15285
15286 attribute_designator ::=
15287   <simple_attribute_>simple_name |
15288   <associative_array_attribute_>simple_name ( string_literal )
15289
15290 typed_variable_declaration ::=
15291   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15292
15293 variable_declaration ::=
15294   <variable_>simple_name := expression;
15295
15296 expression ::=
15297   term @{& term@}
15298
15299 term ::=
15300   literal_string |
15301   string_list |
15302   <variable_>name |
15303   external_value |
15304   attribute_reference
15305
15306 string_literal ::=
15307   (same as Ada)
15308
15309 string_list ::=
15310   ( <string_>expression @{ , <string_>expression @} )
15311
15312 external_value ::=
15313   @b{external} ( string_literal [, string_literal] )
15314
15315 attribute_reference ::=
15316   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15317
15318 attribute_prefix ::=
15319   @b{project} |
15320   <project_>simple_name | package_identifier |
15321   <project_>simple_name . package_identifier
15322
15323 case_construction ::=
15324   @b{case} <typed_variable_>name @b{is}
15325     @{case_item@}
15326   @b{end case} ;
15327
15328 case_item ::=
15329   @b{when} discrete_choice_list =>
15330       @{case_construction | attribute_declaration@}
15331
15332 discrete_choice_list ::=
15333   string_literal @{| string_literal@} |
15334   @b{others}
15335
15336 name ::=
15337   simple_name @{. simple_name@}
15338
15339 simple_name ::=
15340   identifier (same as Ada)
15341
15342 @end smallexample
15343
15344 @node The Cross-Referencing Tools gnatxref and gnatfind
15345 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15346 @findex gnatxref
15347 @findex gnatfind
15348
15349 @noindent
15350 The compiler generates cross-referencing information (unless
15351 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15352 This information indicates where in the source each entity is declared and
15353 referenced. Note that entities in package Standard are not included, but
15354 entities in all other predefined units are included in the output.
15355
15356 Before using any of these two tools, you need to compile successfully your
15357 application, so that GNAT gets a chance to generate the cross-referencing
15358 information.
15359
15360 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15361 information to provide the user with the capability to easily locate the
15362 declaration and references to an entity. These tools are quite similar,
15363 the difference being that @code{gnatfind} is intended for locating
15364 definitions and/or references to a specified entity or entities, whereas
15365 @code{gnatxref} is oriented to generating a full report of all
15366 cross-references.
15367
15368 To use these tools, you must not compile your application using the
15369 @option{-gnatx} switch on the @command{gnatmake} command line
15370 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15371 information will not be generated.
15372
15373 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15374 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15375
15376 @menu
15377 * Switches for gnatxref::
15378 * Switches for gnatfind::
15379 * Project Files for gnatxref and gnatfind::
15380 * Regular Expressions in gnatfind and gnatxref::
15381 * Examples of gnatxref Usage::
15382 * Examples of gnatfind Usage::
15383 @end menu
15384
15385 @node Switches for gnatxref
15386 @section @code{gnatxref} Switches
15387
15388 @noindent
15389 The command invocation for @code{gnatxref} is:
15390 @smallexample
15391 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15392 @c Expanding @ovar macro inline (explanation in macro def comments)
15393 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15394 @end smallexample
15395
15396 @noindent
15397 where
15398
15399 @table @var
15400 @item sourcefile1
15401 @itemx sourcefile2
15402 identifies the source files for which a report is to be generated. The
15403 ``with''ed units will be processed too. You must provide at least one file.
15404
15405 These file names are considered to be regular expressions, so for instance
15406 specifying @file{source*.adb} is the same as giving every file in the current
15407 directory whose name starts with @file{source} and whose extension is
15408 @file{adb}.
15409
15410 You shouldn't specify any directory name, just base names. @command{gnatxref}
15411 and @command{gnatfind} will be able to locate these files by themselves using
15412 the source path. If you specify directories, no result is produced.
15413
15414 @end table
15415
15416 @noindent
15417 The switches can be:
15418 @table @option
15419 @c !sort!
15420 @item --version
15421 @cindex @option{--version} @command{gnatxref}
15422 Display Copyright and version, then exit disregarding all other options.
15423
15424 @item --help
15425 @cindex @option{--help} @command{gnatxref}
15426 If @option{--version} was not used, display usage, then exit disregarding
15427 all other options.
15428
15429 @item ^-a^/ALL_FILES^
15430 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15431 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15432 the read-only files found in the library search path. Otherwise, these files
15433 will be ignored. This option can be used to protect Gnat sources or your own
15434 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15435 much faster, and their output much smaller. Read-only here refers to access
15436 or permissions status in the file system for the current user.
15437
15438 @item -aIDIR
15439 @cindex @option{-aIDIR} (@command{gnatxref})
15440 When looking for source files also look in directory DIR. The order in which
15441 source file search is undertaken is the same as for @command{gnatmake}.
15442
15443 @item -aODIR
15444 @cindex @option{-aODIR} (@command{gnatxref})
15445 When searching for library and object files, look in directory
15446 DIR. The order in which library files are searched is the same as for
15447 @command{gnatmake}.
15448
15449 @item -nostdinc
15450 @cindex @option{-nostdinc} (@command{gnatxref})
15451 Do not look for sources in the system default directory.
15452
15453 @item -nostdlib
15454 @cindex @option{-nostdlib} (@command{gnatxref})
15455 Do not look for library files in the system default directory.
15456
15457 @item --RTS=@var{rts-path}
15458 @cindex @option{--RTS} (@command{gnatxref})
15459 Specifies the default location of the runtime library. Same meaning as the
15460 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15461
15462 @item ^-d^/DERIVED_TYPES^
15463 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15464 If this switch is set @code{gnatxref} will output the parent type
15465 reference for each matching derived types.
15466
15467 @item ^-f^/FULL_PATHNAME^
15468 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15469 If this switch is set, the output file names will be preceded by their
15470 directory (if the file was found in the search path). If this switch is
15471 not set, the directory will not be printed.
15472
15473 @item ^-g^/IGNORE_LOCALS^
15474 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15475 If this switch is set, information is output only for library-level
15476 entities, ignoring local entities. The use of this switch may accelerate
15477 @code{gnatfind} and @code{gnatxref}.
15478
15479 @item -IDIR
15480 @cindex @option{-IDIR} (@command{gnatxref})
15481 Equivalent to @samp{-aODIR -aIDIR}.
15482
15483 @item -pFILE
15484 @cindex @option{-pFILE} (@command{gnatxref})
15485 Specify a project file to use @xref{Project Files}.
15486 If you need to use the @file{.gpr}
15487 project files, you should use gnatxref through the GNAT driver
15488 (@command{gnat xref -Pproject}).
15489
15490 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15491 project file in the current directory.
15492
15493 If a project file is either specified or found by the tools, then the content
15494 of the source directory and object directory lines are added as if they
15495 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15496 and @samp{^-aO^OBJECT_SEARCH^}.
15497 @item ^-u^/UNUSED^
15498 Output only unused symbols. This may be really useful if you give your
15499 main compilation unit on the command line, as @code{gnatxref} will then
15500 display every unused entity and 'with'ed package.
15501
15502 @ifclear vms
15503 @item -v
15504 Instead of producing the default output, @code{gnatxref} will generate a
15505 @file{tags} file that can be used by vi. For examples how to use this
15506 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15507 to the standard output, thus you will have to redirect it to a file.
15508 @end ifclear
15509
15510 @end table
15511
15512 @noindent
15513 All these switches may be in any order on the command line, and may even
15514 appear after the file names. They need not be separated by spaces, thus
15515 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15516 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15517
15518 @node Switches for gnatfind
15519 @section @code{gnatfind} Switches
15520
15521 @noindent
15522 The command line for @code{gnatfind} is:
15523
15524 @smallexample
15525 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15526 @c       @r{[}@var{file1} @var{file2} @dots{}]
15527 @c Expanding @ovar macro inline (explanation in macro def comments)
15528 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15529       @r{[}@var{file1} @var{file2} @dots{}@r{]}
15530 @end smallexample
15531
15532 @noindent
15533 where
15534
15535 @table @var
15536 @item pattern
15537 An entity will be output only if it matches the regular expression found
15538 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15539
15540 Omitting the pattern is equivalent to specifying @samp{*}, which
15541 will match any entity. Note that if you do not provide a pattern, you
15542 have to provide both a sourcefile and a line.
15543
15544 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15545 for matching purposes. At the current time there is no support for
15546 8-bit codes other than Latin-1, or for wide characters in identifiers.
15547
15548 @item sourcefile
15549 @code{gnatfind} will look for references, bodies or declarations
15550 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15551 and column @var{column}. See @ref{Examples of gnatfind Usage}
15552 for syntax examples.
15553
15554 @item line
15555 is a decimal integer identifying the line number containing
15556 the reference to the entity (or entities) to be located.
15557
15558 @item column
15559 is a decimal integer identifying the exact location on the
15560 line of the first character of the identifier for the
15561 entity reference. Columns are numbered from 1.
15562
15563 @item file1 file2 @dots{}
15564 The search will be restricted to these source files. If none are given, then
15565 the search will be done for every library file in the search path.
15566 These file must appear only after the pattern or sourcefile.
15567
15568 These file names are considered to be regular expressions, so for instance
15569 specifying @file{source*.adb} is the same as giving every file in the current
15570 directory whose name starts with @file{source} and whose extension is
15571 @file{adb}.
15572
15573 The location of the spec of the entity will always be displayed, even if it
15574 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15575 occurrences of the entity in the separate units of the ones given on the
15576 command line will also be displayed.
15577
15578 Note that if you specify at least one file in this part, @code{gnatfind} may
15579 sometimes not be able to find the body of the subprograms.
15580
15581 @end table
15582
15583 @noindent
15584 At least one of 'sourcefile' or 'pattern' has to be present on
15585 the command line.
15586
15587 The following switches are available:
15588 @table @option
15589 @c !sort!
15590
15591 @cindex @option{--version} @command{gnatfind}
15592 Display Copyright and version, then exit disregarding all other options.
15593
15594 @item --help
15595 @cindex @option{--help} @command{gnatfind}
15596 If @option{--version} was not used, display usage, then exit disregarding
15597 all other options.
15598
15599 @item ^-a^/ALL_FILES^
15600 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15601 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15602 the read-only files found in the library search path. Otherwise, these files
15603 will be ignored. This option can be used to protect Gnat sources or your own
15604 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15605 much faster, and their output much smaller. Read-only here refers to access
15606 or permission status in the file system for the current user.
15607
15608 @item -aIDIR
15609 @cindex @option{-aIDIR} (@command{gnatfind})
15610 When looking for source files also look in directory DIR. The order in which
15611 source file search is undertaken is the same as for @command{gnatmake}.
15612
15613 @item -aODIR
15614 @cindex @option{-aODIR} (@command{gnatfind})
15615 When searching for library and object files, look in directory
15616 DIR. The order in which library files are searched is the same as for
15617 @command{gnatmake}.
15618
15619 @item -nostdinc
15620 @cindex @option{-nostdinc} (@command{gnatfind})
15621 Do not look for sources in the system default directory.
15622
15623 @item -nostdlib
15624 @cindex @option{-nostdlib} (@command{gnatfind})
15625 Do not look for library files in the system default directory.
15626
15627 @item --ext=@var{extension}
15628 @cindex @option{--ext} (@command{gnatfind})
15629 Specify an alternate ali file extension. The default is @code{ali} and other
15630 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15631 switch. Note that if this switch overrides the default, which means that only
15632 the new extension will be considered.
15633
15634 @item --RTS=@var{rts-path}
15635 @cindex @option{--RTS} (@command{gnatfind})
15636 Specifies the default location of the runtime library. Same meaning as the
15637 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15638
15639 @item ^-d^/DERIVED_TYPE_INFORMATION^
15640 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15641 If this switch is set, then @code{gnatfind} will output the parent type
15642 reference for each matching derived types.
15643
15644 @item ^-e^/EXPRESSIONS^
15645 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15646 By default, @code{gnatfind} accept the simple regular expression set for
15647 @samp{pattern}. If this switch is set, then the pattern will be
15648 considered as full Unix-style regular expression.
15649
15650 @item ^-f^/FULL_PATHNAME^
15651 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15652 If this switch is set, the output file names will be preceded by their
15653 directory (if the file was found in the search path). If this switch is
15654 not set, the directory will not be printed.
15655
15656 @item ^-g^/IGNORE_LOCALS^
15657 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15658 If this switch is set, information is output only for library-level
15659 entities, ignoring local entities. The use of this switch may accelerate
15660 @code{gnatfind} and @code{gnatxref}.
15661
15662 @item -IDIR
15663 @cindex @option{-IDIR} (@command{gnatfind})
15664 Equivalent to @samp{-aODIR -aIDIR}.
15665
15666 @item -pFILE
15667 @cindex @option{-pFILE} (@command{gnatfind})
15668 Specify a project file (@pxref{Project Files}) to use.
15669 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15670 project file in the current directory.
15671
15672 If a project file is either specified or found by the tools, then the content
15673 of the source directory and object directory lines are added as if they
15674 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15675 @samp{^-aO^/OBJECT_SEARCH^}.
15676
15677 @item ^-r^/REFERENCES^
15678 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15679 By default, @code{gnatfind} will output only the information about the
15680 declaration, body or type completion of the entities. If this switch is
15681 set, the @code{gnatfind} will locate every reference to the entities in
15682 the files specified on the command line (or in every file in the search
15683 path if no file is given on the command line).
15684
15685 @item ^-s^/PRINT_LINES^
15686 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15687 If this switch is set, then @code{gnatfind} will output the content
15688 of the Ada source file lines were the entity was found.
15689
15690 @item ^-t^/TYPE_HIERARCHY^
15691 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15692 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15693 the specified type. It act like -d option but recursively from parent
15694 type to parent type. When this switch is set it is not possible to
15695 specify more than one file.
15696
15697 @end table
15698
15699 @noindent
15700 All these switches may be in any order on the command line, and may even
15701 appear after the file names. They need not be separated by spaces, thus
15702 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15703 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15704
15705 As stated previously, gnatfind will search in every directory in the
15706 search path. You can force it to look only in the current directory if
15707 you specify @code{*} at the end of the command line.
15708
15709 @node Project Files for gnatxref and gnatfind
15710 @section Project Files for @command{gnatxref} and @command{gnatfind}
15711
15712 @noindent
15713 Project files allow a programmer to specify how to compile its
15714 application, where to find sources, etc.  These files are used
15715 @ifclear vms
15716 primarily by GPS, but they can also be used
15717 @end ifclear
15718 by the two tools
15719 @code{gnatxref} and @code{gnatfind}.
15720
15721 A project file name must end with @file{.gpr}. If a single one is
15722 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15723 extract the information from it. If multiple project files are found, none of
15724 them is read, and you have to use the @samp{-p} switch to specify the one
15725 you want to use.
15726
15727 The following lines can be included, even though most of them have default
15728 values which can be used in most cases.
15729 The lines can be entered in any order in the file.
15730 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15731 each line. If you have multiple instances, only the last one is taken into
15732 account.
15733
15734 @table @code
15735 @item src_dir=DIR
15736 [default: @code{"^./^[]^"}]
15737 specifies a directory where to look for source files. Multiple @code{src_dir}
15738 lines can be specified and they will be searched in the order they
15739 are specified.
15740
15741 @item obj_dir=DIR
15742 [default: @code{"^./^[]^"}]
15743 specifies a directory where to look for object and library files. Multiple
15744 @code{obj_dir} lines can be specified, and they will be searched in the order
15745 they are specified
15746
15747 @item comp_opt=SWITCHES
15748 [default: @code{""}]
15749 creates a variable which can be referred to subsequently by using
15750 the @code{$@{comp_opt@}} notation. This is intended to store the default
15751 switches given to @command{gnatmake} and @command{gcc}.
15752
15753 @item bind_opt=SWITCHES
15754 [default: @code{""}]
15755 creates a variable which can be referred to subsequently by using
15756 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15757 switches given to @command{gnatbind}.
15758
15759 @item link_opt=SWITCHES
15760 [default: @code{""}]
15761 creates a variable which can be referred to subsequently by using
15762 the @samp{$@{link_opt@}} notation. This is intended to store the default
15763 switches given to @command{gnatlink}.
15764
15765 @item main=EXECUTABLE
15766 [default: @code{""}]
15767 specifies the name of the executable for the application. This variable can
15768 be referred to in the following lines by using the @samp{$@{main@}} notation.
15769
15770 @ifset vms
15771 @item comp_cmd=COMMAND
15772 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15773 @end ifset
15774 @ifclear vms
15775 @item comp_cmd=COMMAND
15776 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15777 @end ifclear
15778 specifies the command used to compile a single file in the application.
15779
15780 @ifset vms
15781 @item make_cmd=COMMAND
15782 [default: @code{"GNAT MAKE $@{main@}
15783 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15784 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15785 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15786 @end ifset
15787 @ifclear vms
15788 @item make_cmd=COMMAND
15789 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15790 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15791 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15792 @end ifclear
15793 specifies the command used to recompile the whole application.
15794
15795 @item run_cmd=COMMAND
15796 [default: @code{"$@{main@}"}]
15797 specifies the command used to run the application.
15798
15799 @item debug_cmd=COMMAND
15800 [default: @code{"gdb $@{main@}"}]
15801 specifies the command used to debug the application
15802
15803 @end table
15804
15805 @noindent
15806 @command{gnatxref} and @command{gnatfind} only take into account the
15807 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15808
15809 @node Regular Expressions in gnatfind and gnatxref
15810 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15811
15812 @noindent
15813 As specified in the section about @command{gnatfind}, the pattern can be a
15814 regular expression. Actually, there are to set of regular expressions
15815 which are recognized by the program:
15816
15817 @table @code
15818 @item globbing patterns
15819 These are the most usual regular expression. They are the same that you
15820 generally used in a Unix shell command line, or in a DOS session.
15821
15822 Here is a more formal grammar:
15823 @smallexample
15824 @group
15825 @iftex
15826 @leftskip=.5cm
15827 @end iftex
15828 regexp ::= term
15829 term   ::= elmt            -- matches elmt
15830 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15831 term   ::= *               -- any string of 0 or more characters
15832 term   ::= ?               -- matches any character
15833 term   ::= [char @{char@}]   -- matches any character listed
15834 term   ::= [char - char]   -- matches any character in range
15835 @end group
15836 @end smallexample
15837
15838 @item full regular expression
15839 The second set of regular expressions is much more powerful. This is the
15840 type of regular expressions recognized by utilities such a @file{grep}.
15841
15842 The following is the form of a regular expression, expressed in Ada
15843 reference manual style BNF is as follows
15844
15845 @smallexample
15846 @iftex
15847 @leftskip=.5cm
15848 @end iftex
15849 @group
15850 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15851
15852 term ::= item @{item@}       -- concatenation (item then item)
15853
15854 item ::= elmt              -- match elmt
15855 item ::= elmt *            -- zero or more elmt's
15856 item ::= elmt +            -- one or more elmt's
15857 item ::= elmt ?            -- matches elmt or nothing
15858 @end group
15859 @group
15860 elmt ::= nschar            -- matches given character
15861 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15862 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15863 elmt ::= [char - char]     -- matches chars in given range
15864 elmt ::= \ char            -- matches given character
15865 elmt ::= .                 -- matches any single character
15866 elmt ::= ( regexp )        -- parens used for grouping
15867
15868 char ::= any character, including special characters
15869 nschar ::= any character except ()[].*+?^^^
15870 @end group
15871 @end smallexample
15872
15873 Following are a few examples:
15874
15875 @table @samp
15876 @item abcde|fghi
15877 will match any of the two strings @samp{abcde} and @samp{fghi},
15878
15879 @item abc*d
15880 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15881 @samp{abcccd}, and so on,
15882
15883 @item [a-z]+
15884 will match any string which has only lowercase characters in it (and at
15885 least one character.
15886
15887 @end table
15888 @end table
15889
15890 @node Examples of gnatxref Usage
15891 @section Examples of @code{gnatxref} Usage
15892
15893 @subsection General Usage
15894
15895 @noindent
15896 For the following examples, we will consider the following units:
15897
15898 @smallexample @c ada
15899 @group
15900 @cartouche
15901 main.ads:
15902 1: with Bar;
15903 2: package Main is
15904 3:     procedure Foo (B : in Integer);
15905 4:     C : Integer;
15906 5: private
15907 6:     D : Integer;
15908 7: end Main;
15909
15910 main.adb:
15911 1: package body Main is
15912 2:     procedure Foo (B : in Integer) is
15913 3:     begin
15914 4:        C := B;
15915 5:        D := B;
15916 6:        Bar.Print (B);
15917 7:        Bar.Print (C);
15918 8:     end Foo;
15919 9: end Main;
15920
15921 bar.ads:
15922 1: package Bar is
15923 2:     procedure Print (B : Integer);
15924 3: end bar;
15925 @end cartouche
15926 @end group
15927 @end smallexample
15928
15929 @table @code
15930
15931 @noindent
15932 The first thing to do is to recompile your application (for instance, in
15933 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15934 the cross-referencing information.
15935 You can then issue any of the following commands:
15936
15937 @item gnatxref main.adb
15938 @code{gnatxref} generates cross-reference information for main.adb
15939 and every unit 'with'ed by main.adb.
15940
15941 The output would be:
15942 @smallexample
15943 @iftex
15944 @leftskip=0cm
15945 @end iftex
15946 B                                                      Type: Integer
15947   Decl: bar.ads           2:22
15948 B                                                      Type: Integer
15949   Decl: main.ads          3:20
15950   Body: main.adb          2:20
15951   Ref:  main.adb          4:13     5:13     6:19
15952 Bar                                                    Type: Unit
15953   Decl: bar.ads           1:9
15954   Ref:  main.adb          6:8      7:8
15955        main.ads           1:6
15956 C                                                      Type: Integer
15957   Decl: main.ads          4:5
15958   Modi: main.adb          4:8
15959   Ref:  main.adb          7:19
15960 D                                                      Type: Integer
15961   Decl: main.ads          6:5
15962   Modi: main.adb          5:8
15963 Foo                                                    Type: Unit
15964   Decl: main.ads          3:15
15965   Body: main.adb          2:15
15966 Main                                                    Type: Unit
15967   Decl: main.ads          2:9
15968   Body: main.adb          1:14
15969 Print                                                   Type: Unit
15970   Decl: bar.ads           2:15
15971   Ref:  main.adb          6:12     7:12
15972 @end smallexample
15973
15974 @noindent
15975 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15976 its body is in main.adb, line 1, column 14 and is not referenced any where.
15977
15978 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15979 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15980
15981 @item gnatxref package1.adb package2.ads
15982 @code{gnatxref} will generates cross-reference information for
15983 package1.adb, package2.ads and any other package 'with'ed by any
15984 of these.
15985
15986 @end table
15987
15988 @ifclear vms
15989 @subsection Using gnatxref with vi
15990
15991 @code{gnatxref} can generate a tags file output, which can be used
15992 directly from @command{vi}. Note that the standard version of @command{vi}
15993 will not work properly with overloaded symbols. Consider using another
15994 free implementation of @command{vi}, such as @command{vim}.
15995
15996 @smallexample
15997 $ gnatxref -v gnatfind.adb > tags
15998 @end smallexample
15999
16000 @noindent
16001 will generate the tags file for @code{gnatfind} itself (if the sources
16002 are in the search path!).
16003
16004 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
16005 (replacing @var{entity} by whatever you are looking for), and vi will
16006 display a new file with the corresponding declaration of entity.
16007 @end ifclear
16008
16009 @node Examples of gnatfind Usage
16010 @section Examples of @code{gnatfind} Usage
16011
16012 @table @code
16013
16014 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
16015 Find declarations for all entities xyz referenced at least once in
16016 main.adb. The references are search in every library file in the search
16017 path.
16018
16019 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
16020 switch is set)
16021
16022 The output will look like:
16023 @smallexample
16024 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16025 ^directory/^[directory]^main.adb:24:10: xyz <= body
16026 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16027 @end smallexample
16028
16029 @noindent
16030 that is to say, one of the entities xyz found in main.adb is declared at
16031 line 12 of main.ads (and its body is in main.adb), and another one is
16032 declared at line 45 of foo.ads
16033
16034 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16035 This is the same command as the previous one, instead @code{gnatfind} will
16036 display the content of the Ada source file lines.
16037
16038 The output will look like:
16039
16040 @smallexample
16041 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16042    procedure xyz;
16043 ^directory/^[directory]^main.adb:24:10: xyz <= body
16044    procedure xyz is
16045 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16046    xyz : Integer;
16047 @end smallexample
16048
16049 @noindent
16050 This can make it easier to find exactly the location your are looking
16051 for.
16052
16053 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16054 Find references to all entities containing an x that are
16055 referenced on line 123 of main.ads.
16056 The references will be searched only in main.ads and foo.adb.
16057
16058 @item gnatfind main.ads:123
16059 Find declarations and bodies for all entities that are referenced on
16060 line 123 of main.ads.
16061
16062 This is the same as @code{gnatfind "*":main.adb:123}.
16063
16064 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16065 Find the declaration for the entity referenced at column 45 in
16066 line 123 of file main.adb in directory mydir. Note that it
16067 is usual to omit the identifier name when the column is given,
16068 since the column position identifies a unique reference.
16069
16070 The column has to be the beginning of the identifier, and should not
16071 point to any character in the middle of the identifier.
16072
16073 @end table
16074
16075 @c *********************************
16076 @node The GNAT Pretty-Printer gnatpp
16077 @chapter The GNAT Pretty-Printer @command{gnatpp}
16078 @findex gnatpp
16079 @cindex Pretty-Printer
16080
16081 @noindent
16082 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16083 for source reformatting / pretty-printing.
16084 It takes an Ada source file as input and generates a reformatted
16085 version as output.
16086 You can specify various style directives via switches; e.g.,
16087 identifier case conventions, rules of indentation, and comment layout.
16088
16089 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16090 tree for the input source and thus requires the input to be syntactically and
16091 semantically legal.
16092 If this condition is not met, @command{gnatpp} will terminate with an
16093 error message; no output file will be generated.
16094
16095 If the source files presented to @command{gnatpp} contain
16096 preprocessing directives, then the output file will
16097 correspond to the generated source after all
16098 preprocessing is carried out. There is no way
16099 using @command{gnatpp} to obtain pretty printed files that
16100 include the preprocessing directives.
16101
16102 If the compilation unit
16103 contained in the input source depends semantically upon units located
16104 outside the current directory, you have to provide the source search path
16105 when invoking @command{gnatpp}, if these units are contained in files with
16106 names that do not follow the GNAT file naming rules, you have to provide
16107 the configuration file describing the corresponding naming scheme;
16108 see the description of the @command{gnatpp}
16109 switches below. Another possibility is to use a project file and to
16110 call @command{gnatpp} through the @command{gnat} driver
16111
16112 The @command{gnatpp} command has the form
16113
16114 @smallexample
16115 @c $ gnatpp @ovar{switches} @var{filename}
16116 @c Expanding @ovar macro inline (explanation in macro def comments)
16117 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
16118 @end smallexample
16119
16120 @noindent
16121 where
16122 @itemize @bullet
16123 @item
16124 @var{switches} is an optional sequence of switches defining such properties as
16125 the formatting rules, the source search path, and the destination for the
16126 output source file
16127
16128 @item
16129 @var{filename} is the name (including the extension) of the source file to
16130 reformat; ``wildcards'' or several file names on the same gnatpp command are
16131 allowed.  The file name may contain path information; it does not have to
16132 follow the GNAT file naming rules
16133
16134 @item
16135 @samp{@var{gcc_switches}} is a list of switches for
16136 @command{gcc}. They will be passed on to all compiler invocations made by
16137 @command{gnatelim} to generate the ASIS trees. Here you can provide
16138 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16139 use the @option{-gnatec} switch to set the configuration file etc.
16140 @end itemize
16141
16142 @menu
16143 * Switches for gnatpp::
16144 * Formatting Rules::
16145 @end menu
16146
16147 @node Switches for gnatpp
16148 @section Switches for @command{gnatpp}
16149
16150 @noindent
16151 The following subsections describe the various switches accepted by
16152 @command{gnatpp}, organized by category.
16153
16154 @ifclear vms
16155 You specify a switch by supplying a name and generally also a value.
16156 In many cases the values for a switch with a given name are incompatible with
16157 each other
16158 (for example the switch that controls the casing of a reserved word may have
16159 exactly one value: upper case, lower case, or
16160 mixed case) and thus exactly one such switch can be in effect for an
16161 invocation of @command{gnatpp}.
16162 If more than one is supplied, the last one is used.
16163 However, some values for the same switch are mutually compatible.
16164 You may supply several such switches to @command{gnatpp}, but then
16165 each must be specified in full, with both the name and the value.
16166 Abbreviated forms (the name appearing once, followed by each value) are
16167 not permitted.
16168 For example, to set
16169 the alignment of the assignment delimiter both in declarations and in
16170 assignment statements, you must write @option{-A2A3}
16171 (or @option{-A2 -A3}), but not @option{-A23}.
16172 @end ifclear
16173
16174 @ifset vms
16175 In many cases the set of options for a given qualifier are incompatible with
16176 each other (for example the qualifier that controls the casing of a reserved
16177 word may have exactly one option, which specifies either upper case, lower
16178 case, or mixed case), and thus exactly one such option can be in effect for
16179 an invocation of @command{gnatpp}.
16180 If more than one is supplied, the last one is used.
16181 However, some qualifiers have options that are mutually compatible,
16182 and then you may then supply several such options when invoking
16183 @command{gnatpp}.
16184 @end ifset
16185
16186 In most cases, it is obvious whether or not the
16187 ^values for a switch with a given name^options for a given qualifier^
16188 are compatible with each other.
16189 When the semantics might not be evident, the summaries below explicitly
16190 indicate the effect.
16191
16192 @menu
16193 * Alignment Control::
16194 * Casing Control::
16195 * Construct Layout Control::
16196 * General Text Layout Control::
16197 * Other Formatting Options::
16198 * Setting the Source Search Path::
16199 * Output File Control::
16200 * Other gnatpp Switches::
16201 @end menu
16202
16203 @node Alignment Control
16204 @subsection Alignment Control
16205 @cindex Alignment control in @command{gnatpp}
16206
16207 @noindent
16208 Programs can be easier to read if certain constructs are vertically aligned.
16209 By default all alignments are set ON.
16210 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16211 OFF, and then use one or more of the other
16212 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16213 to activate alignment for specific constructs.
16214
16215 @table @option
16216 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16217
16218 @ifset vms
16219 @item /ALIGN=ON
16220 Set all alignments to ON
16221 @end ifset
16222
16223 @item ^-A0^/ALIGN=OFF^
16224 Set all alignments to OFF
16225
16226 @item ^-A1^/ALIGN=COLONS^
16227 Align @code{:} in declarations
16228
16229 @item ^-A2^/ALIGN=DECLARATIONS^
16230 Align @code{:=} in initializations in declarations
16231
16232 @item ^-A3^/ALIGN=STATEMENTS^
16233 Align @code{:=} in assignment statements
16234
16235 @item ^-A4^/ALIGN=ARROWS^
16236 Align @code{=>} in associations
16237
16238 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16239 Align @code{at} keywords in the component clauses in record
16240 representation clauses
16241 @end table
16242
16243 @noindent
16244 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16245 is allowed.
16246
16247 @node Casing Control
16248 @subsection Casing Control
16249 @cindex Casing control in @command{gnatpp}
16250
16251 @noindent
16252 @command{gnatpp} allows you to specify the casing for reserved words,
16253 pragma names, attribute designators and identifiers.
16254 For identifiers you may define a
16255 general rule for name casing but also override this rule
16256 via a set of dictionary files.
16257
16258 Three types of casing are supported: lower case, upper case, and mixed case.
16259 Lower and upper case are self-explanatory (but since some letters in
16260 Latin1 and other GNAT-supported character sets
16261 exist only in lower-case form, an upper case conversion will have no
16262 effect on them.)
16263 ``Mixed case'' means that the first letter, and also each letter immediately
16264 following an underscore, are converted to their uppercase forms;
16265 all the other letters are converted to their lowercase forms.
16266
16267 @table @option
16268 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16269 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16270 Attribute designators are lower case
16271
16272 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16273 Attribute designators are upper case
16274
16275 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16276 Attribute designators are mixed case (this is the default)
16277
16278 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16279 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16280 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16281 lower case (this is the default)
16282
16283 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16284 Keywords are upper case
16285
16286 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16287 @item ^-nD^/NAME_CASING=AS_DECLARED^
16288 Name casing for defining occurrences are as they appear in the source file
16289 (this is the default)
16290
16291 @item ^-nU^/NAME_CASING=UPPER_CASE^
16292 Names are in upper case
16293
16294 @item ^-nL^/NAME_CASING=LOWER_CASE^
16295 Names are in lower case
16296
16297 @item ^-nM^/NAME_CASING=MIXED_CASE^
16298 Names are in mixed case
16299
16300 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16301 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16302 Pragma names are lower case
16303
16304 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16305 Pragma names are upper case
16306
16307 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16308 Pragma names are mixed case (this is the default)
16309
16310 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16311 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16312 Use @var{file} as a @emph{dictionary file} that defines
16313 the casing for a set of specified names,
16314 thereby overriding the effect on these names by
16315 any explicit or implicit
16316 ^-n^/NAME_CASING^ switch.
16317 To supply more than one dictionary file,
16318 use ^several @option{-D} switches^a list of files as options^.
16319
16320 @noindent
16321 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16322 to define the casing for the Ada predefined names and
16323 the names declared in the GNAT libraries.
16324
16325 @item ^-D-^/SPECIFIC_CASING^
16326 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16327 Do not use the default dictionary file;
16328 instead, use the casing
16329 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16330 dictionary file(s)
16331 @end table
16332
16333 @noindent
16334 The structure of a dictionary file, and details on the conventions
16335 used in the default dictionary file, are defined in @ref{Name Casing}.
16336
16337 The @option{^-D-^/SPECIFIC_CASING^} and
16338 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16339 compatible.
16340
16341 @node Construct Layout Control
16342 @subsection Construct Layout Control
16343 @cindex Layout control in @command{gnatpp}
16344
16345 @noindent
16346 This group of @command{gnatpp} switches controls the layout of comments and
16347 complex syntactic constructs.  See @ref{Formatting Comments} for details
16348 on their effect.
16349
16350 @table @option
16351 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16352 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16353 All the comments remain unchanged
16354
16355 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16356 GNAT-style comment line indentation (this is the default).
16357
16358 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16359 Reference-manual comment line indentation.
16360
16361 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16362 GNAT-style comment beginning
16363
16364 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16365 Reformat comment blocks
16366
16367 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16368 Keep unchanged special form comments
16369
16370 Reformat comment blocks
16371
16372 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16373 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16374 GNAT-style layout (this is the default)
16375
16376 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16377 Compact layout
16378
16379 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16380 Uncompact layout
16381
16382 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16383 @item ^-N^/NOTABS^
16384 All the VT characters are removed from the comment text. All the HT characters
16385 are expanded with the sequences of space characters to get to the next tab
16386 stops.
16387
16388 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16389 @item ^--no-separate-is^/NO_SEPARATE_IS^
16390 Do not place the keyword @code{is} on a separate line in a subprogram body in
16391 case if the spec occupies more then one line.
16392
16393 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16394 @item ^--separate-label^/SEPARATE_LABEL^
16395 Place statement label(s) on a separate line, with the following statement
16396 on the next line.
16397
16398 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16399 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16400 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16401 keyword @code{then} in IF statements on a separate line.
16402
16403 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16404 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16405 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16406 keyword @code{then} in IF statements on a separate line. This option is
16407 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16408
16409 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16410 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16411 Start each USE clause in a context clause from a separate line.
16412
16413 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16414 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16415 Use a separate line for a loop or block statement name, but do not use an extra
16416 indentation level for the statement itself.
16417
16418 @end table
16419
16420 @ifclear vms
16421 @noindent
16422 The @option{-c1} and @option{-c2} switches are incompatible.
16423 The @option{-c3} and @option{-c4} switches are compatible with each other and
16424 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16425 the other comment formatting switches.
16426
16427 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16428 @end ifclear
16429
16430 @ifset vms
16431 @noindent
16432 For the @option{/COMMENTS_LAYOUT} qualifier:
16433 @itemize @bullet
16434 @item
16435 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16436 @item
16437 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16438 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16439 @end itemize
16440
16441 @noindent
16442 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16443 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16444 @end ifset
16445
16446 @node General Text Layout Control
16447 @subsection General Text Layout Control
16448
16449 @noindent
16450 These switches allow control over line length and indentation.
16451
16452 @table @option
16453 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16454 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16455 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16456
16457 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16458 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16459 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16460
16461 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16462 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16463 Indentation level for continuation lines (relative to the line being
16464 continued), @var{nnn} from 1@dots{}9.
16465 The default
16466 value is one less then the (normal) indentation level, unless the
16467 indentation is set to 1 (in which case the default value for continuation
16468 line indentation is also 1)
16469 @end table
16470
16471 @node Other Formatting Options
16472 @subsection Other Formatting Options
16473
16474 @noindent
16475 These switches control the inclusion of missing end/exit labels, and
16476 the indentation level in @b{case} statements.
16477
16478 @table @option
16479 @item ^-e^/NO_MISSED_LABELS^
16480 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16481 Do not insert missing end/exit labels. An end label is the name of
16482 a construct that may optionally be repeated at the end of the
16483 construct's declaration;
16484 e.g., the names of packages, subprograms, and tasks.
16485 An exit label is the name of a loop that may appear as target
16486 of an exit statement within the loop.
16487 By default, @command{gnatpp} inserts these end/exit labels when
16488 they are absent from the original source. This option suppresses such
16489 insertion, so that the formatted source reflects the original.
16490
16491 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16492 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16493 Insert a Form Feed character after a pragma Page.
16494
16495 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16496 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16497 Do not use an additional indentation level for @b{case} alternatives
16498 and variants if there are @var{nnn} or more (the default
16499 value is 10).
16500 If @var{nnn} is 0, an additional indentation level is
16501 used for @b{case} alternatives and variants regardless of their number.
16502 @end table
16503
16504 @node Setting the Source Search Path
16505 @subsection Setting the Source Search Path
16506
16507 @noindent
16508 To define the search path for the input source file, @command{gnatpp}
16509 uses the same switches as the GNAT compiler, with the same effects.
16510
16511 @table @option
16512 @item ^-I^/SEARCH=^@var{dir}
16513 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16514 The same as the corresponding gcc switch
16515
16516 @item ^-I-^/NOCURRENT_DIRECTORY^
16517 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16518 The same as the corresponding gcc switch
16519
16520 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16521 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16522 The same as the corresponding gcc switch
16523
16524 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16525 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16526 The same as the corresponding gcc switch
16527
16528 @end table
16529
16530 @node Output File Control
16531 @subsection Output File Control
16532
16533 @noindent
16534 By default the output is sent to the file whose name is obtained by appending
16535 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16536 (if the file with this name already exists, it is unconditionally overwritten).
16537 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16538 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16539 as output file.
16540 The output may be redirected by the following switches:
16541
16542 @table @option
16543 @item ^-pipe^/STANDARD_OUTPUT^
16544 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16545 Send the output to @code{Standard_Output}
16546
16547 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16548 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16549 Write the output into @var{output_file}.
16550 If @var{output_file} already exists, @command{gnatpp} terminates without
16551 reading or processing the input file.
16552
16553 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16554 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16555 Write the output into @var{output_file}, overwriting the existing file
16556 (if one is present).
16557
16558 @item ^-r^/REPLACE^
16559 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16560 Replace the input source file with the reformatted output, and copy the
16561 original input source into the file whose name is obtained by appending the
16562 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16563 If a file with this name already exists, @command{gnatpp} terminates without
16564 reading or processing the input file.
16565
16566 @item ^-rf^/OVERRIDING_REPLACE^
16567 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16568 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16569 already exists, it is overwritten.
16570
16571 @item ^-rnb^/REPLACE_NO_BACKUP^
16572 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16573 Replace the input source file with the reformatted output without
16574 creating any backup copy of the input source.
16575
16576 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16577 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16578 Specifies the format of the reformatted output file. The @var{xxx}
16579 ^string specified with the switch^option^ may be either
16580 @itemize @bullet
16581 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16582 @item ``@option{^crlf^CRLF^}''
16583 the same as @option{^crlf^CRLF^}
16584 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16585 @item ``@option{^lf^LF^}''
16586 the same as @option{^unix^UNIX^}
16587 @end itemize
16588
16589 @item ^-W^/RESULT_ENCODING=^@var{e}
16590 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16591 Specify the wide character encoding method used to write the code in the
16592 result file
16593 @var{e} is one of the following:
16594
16595 @itemize @bullet
16596
16597 @item ^h^HEX^
16598 Hex encoding
16599
16600 @item ^u^UPPER^
16601 Upper half encoding
16602
16603 @item ^s^SHIFT_JIS^
16604 Shift/JIS encoding
16605
16606 @item ^e^EUC^
16607 EUC encoding
16608
16609 @item ^8^UTF8^
16610 UTF-8 encoding
16611
16612 @item ^b^BRACKETS^
16613 Brackets encoding (default value)
16614 @end itemize
16615
16616 @end table
16617
16618 @noindent
16619 Options @option{^-pipe^/STANDARD_OUTPUT^},
16620 @option{^-o^/OUTPUT^} and
16621 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16622 contains only one file to reformat.
16623 Option
16624 @option{^--eol^/END_OF_LINE^}
16625 and
16626 @option{^-W^/RESULT_ENCODING^}
16627 cannot be used together
16628 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16629
16630 @node Other gnatpp Switches
16631 @subsection Other @code{gnatpp} Switches
16632
16633 @noindent
16634 The additional @command{gnatpp} switches are defined in this subsection.
16635
16636 @table @option
16637 @item ^-files @var{filename}^/FILES=@var{filename}^
16638 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16639 Take the argument source files from the specified file. This file should be an
16640 ordinary text file containing file names separated by spaces or
16641 line breaks. You can use this switch more than once in the same call to
16642 @command{gnatpp}. You also can combine this switch with an explicit list of
16643 files.
16644
16645 @item ^-v^/VERBOSE^
16646 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16647 Verbose mode;
16648 @command{gnatpp} generates version information and then
16649 a trace of the actions it takes to produce or obtain the ASIS tree.
16650
16651 @item ^-w^/WARNINGS^
16652 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16653 Warning mode;
16654 @command{gnatpp} generates a warning whenever it cannot provide
16655 a required layout in the result source.
16656 @end table
16657
16658 @node Formatting Rules
16659 @section Formatting Rules
16660
16661 @noindent
16662 The following subsections show how @command{gnatpp} treats ``white space'',
16663 comments, program layout, and name casing.
16664 They provide the detailed descriptions of the switches shown above.
16665
16666 @menu
16667 * White Space and Empty Lines::
16668 * Formatting Comments::
16669 * Construct Layout::
16670 * Name Casing::
16671 @end menu
16672
16673 @node White Space and Empty Lines
16674 @subsection White Space and Empty Lines
16675
16676 @noindent
16677 @command{gnatpp} does not have an option to control space characters.
16678 It will add or remove spaces according to the style illustrated by the
16679 examples in the @cite{Ada Reference Manual}.
16680
16681 The only format effectors
16682 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16683 that will appear in the output file are platform-specific line breaks,
16684 and also format effectors within (but not at the end of) comments.
16685 In particular, each horizontal tab character that is not inside
16686 a comment will be treated as a space and thus will appear in the
16687 output file as zero or more spaces depending on
16688 the reformatting of the line in which it appears.
16689 The only exception is a Form Feed character, which is inserted after a
16690 pragma @code{Page} when @option{-ff} is set.
16691
16692 The output file will contain no lines with trailing ``white space'' (spaces,
16693 format effectors).
16694
16695 Empty lines in the original source are preserved
16696 only if they separate declarations or statements.
16697 In such contexts, a
16698 sequence of two or more empty lines is replaced by exactly one empty line.
16699 Note that a blank line will be removed if it separates two ``comment blocks''
16700 (a comment block is a sequence of whole-line comments).
16701 In order to preserve a visual separation between comment blocks, use an
16702 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16703 Likewise, if for some reason you wish to have a sequence of empty lines,
16704 use a sequence of empty comments instead.
16705
16706 @node Formatting Comments
16707 @subsection Formatting Comments
16708
16709 @noindent
16710 Comments in Ada code are of two kinds:
16711 @itemize @bullet
16712 @item
16713 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16714 ``white space'') on a line
16715
16716 @item
16717 an @emph{end-of-line comment}, which follows some other Ada lexical element
16718 on the same line.
16719 @end itemize
16720
16721 @noindent
16722 The indentation of a whole-line comment is that of either
16723 the preceding or following line in
16724 the formatted source, depending on switch settings as will be described below.
16725
16726 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16727 between the end of the preceding Ada lexical element and the beginning
16728 of the comment as appear in the original source,
16729 unless either the comment has to be split to
16730 satisfy the line length limitation, or else the next line contains a
16731 whole line comment that is considered a continuation of this end-of-line
16732 comment (because it starts at the same position).
16733 In the latter two
16734 cases, the start of the end-of-line comment is moved right to the nearest
16735 multiple of the indentation level.
16736 This may result in a ``line overflow'' (the right-shifted comment extending
16737 beyond the maximum line length), in which case the comment is split as
16738 described below.
16739
16740 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16741 (GNAT-style comment line indentation)
16742 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16743 (reference-manual comment line indentation).
16744 With reference-manual style, a whole-line comment is indented as if it
16745 were a declaration or statement at the same place
16746 (i.e., according to the indentation of the preceding line(s)).
16747 With GNAT style, a whole-line comment that is immediately followed by an
16748 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16749 word @b{begin}, is indented based on the construct that follows it.
16750
16751 For example:
16752 @smallexample @c ada
16753 @cartouche
16754 if A then
16755     null;
16756        -- some comment
16757 else
16758    null;
16759 end if;
16760 @end cartouche
16761 @end smallexample
16762
16763 @noindent
16764 Reference-manual indentation produces:
16765
16766 @smallexample @c ada
16767 @cartouche
16768 if A then
16769    null;
16770    --  some comment
16771 else
16772    null;
16773 end if;
16774 @end cartouche
16775 @end smallexample
16776
16777 @noindent
16778 while GNAT-style indentation produces:
16779
16780 @smallexample @c ada
16781 @cartouche
16782 if A then
16783    null;
16784 --  some comment
16785 else
16786    null;
16787 end if;
16788 @end cartouche
16789 @end smallexample
16790
16791 @noindent
16792 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16793 (GNAT style comment beginning) has the following
16794 effect:
16795
16796 @itemize @bullet
16797 @item
16798 For each whole-line comment that does not end with two hyphens,
16799 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16800 to ensure that there are at least two spaces between these hyphens and the
16801 first non-blank character of the comment.
16802 @end itemize
16803
16804 @noindent
16805 For an end-of-line comment, if in the original source the next line is a
16806 whole-line comment that starts at the same position
16807 as the end-of-line comment,
16808 then the whole-line comment (and all whole-line comments
16809 that follow it and that start at the same position)
16810 will start at this position in the output file.
16811
16812 @noindent
16813 That is, if in the original source we have:
16814
16815 @smallexample @c ada
16816 @cartouche
16817 begin
16818 A := B + C;            --  B must be in the range Low1..High1
16819                        --  C must be in the range Low2..High2
16820              --B+C will be in the range Low1+Low2..High1+High2
16821 X := X + 1;
16822 @end cartouche
16823 @end smallexample
16824
16825 @noindent
16826 Then in the formatted source we get
16827
16828 @smallexample @c ada
16829 @cartouche
16830 begin
16831    A := B + C;            --  B must be in the range Low1..High1
16832                           --  C must be in the range Low2..High2
16833    --  B+C will be in the range Low1+Low2..High1+High2
16834    X := X + 1;
16835 @end cartouche
16836 @end smallexample
16837
16838 @noindent
16839 A comment that exceeds the line length limit will be split.
16840 Unless switch
16841 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16842 the line belongs to a reformattable block, splitting the line generates a
16843 @command{gnatpp} warning.
16844 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16845 comments may be reformatted in typical
16846 word processor style (that is, moving words between lines and putting as
16847 many words in a line as possible).
16848
16849 @noindent
16850 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16851 that has a special format (that is, a character that is neither a letter nor digit
16852 not white space nor line break immediately following the leading @code{--} of
16853 the comment) should be without any change moved from the argument source
16854 into reformatted source. This switch allows to preserve comments that are used
16855 as a special marks in the code (e.g.@: SPARK annotation).
16856
16857 @node Construct Layout
16858 @subsection Construct Layout
16859
16860 @noindent
16861 In several cases the suggested layout in the Ada Reference Manual includes
16862 an extra level of indentation that many programmers prefer to avoid. The
16863 affected cases include:
16864
16865 @itemize @bullet
16866
16867 @item Record type declaration (RM 3.8)
16868
16869 @item Record representation clause (RM 13.5.1)
16870
16871 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16872
16873 @item Block statement in case if a block has a statement identifier (RM 5.6)
16874 @end itemize
16875
16876 @noindent
16877 In compact mode (when GNAT style layout or compact layout is set),
16878 the pretty printer uses one level of indentation instead
16879 of two. This is achieved in the record definition and record representation
16880 clause cases by putting the @code{record} keyword on the same line as the
16881 start of the declaration or representation clause, and in the block and loop
16882 case by putting the block or loop header on the same line as the statement
16883 identifier.
16884
16885 @noindent
16886 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16887 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16888 layout on the one hand, and uncompact layout
16889 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16890 can be illustrated by the following examples:
16891
16892 @iftex
16893 @cartouche
16894 @multitable @columnfractions .5 .5
16895 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16896
16897 @item
16898 @smallexample @c ada
16899 type q is record
16900    a : integer;
16901    b : integer;
16902 end record;
16903 @end smallexample
16904 @tab
16905 @smallexample @c ada
16906 type q is
16907    record
16908       a : integer;
16909       b : integer;
16910    end record;
16911 @end smallexample
16912
16913 @item
16914 @smallexample @c ada
16915 for q use record
16916    a at 0 range  0 .. 31;
16917    b at 4 range  0 .. 31;
16918 end record;
16919 @end smallexample
16920 @tab
16921 @smallexample @c ada
16922 for q use
16923    record
16924       a at 0 range  0 .. 31;
16925       b at 4 range  0 .. 31;
16926    end record;
16927 @end smallexample
16928
16929 @item
16930 @smallexample @c ada
16931 Block : declare
16932    A : Integer := 3;
16933 begin
16934    Proc (A, A);
16935 end Block;
16936 @end smallexample
16937 @tab
16938 @smallexample @c ada
16939 Block :
16940    declare
16941       A : Integer := 3;
16942    begin
16943       Proc (A, A);
16944    end Block;
16945 @end smallexample
16946
16947 @item
16948 @smallexample @c ada
16949 Clear : for J in 1 .. 10 loop
16950    A (J) := 0;
16951 end loop Clear;
16952 @end smallexample
16953 @tab
16954 @smallexample @c ada
16955 Clear :
16956    for J in 1 .. 10 loop
16957       A (J) := 0;
16958    end loop Clear;
16959 @end smallexample
16960 @end multitable
16961 @end cartouche
16962 @end iftex
16963
16964 @ifnottex
16965 @smallexample
16966 @cartouche
16967 GNAT style, compact layout              Uncompact layout
16968
16969 type q is record                        type q is
16970    a : integer;                            record
16971    b : integer;                               a : integer;
16972 end record;                                   b : integer;
16973                                            end record;
16974
16975 for q use record                        for q use
16976    a at 0 range  0 .. 31;                  record
16977    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16978 end record;                                   b at 4 range  0 .. 31;
16979                                            end record;
16980
16981 Block : declare                         Block :
16982    A : Integer := 3;                       declare
16983 begin                                         A : Integer := 3;
16984    Proc (A, A);                            begin
16985 end Block;                                    Proc (A, A);
16986                                            end Block;
16987
16988 Clear : for J in 1 .. 10 loop           Clear :
16989    A (J) := 0;                             for J in 1 .. 10 loop
16990 end loop Clear;                               A (J) := 0;
16991                                            end loop Clear;
16992 @end cartouche
16993 @end smallexample
16994 @end ifnottex
16995
16996 @noindent
16997 A further difference between GNAT style layout and compact layout is that
16998 GNAT style layout inserts empty lines as separation for
16999 compound statements, return statements and bodies.
17000
17001 Note that the layout specified by
17002 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
17003 for named block and loop statements overrides the layout defined by these
17004 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
17005 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
17006 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
17007
17008 @node Name Casing
17009 @subsection Name Casing
17010
17011 @noindent
17012 @command{gnatpp} always converts the usage occurrence of a (simple) name to
17013 the same casing as the corresponding defining identifier.
17014
17015 You control the casing for defining occurrences via the
17016 @option{^-n^/NAME_CASING^} switch.
17017 @ifclear vms
17018 With @option{-nD} (``as declared'', which is the default),
17019 @end ifclear
17020 @ifset vms
17021 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
17022 @end ifset
17023 defining occurrences appear exactly as in the source file
17024 where they are declared.
17025 The other ^values for this switch^options for this qualifier^ ---
17026 @option{^-nU^UPPER_CASE^},
17027 @option{^-nL^LOWER_CASE^},
17028 @option{^-nM^MIXED_CASE^} ---
17029 result in
17030 ^upper, lower, or mixed case, respectively^the corresponding casing^.
17031 If @command{gnatpp} changes the casing of a defining
17032 occurrence, it analogously changes the casing of all the
17033 usage occurrences of this name.
17034
17035 If the defining occurrence of a name is not in the source compilation unit
17036 currently being processed by @command{gnatpp}, the casing of each reference to
17037 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
17038 switch (subject to the dictionary file mechanism described below).
17039 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17040 had affected the
17041 casing for the defining occurrence of the name.
17042
17043 Some names may need to be spelled with casing conventions that are not
17044 covered by the upper-, lower-, and mixed-case transformations.
17045 You can arrange correct casing by placing such names in a
17046 @emph{dictionary file},
17047 and then supplying a @option{^-D^/DICTIONARY^} switch.
17048 The casing of names from dictionary files overrides
17049 any @option{^-n^/NAME_CASING^} switch.
17050
17051 To handle the casing of Ada predefined names and the names from GNAT libraries,
17052 @command{gnatpp} assumes a default dictionary file.
17053 The name of each predefined entity is spelled with the same casing as is used
17054 for the entity in the @cite{Ada Reference Manual}.
17055 The name of each entity in the GNAT libraries is spelled with the same casing
17056 as is used in the declaration of that entity.
17057
17058 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17059 default dictionary file.
17060 Instead, the casing for predefined and GNAT-defined names will be established
17061 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17062 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17063 will appear as just shown,
17064 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17065 To ensure that even such names are rendered in uppercase,
17066 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17067 (or else, less conveniently, place these names in upper case in a dictionary
17068 file).
17069
17070 A dictionary file is
17071 a plain text file; each line in this file can be either a blank line
17072 (containing only space characters and ASCII.HT characters), an Ada comment
17073 line, or the specification of exactly one @emph{casing schema}.
17074
17075 A casing schema is a string that has the following syntax:
17076
17077 @smallexample
17078 @cartouche
17079   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17080
17081   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17082 @end cartouche
17083 @end smallexample
17084
17085 @noindent
17086 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17087 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17088
17089 The casing schema string can be followed by white space and/or an Ada-style
17090 comment; any amount of white space is allowed before the string.
17091
17092 If a dictionary file is passed as
17093 @ifclear vms
17094 the value of a @option{-D@var{file}} switch
17095 @end ifclear
17096 @ifset vms
17097 an option to the @option{/DICTIONARY} qualifier
17098 @end ifset
17099 then for every
17100 simple name and every identifier, @command{gnatpp} checks if the dictionary
17101 defines the casing for the name or for some of its parts (the term ``subword''
17102 is used below to denote the part of a name which is delimited by ``_'' or by
17103 the beginning or end of the word and which does not contain any ``_'' inside):
17104
17105 @itemize @bullet
17106 @item
17107 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17108 the casing defined by the dictionary; no subwords are checked for this word
17109
17110 @item
17111 for every subword @command{gnatpp} checks if the dictionary contains the
17112 corresponding string of the form @code{*@var{simple_identifier}*},
17113 and if it does, the casing of this @var{simple_identifier} is used
17114 for this subword
17115
17116 @item
17117 if the whole name does not contain any ``_'' inside, and if for this name
17118 the dictionary contains two entries - one of the form @var{identifier},
17119 and another - of the form *@var{simple_identifier}*, then the first one
17120 is applied to define the casing of this name
17121
17122 @item
17123 if more than one dictionary file is passed as @command{gnatpp} switches, each
17124 dictionary adds new casing exceptions and overrides all the existing casing
17125 exceptions set by the previous dictionaries
17126
17127 @item
17128 when @command{gnatpp} checks if the word or subword is in the dictionary,
17129 this check is not case sensitive
17130 @end itemize
17131
17132 @noindent
17133 For example, suppose we have the following source to reformat:
17134
17135 @smallexample @c ada
17136 @cartouche
17137 procedure test is
17138    name1 : integer := 1;
17139    name4_name3_name2 : integer := 2;
17140    name2_name3_name4 : Boolean;
17141    name1_var : Float;
17142 begin
17143    name2_name3_name4 := name4_name3_name2 > name1;
17144 end;
17145 @end cartouche
17146 @end smallexample
17147
17148 @noindent
17149 And suppose we have two dictionaries:
17150
17151 @smallexample
17152 @cartouche
17153 @i{dict1:}
17154    NAME1
17155    *NaMe3*
17156    *Name1*
17157 @end cartouche
17158
17159 @cartouche
17160 @i{dict2:}
17161   *NAME3*
17162 @end cartouche
17163 @end smallexample
17164
17165 @noindent
17166 If @command{gnatpp} is called with the following switches:
17167
17168 @smallexample
17169 @ifclear vms
17170 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17171 @end ifclear
17172 @ifset vms
17173 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17174 @end ifset
17175 @end smallexample
17176
17177 @noindent
17178 then we will get the following name casing in the @command{gnatpp} output:
17179
17180 @smallexample @c ada
17181 @cartouche
17182 procedure Test is
17183    NAME1             : Integer := 1;
17184    Name4_NAME3_Name2 : Integer := 2;
17185    Name2_NAME3_Name4 : Boolean;
17186    Name1_Var         : Float;
17187 begin
17188    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17189 end Test;
17190 @end cartouche
17191 @end smallexample
17192
17193 @c *********************************
17194 @node The GNAT Metric Tool gnatmetric
17195 @chapter The GNAT Metric Tool @command{gnatmetric}
17196 @findex gnatmetric
17197 @cindex Metric tool
17198
17199 @noindent
17200 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17201 for computing various program metrics.
17202 It takes an Ada source file as input and generates a file containing the
17203 metrics data as output. Various switches control which
17204 metrics are computed and output.
17205
17206 @command{gnatmetric} generates and uses the ASIS
17207 tree for the input source and thus requires the input to be syntactically and
17208 semantically legal.
17209 If this condition is not met, @command{gnatmetric} will generate
17210 an error message; no metric information for this file will be
17211 computed and reported.
17212
17213 If the compilation unit contained in the input source depends semantically
17214 upon units in files located outside the current directory, you have to provide
17215 the source search path when invoking @command{gnatmetric}.
17216 If it depends semantically upon units that are contained
17217 in files with names that do not follow the GNAT file naming rules, you have to
17218 provide the configuration file describing the corresponding naming scheme (see
17219 the description of the @command{gnatmetric} switches below.)
17220 Alternatively, you may use a project file and invoke @command{gnatmetric}
17221 through the @command{gnat} driver.
17222
17223 The @command{gnatmetric} command has the form
17224
17225 @smallexample
17226 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17227 @c Expanding @ovar macro inline (explanation in macro def comments)
17228 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17229 @end smallexample
17230
17231 @noindent
17232 where
17233 @itemize @bullet
17234 @item
17235 @var{switches} specify the metrics to compute and define the destination for
17236 the output
17237
17238 @item
17239 Each @var{filename} is the name (including the extension) of a source
17240 file to process. ``Wildcards'' are allowed, and
17241 the file name may contain path information.
17242 If no @var{filename} is supplied, then the @var{switches} list must contain
17243 at least one
17244 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17245 Including both a @option{-files} switch and one or more
17246 @var{filename} arguments is permitted.
17247
17248 @item
17249 @samp{@var{gcc_switches}} is a list of switches for
17250 @command{gcc}. They will be passed on to all compiler invocations made by
17251 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17252 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17253 and use the @option{-gnatec} switch to set the configuration file.
17254 @end itemize
17255
17256 @menu
17257 * Switches for gnatmetric::
17258 @end menu
17259
17260 @node Switches for gnatmetric
17261 @section Switches for @command{gnatmetric}
17262
17263 @noindent
17264 The following subsections describe the various switches accepted by
17265 @command{gnatmetric}, organized by category.
17266
17267 @menu
17268 * Output Files Control::
17269 * Disable Metrics For Local Units::
17270 * Specifying a set of metrics to compute::
17271 * Other gnatmetric Switches::
17272 * Generate project-wide metrics::
17273 @end menu
17274
17275 @node Output Files Control
17276 @subsection Output File Control
17277 @cindex Output file control in @command{gnatmetric}
17278
17279 @noindent
17280 @command{gnatmetric} has two output formats. It can generate a
17281 textual (human-readable) form, and also XML. By default only textual
17282 output is generated.
17283
17284 When generating the output in textual form, @command{gnatmetric} creates
17285 for each Ada source file a corresponding text file
17286 containing the computed metrics, except for the case when the set of metrics
17287 specified by gnatmetric parameters consists only of metrics that are computed
17288 for the whole set of analyzed sources, but not for each Ada source.
17289 By default, this file is placed in the same directory as where the source
17290 file is located, and its name is obtained
17291 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17292 input file.
17293
17294 All the output information generated in XML format is placed in a single
17295 file. By default this file is placed in the current directory and has the
17296 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17297
17298 Some of the computed metrics are summed over the units passed to
17299 @command{gnatmetric}; for example, the total number of lines of code.
17300 By default this information is sent to @file{stdout}, but a file
17301 can be specified with the @option{-og} switch.
17302
17303 The following switches control the @command{gnatmetric} output:
17304
17305 @table @option
17306 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17307 @item ^-x^/XML^
17308 Generate the XML output
17309
17310 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17311 @item ^-xs^/XSD^
17312 Generate the XML output and the XML schema file that describes the structure
17313 of the XML metric report, this schema is assigned to the XML file. The schema
17314 file has the same name as the XML output file with @file{.xml} suffix replaced
17315 with @file{.xsd}
17316
17317 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17318 @item ^-nt^/NO_TEXT^
17319 Do not generate the output in text form (implies @option{^-x^/XML^})
17320
17321 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17322 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17323 Put text files with detailed metrics into @var{output_dir}
17324
17325 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17326 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17327 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17328 in the name of the output file.
17329
17330 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17331 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17332 Put global metrics into @var{file_name}
17333
17334 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17335 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17336 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17337
17338 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17339 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17340 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17341 output includes the name(s) of the Ada source file(s) from which the metrics
17342 are computed.  By default each name includes the absolute path. The
17343 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17344 to exclude all directory information from the file names that are output.)
17345
17346 @end table
17347
17348 @node Disable Metrics For Local Units
17349 @subsection Disable Metrics For Local Units
17350 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17351
17352 @noindent
17353 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17354 one compilation
17355 unit per one source file. It computes line metrics for the whole source
17356 file, and it also computes syntax
17357 and complexity metrics for the file's outermost unit.
17358
17359 By default, @command{gnatmetric} will also compute all metrics for certain
17360 kinds of locally declared program units:
17361
17362 @itemize @bullet
17363 @item
17364 subprogram (and generic subprogram) bodies;
17365
17366 @item
17367 package (and generic package) specs and bodies;
17368
17369 @item
17370 task object and type specifications and bodies;
17371
17372 @item
17373 protected object and type specifications and bodies.
17374 @end itemize
17375
17376 @noindent
17377 These kinds of entities will be referred to as
17378 @emph{eligible local program units}, or simply @emph{eligible local units},
17379 @cindex Eligible local unit (for @command{gnatmetric})
17380 in the discussion below.
17381
17382 Note that a subprogram declaration, generic instantiation,
17383 or renaming declaration only receives metrics
17384 computation when it appear as the outermost entity
17385 in a source file.
17386
17387 Suppression of metrics computation for eligible local units can be
17388 obtained via the following switch:
17389
17390 @table @option
17391 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17392 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17393 Do not compute detailed metrics for eligible local program units
17394
17395 @end table
17396
17397 @node Specifying a set of metrics to compute
17398 @subsection Specifying a set of metrics to compute
17399
17400 @noindent
17401 By default all the metrics are computed and reported. The switches
17402 described in this subsection allow you to control, on an individual
17403 basis, whether metrics are computed and
17404 reported. If at least one positive metric
17405 switch is specified (that is, a switch that defines that a given
17406 metric or set of metrics is to be computed), then only
17407 explicitly specified metrics are reported.
17408
17409 @menu
17410 * Line Metrics Control::
17411 * Syntax Metrics Control::
17412 * Complexity Metrics Control::
17413 * Object-Oriented Metrics Control::
17414 @end menu
17415
17416 @node Line Metrics Control
17417 @subsubsection Line Metrics Control
17418 @cindex Line metrics control in @command{gnatmetric}
17419
17420 @noindent
17421 For any (legal) source file, and for each of its
17422 eligible local program units, @command{gnatmetric} computes the following
17423 metrics:
17424
17425 @itemize @bullet
17426 @item
17427 the total number of lines;
17428
17429 @item
17430 the total number of code lines (i.e., non-blank lines that are not comments)
17431
17432 @item
17433 the number of comment lines
17434
17435 @item
17436 the number of code lines containing end-of-line comments;
17437
17438 @item
17439 the comment percentage: the ratio between the number of lines that contain
17440 comments and the number of all non-blank lines, expressed as a percentage;
17441
17442 @item
17443 the number of empty lines and lines containing only space characters and/or
17444 format effectors (blank lines)
17445
17446 @item
17447 the average number of code lines in subprogram bodies, task bodies, entry
17448 bodies and statement sequences in package bodies (this metric is only computed
17449 across the whole set of the analyzed units)
17450
17451 @end itemize
17452
17453 @noindent
17454 @command{gnatmetric} sums the values of the line metrics for all the
17455 files being processed and then generates the cumulative results. The tool
17456 also computes for all the files being processed the average number of code
17457 lines in bodies.
17458
17459 You can use the following switches to select the specific line metrics
17460 to be computed and reported.
17461
17462 @table @option
17463 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17464
17465 @ifclear vms
17466 @cindex @option{--no-lines@var{x}}
17467 @end ifclear
17468
17469 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17470 Report all the line metrics
17471
17472 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17473 Do not report any of line metrics
17474
17475 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17476 Report the number of all lines
17477
17478 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17479 Do not report the number of all lines
17480
17481 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17482 Report the number of code lines
17483
17484 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17485 Do not report the number of code lines
17486
17487 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17488 Report the number of comment lines
17489
17490 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17491 Do not report the number of comment lines
17492
17493 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17494 Report the number of code lines containing
17495 end-of-line comments
17496
17497 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17498 Do not report the number of code lines containing
17499 end-of-line comments
17500
17501 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17502 Report the comment percentage in the program text
17503
17504 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17505 Do not report the comment percentage in the program text
17506
17507 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17508 Report the number of blank lines
17509
17510 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17511 Do not report the number of blank lines
17512
17513 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17514 Report the average number of code lines in subprogram bodies, task bodies,
17515 entry bodies and statement sequences in package bodies. The metric is computed
17516 and reported for the whole set of processed Ada sources only.
17517
17518 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17519 Do not report the average number of code lines in subprogram bodies,
17520 task bodies, entry bodies and statement sequences in package bodies.
17521
17522 @end table
17523
17524 @node Syntax Metrics Control
17525 @subsubsection Syntax Metrics Control
17526 @cindex Syntax metrics control in @command{gnatmetric}
17527
17528 @noindent
17529 @command{gnatmetric} computes various syntactic metrics for the
17530 outermost unit and for each eligible local unit:
17531
17532 @table @emph
17533 @item LSLOC (``Logical Source Lines Of Code'')
17534 The total number of declarations and the total number of statements
17535
17536 @item Maximal static nesting level of inner program units
17537 According to
17538 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17539 package, a task unit, a protected unit, a
17540 protected entry, a generic unit, or an explicitly declared subprogram other
17541 than an enumeration literal.''
17542
17543 @item Maximal nesting level of composite syntactic constructs
17544 This corresponds to the notion of the
17545 maximum nesting level in the GNAT built-in style checks
17546 (@pxref{Style Checking})
17547 @end table
17548
17549 @noindent
17550 For the outermost unit in the file, @command{gnatmetric} additionally computes
17551 the following metrics:
17552
17553 @table @emph
17554 @item Public subprograms
17555 This metric is computed for package specs. It is the
17556 number of subprograms and generic subprograms declared in the visible
17557 part (including the visible part of nested packages, protected objects, and
17558 protected types).
17559
17560 @item All subprograms
17561 This metric is computed for bodies and subunits. The
17562 metric is equal to a total number of subprogram bodies in the compilation
17563 unit.
17564 Neither generic instantiations nor renamings-as-a-body nor body stubs
17565 are counted. Any subprogram body is counted, independently of its nesting
17566 level and enclosing constructs. Generic bodies and bodies of protected
17567 subprograms are counted in the same way as ``usual'' subprogram bodies.
17568
17569 @item Public types
17570 This metric is computed for package specs and
17571 generic package declarations. It is the total number of types
17572 that can be referenced from outside this compilation unit, plus the
17573 number of types from all the visible parts of all the visible generic
17574 packages. Generic formal types are not counted.  Only types, not subtypes,
17575 are included.
17576
17577 @noindent
17578 Along with the total number of public types, the following
17579 types are counted and reported separately:
17580
17581 @itemize @bullet
17582 @item
17583 Abstract types
17584
17585 @item
17586 Root tagged types (abstract, non-abstract, private, non-private). Type
17587 extensions are @emph{not} counted
17588
17589 @item
17590 Private types (including private extensions)
17591
17592 @item
17593 Task types
17594
17595 @item
17596 Protected types
17597
17598 @end itemize
17599
17600 @item All types
17601 This metric is computed for any compilation unit. It is equal to the total
17602 number of the declarations of different types given in the compilation unit.
17603 The private and the corresponding full type declaration are counted as one
17604 type declaration. Incomplete type declarations and generic formal types
17605 are not counted.
17606 No distinction is made among different kinds of types (abstract,
17607 private etc.); the total number of types is computed and reported.
17608
17609 @end table
17610
17611 @noindent
17612 By default, all the syntax metrics are computed and reported. You can use the
17613 following switches to select specific syntax metrics.
17614
17615 @table @option
17616
17617 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17618
17619 @ifclear vms
17620 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17621 @end ifclear
17622
17623 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17624 Report all the syntax metrics
17625
17626 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17627 Do not report any of syntax metrics
17628
17629 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17630 Report the total number of declarations
17631
17632 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17633 Do not report the total number of declarations
17634
17635 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17636 Report the total number of statements
17637
17638 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17639 Do not report the total number of statements
17640
17641 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17642 Report the number of public subprograms in a compilation unit
17643
17644 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17645 Do not report the number of public subprograms in a compilation unit
17646
17647 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17648 Report the number of all the subprograms in a compilation unit
17649
17650 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17651 Do not report the number of all the subprograms in a compilation unit
17652
17653 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17654 Report the number of public types in a compilation unit
17655
17656 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17657 Do not report the number of public types in a compilation unit
17658
17659 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17660 Report the number of all the types in a compilation unit
17661
17662 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17663 Do not report the number of all the types in a compilation unit
17664
17665 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17666 Report the maximal program unit nesting level
17667
17668 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17669 Do not report the maximal program unit nesting level
17670
17671 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17672 Report the maximal construct nesting level
17673
17674 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17675 Do not report the maximal construct nesting level
17676
17677 @end table
17678
17679 @node Complexity Metrics Control
17680 @subsubsection Complexity Metrics Control
17681 @cindex Complexity metrics control in @command{gnatmetric}
17682
17683 @noindent
17684 For a program unit that is an executable body (a subprogram body (including
17685 generic bodies), task body, entry body or a package body containing
17686 its own statement sequence) @command{gnatmetric} computes the following
17687 complexity metrics:
17688
17689 @itemize @bullet
17690 @item
17691 McCabe cyclomatic complexity;
17692
17693 @item
17694 McCabe essential complexity;
17695
17696 @item
17697 maximal loop nesting level
17698
17699 @end itemize
17700
17701 @noindent
17702 The McCabe complexity metrics are defined
17703 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17704
17705 According to McCabe, both control statements and short-circuit control forms
17706 should be taken into account when computing cyclomatic complexity. For each
17707 body, we compute three metric values:
17708
17709 @itemize @bullet
17710 @item
17711 the complexity introduced by control
17712 statements only, without taking into account short-circuit forms,
17713
17714 @item
17715 the complexity introduced by short-circuit control forms only, and
17716
17717 @item
17718 the total
17719 cyclomatic complexity, which is the sum of these two values.
17720 @end itemize
17721
17722 @noindent
17723 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17724 the code in the exception handlers and in all the nested program units.
17725
17726 By default, all the complexity metrics are computed and reported.
17727 For more fine-grained control you can use
17728 the following switches:
17729
17730 @table @option
17731 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17732
17733 @ifclear vms
17734 @cindex @option{--no-complexity@var{x}}
17735 @end ifclear
17736
17737 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17738 Report all the complexity metrics
17739
17740 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17741 Do not report any of complexity metrics
17742
17743 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17744 Report the McCabe Cyclomatic Complexity
17745
17746 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17747 Do not report the McCabe Cyclomatic Complexity
17748
17749 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17750 Report the Essential Complexity
17751
17752 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17753 Do not report the Essential Complexity
17754
17755 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17756 Report maximal loop nesting level
17757
17758 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17759 Do not report maximal loop nesting level
17760
17761 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17762 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17763 task bodies, entry bodies and statement sequences in package bodies.
17764 The metric is computed and reported for whole set of processed Ada sources
17765 only.
17766
17767 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17768 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17769 bodies, task bodies, entry bodies and statement sequences in package bodies
17770
17771 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17772 @item ^-ne^/NO_EXITS_AS_GOTOS^
17773 Do not consider @code{exit} statements as @code{goto}s when
17774 computing Essential Complexity
17775
17776 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17777 Report the extra exit points for subprogram bodies. As an exit point, this
17778 metric counts @code{return} statements and raise statements in case when the
17779 raised exception is not handled in the same body. In case of a function this
17780 metric subtracts 1 from the number of exit points, because a function body
17781 must contain at least one @code{return} statement.
17782
17783 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17784 Do not report the extra exit points for subprogram bodies
17785 @end table
17786
17787
17788 @node Object-Oriented Metrics Control
17789 @subsubsection Object-Oriented Metrics Control
17790 @cindex Object-Oriented metrics control in @command{gnatmetric}
17791
17792 @noindent
17793 @cindex Coupling metrics (in in @command{gnatmetric})
17794 Coupling metrics are object-oriented metrics that measure the
17795 dependencies between a given class (or a group of classes) and the
17796 ``external world'' (that is, the other classes in the program). In this
17797 subsection the term ``class'' is used in its
17798 traditional object-oriented programming sense
17799 (an instantiable module that contains data and/or method members).
17800 A @emph{category} (of classes)
17801 is a group of closely related classes that are reused and/or
17802 modified together.
17803
17804 A class @code{K}'s @emph{efferent coupling} is the number of classes
17805 that @code{K} depends upon.
17806 A category's efferent coupling is the number of classes outside the
17807 category that the classes inside the category depend upon.
17808
17809 A class @code{K}'s @emph{afferent coupling} is the number of classes
17810 that depend upon @code{K}.
17811 A category's afferent coupling is the number of classes outside the
17812 category that depend on classes belonging to the category.
17813
17814 Ada's implementation of the object-oriented paradigm does not use the
17815 traditional class notion, so the definition of the coupling
17816 metrics for Ada maps the class and class category notions
17817 onto Ada constructs.
17818
17819 For the coupling metrics, several kinds of modules -- a library package,
17820 a library generic package, and a library generic package instantiation --
17821 that define a tagged type or an interface type are
17822 considered to be a class. A category consists of a library package (or
17823 a library generic package) that defines a tagged or an interface type,
17824 together with all its descendant (generic) packages that define tagged
17825 or interface types. For any package counted as a class,
17826 its body and subunits (if any) are considered
17827 together with its spec when counting the dependencies, and coupling
17828 metrics are reported for spec units only. For dependencies
17829 between classes, the Ada semantic dependencies are considered.
17830 For coupling metrics, only dependencies on units that are considered as
17831 classes, are considered.
17832
17833 When computing coupling metrics, @command{gnatmetric} counts only
17834 dependencies between units that are arguments of the gnatmetric call.
17835 Coupling metrics are program-wide (or project-wide) metrics, so to
17836 get a valid result, you should call @command{gnatmetric} for
17837 the whole set of sources that make up your program. It can be done
17838 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17839 option (see See @ref{The GNAT Driver and Project Files} for details.
17840
17841 By default, all the coupling metrics are disabled. You can use the following
17842 switches to specify the coupling metrics to be computed and reported:
17843
17844 @table @option
17845
17846 @ifclear vms
17847 @cindex @option{--package@var{x}} (@command{gnatmetric})
17848 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17849 @cindex @option{--category@var{x}} (@command{gnatmetric})
17850 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17851 @end ifclear
17852
17853 @ifset vms
17854 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17855 @end ifset
17856
17857 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17858 Report all the coupling metrics
17859
17860 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17861 Do not report any of  metrics
17862
17863 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17864 Report package efferent coupling
17865
17866 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17867 Do not report package efferent coupling
17868
17869 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17870 Report package afferent coupling
17871
17872 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17873 Do not report package afferent coupling
17874
17875 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17876 Report category efferent coupling
17877
17878 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17879 Do not report category efferent coupling
17880
17881 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17882 Report category afferent coupling
17883
17884 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17885 Do not report category afferent coupling
17886
17887 @end table
17888
17889 @node Other gnatmetric Switches
17890 @subsection Other @code{gnatmetric} Switches
17891
17892 @noindent
17893 Additional @command{gnatmetric} switches are as follows:
17894
17895 @table @option
17896 @item ^-files @var{filename}^/FILES=@var{filename}^
17897 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17898 Take the argument source files from the specified file. This file should be an
17899 ordinary text file containing file names separated by spaces or
17900 line breaks. You can use this switch more than once in the same call to
17901 @command{gnatmetric}. You also can combine this switch with
17902 an explicit list of files.
17903
17904 @item ^-v^/VERBOSE^
17905 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17906 Verbose mode;
17907 @command{gnatmetric} generates version information and then
17908 a trace of sources being processed.
17909
17910 @item ^-dv^/DEBUG_OUTPUT^
17911 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17912 Debug mode;
17913 @command{gnatmetric} generates various messages useful to understand what
17914 happens during the metrics computation
17915
17916 @item ^-q^/QUIET^
17917 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17918 Quiet mode.
17919 @end table
17920
17921 @node Generate project-wide metrics
17922 @subsection Generate project-wide metrics
17923
17924 In order to compute metrics on all units of a given project, you can use
17925 the @command{gnat} driver along with the @option{-P} option:
17926 @smallexample
17927    gnat metric -Pproj
17928 @end smallexample
17929
17930 @noindent
17931 If the project @code{proj} depends upon other projects, you can compute
17932 the metrics on the project closure using the @option{-U} option:
17933 @smallexample
17934    gnat metric -Pproj -U
17935 @end smallexample
17936
17937 @noindent
17938 Finally, if not all the units are relevant to a particular main
17939 program in the project closure, you can generate metrics for the set
17940 of units needed to create a given main program (unit closure) using
17941 the @option{-U} option followed by the name of the main unit:
17942 @smallexample
17943    gnat metric -Pproj -U main
17944 @end smallexample
17945
17946
17947 @c ***********************************
17948 @node File Name Krunching Using gnatkr
17949 @chapter File Name Krunching Using @code{gnatkr}
17950 @findex gnatkr
17951
17952 @noindent
17953 This chapter discusses the method used by the compiler to shorten
17954 the default file names chosen for Ada units so that they do not
17955 exceed the maximum length permitted. It also describes the
17956 @code{gnatkr} utility that can be used to determine the result of
17957 applying this shortening.
17958 @menu
17959 * About gnatkr::
17960 * Using gnatkr::
17961 * Krunching Method::
17962 * Examples of gnatkr Usage::
17963 @end menu
17964
17965 @node About gnatkr
17966 @section About @code{gnatkr}
17967
17968 @noindent
17969 The default file naming rule in GNAT
17970 is that the file name must be derived from
17971 the unit name. The exact default rule is as follows:
17972 @itemize @bullet
17973 @item
17974 Take the unit name and replace all dots by hyphens.
17975 @item
17976 If such a replacement occurs in the
17977 second character position of a name, and the first character is
17978 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17979 then replace the dot by the character
17980 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17981 instead of a minus.
17982 @end itemize
17983 The reason for this exception is to avoid clashes
17984 with the standard names for children of System, Ada, Interfaces,
17985 and GNAT, which use the prefixes
17986 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17987 respectively.
17988
17989 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17990 switch of the compiler activates a ``krunching''
17991 circuit that limits file names to nn characters (where nn is a decimal
17992 integer). For example, using OpenVMS,
17993 where the maximum file name length is
17994 39, the value of nn is usually set to 39, but if you want to generate
17995 a set of files that would be usable if ported to a system with some
17996 different maximum file length, then a different value can be specified.
17997 The default value of 39 for OpenVMS need not be specified.
17998
17999 The @code{gnatkr} utility can be used to determine the krunched name for
18000 a given file, when krunched to a specified maximum length.
18001
18002 @node Using gnatkr
18003 @section Using @code{gnatkr}
18004
18005 @noindent
18006 The @code{gnatkr} command has the form
18007
18008 @ifclear vms
18009 @smallexample
18010 @c $ gnatkr @var{name} @ovar{length}
18011 @c Expanding @ovar macro inline (explanation in macro def comments)
18012 $ gnatkr @var{name} @r{[}@var{length}@r{]}
18013 @end smallexample
18014 @end ifclear
18015
18016 @ifset vms
18017 @smallexample
18018 $ gnatkr @var{name} /COUNT=nn
18019 @end smallexample
18020 @end ifset
18021
18022 @noindent
18023 @var{name} is the uncrunched file name, derived from the name of the unit
18024 in the standard manner described in the previous section (i.e., in particular
18025 all dots are replaced by hyphens). The file name may or may not have an
18026 extension (defined as a suffix of the form period followed by arbitrary
18027 characters other than period). If an extension is present then it will
18028 be preserved in the output. For example, when krunching @file{hellofile.ads}
18029 to eight characters, the result will be hellofil.ads.
18030
18031 Note: for compatibility with previous versions of @code{gnatkr} dots may
18032 appear in the name instead of hyphens, but the last dot will always be
18033 taken as the start of an extension. So if @code{gnatkr} is given an argument
18034 such as @file{Hello.World.adb} it will be treated exactly as if the first
18035 period had been a hyphen, and for example krunching to eight characters
18036 gives the result @file{hellworl.adb}.
18037
18038 Note that the result is always all lower case (except on OpenVMS where it is
18039 all upper case). Characters of the other case are folded as required.
18040
18041 @var{length} represents the length of the krunched name. The default
18042 when no argument is given is ^8^39^ characters. A length of zero stands for
18043 unlimited, in other words do not chop except for system files where the
18044 implied crunching length is always eight characters.
18045
18046 @noindent
18047 The output is the krunched name. The output has an extension only if the
18048 original argument was a file name with an extension.
18049
18050 @node Krunching Method
18051 @section Krunching Method
18052
18053 @noindent
18054 The initial file name is determined by the name of the unit that the file
18055 contains. The name is formed by taking the full expanded name of the
18056 unit and replacing the separating dots with hyphens and
18057 using ^lowercase^uppercase^
18058 for all letters, except that a hyphen in the second character position is
18059 replaced by a ^tilde^dollar sign^ if the first character is
18060 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18061 The extension is @code{.ads} for a
18062 spec and @code{.adb} for a body.
18063 Krunching does not affect the extension, but the file name is shortened to
18064 the specified length by following these rules:
18065
18066 @itemize @bullet
18067 @item
18068 The name is divided into segments separated by hyphens, tildes or
18069 underscores and all hyphens, tildes, and underscores are
18070 eliminated. If this leaves the name short enough, we are done.
18071
18072 @item
18073 If the name is too long, the longest segment is located (left-most
18074 if there are two of equal length), and shortened by dropping
18075 its last character. This is repeated until the name is short enough.
18076
18077 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18078 to fit the name into 8 characters as required by some operating systems.
18079
18080 @smallexample
18081 our-strings-wide_fixed 22
18082 our strings wide fixed 19
18083 our string  wide fixed 18
18084 our strin   wide fixed 17
18085 our stri    wide fixed 16
18086 our stri    wide fixe  15
18087 our str     wide fixe  14
18088 our str     wid  fixe  13
18089 our str     wid  fix   12
18090 ou  str     wid  fix   11
18091 ou  st      wid  fix   10
18092 ou  st      wi   fix   9
18093 ou  st      wi   fi    8
18094 Final file name: oustwifi.adb
18095 @end smallexample
18096
18097 @item
18098 The file names for all predefined units are always krunched to eight
18099 characters. The krunching of these predefined units uses the following
18100 special prefix replacements:
18101
18102 @table @file
18103 @item ada-
18104 replaced by @file{^a^A^-}
18105
18106 @item gnat-
18107 replaced by @file{^g^G^-}
18108
18109 @item interfaces-
18110 replaced by @file{^i^I^-}
18111
18112 @item system-
18113 replaced by @file{^s^S^-}
18114 @end table
18115
18116 These system files have a hyphen in the second character position. That
18117 is why normal user files replace such a character with a
18118 ^tilde^dollar sign^, to
18119 avoid confusion with system file names.
18120
18121 As an example of this special rule, consider
18122 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18123
18124 @smallexample
18125 ada-strings-wide_fixed 22
18126 a-  strings wide fixed 18
18127 a-  string  wide fixed 17
18128 a-  strin   wide fixed 16
18129 a-  stri    wide fixed 15
18130 a-  stri    wide fixe  14
18131 a-  str     wide fixe  13
18132 a-  str     wid  fixe  12
18133 a-  str     wid  fix   11
18134 a-  st      wid  fix   10
18135 a-  st      wi   fix   9
18136 a-  st      wi   fi    8
18137 Final file name: a-stwifi.adb
18138 @end smallexample
18139 @end itemize
18140
18141 Of course no file shortening algorithm can guarantee uniqueness over all
18142 possible unit names, and if file name krunching is used then it is your
18143 responsibility to ensure that no name clashes occur. The utility
18144 program @code{gnatkr} is supplied for conveniently determining the
18145 krunched name of a file.
18146
18147 @node Examples of gnatkr Usage
18148 @section Examples of @code{gnatkr} Usage
18149
18150 @smallexample
18151 @iftex
18152 @leftskip=0cm
18153 @end iftex
18154 @ifclear vms
18155 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18156 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18157 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18158 $ gnatkr grandparent-parent-child     --> grparchi
18159 @end ifclear
18160 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18161 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18162 @end smallexample
18163
18164 @node Preprocessing Using gnatprep
18165 @chapter Preprocessing Using @code{gnatprep}
18166 @findex gnatprep
18167
18168 @noindent
18169 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18170 preprocessing.
18171 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18172 special GNAT features.
18173 For further discussion of conditional compilation in general, see
18174 @ref{Conditional Compilation}.
18175
18176 @menu
18177 * Preprocessing Symbols::
18178 * Using gnatprep::
18179 * Switches for gnatprep::
18180 * Form of Definitions File::
18181 * Form of Input Text for gnatprep::
18182 @end menu
18183
18184 @node Preprocessing Symbols
18185 @section Preprocessing Symbols
18186
18187 @noindent
18188 Preprocessing symbols are defined in definition files and referred to in
18189 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18190 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18191 all characters need to be in the ASCII set (no accented letters).
18192
18193 @node Using gnatprep
18194 @section Using @code{gnatprep}
18195
18196 @noindent
18197 To call @code{gnatprep} use
18198
18199 @smallexample
18200 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18201 @c Expanding @ovar macro inline (explanation in macro def comments)
18202 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
18203 @end smallexample
18204
18205 @noindent
18206 where
18207 @table @var
18208 @item switches
18209 is an optional sequence of switches as described in the next section.
18210
18211 @item infile
18212 is the full name of the input file, which is an Ada source
18213 file containing preprocessor directives.
18214
18215 @item outfile
18216 is the full name of the output file, which is an Ada source
18217 in standard Ada form. When used with GNAT, this file name will
18218 normally have an ads or adb suffix.
18219
18220 @item deffile
18221 is the full name of a text file containing definitions of
18222 preprocessing symbols to be referenced by the preprocessor. This argument is
18223 optional, and can be replaced by the use of the @option{-D} switch.
18224
18225 @end table
18226
18227 @node Switches for gnatprep
18228 @section Switches for @code{gnatprep}
18229
18230 @table @option
18231 @c !sort!
18232
18233 @item ^-b^/BLANK_LINES^
18234 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18235 Causes both preprocessor lines and the lines deleted by
18236 preprocessing to be replaced by blank lines in the output source file,
18237 preserving line numbers in the output file.
18238
18239 @item ^-c^/COMMENTS^
18240 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18241 Causes both preprocessor lines and the lines deleted
18242 by preprocessing to be retained in the output source as comments marked
18243 with the special string @code{"--! "}. This option will result in line numbers
18244 being preserved in the output file.
18245
18246 @item ^-C^/REPLACE_IN_COMMENTS^
18247 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18248 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18249 If this option is specified, then comments are scanned and any $symbol
18250 substitutions performed as in program text. This is particularly useful
18251 when structured comments are used (e.g., when writing programs in the
18252 SPARK dialect of Ada). Note that this switch is not available when
18253 doing integrated preprocessing (it would be useless in this context
18254 since comments are ignored by the compiler in any case).
18255
18256 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18257 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18258 Defines a new preprocessing symbol, associated with value. If no value is given
18259 on the command line, then symbol is considered to be @code{True}. This switch
18260 can be used in place of a definition file.
18261
18262 @ifset vms
18263 @item /REMOVE
18264 @cindex @option{/REMOVE} (@command{gnatprep})
18265 This is the default setting which causes lines deleted by preprocessing
18266 to be entirely removed from the output file.
18267 @end ifset
18268
18269 @item ^-r^/REFERENCE^
18270 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18271 Causes a @code{Source_Reference} pragma to be generated that
18272 references the original input file, so that error messages will use
18273 the file name of this original file. The use of this switch implies
18274 that preprocessor lines are not to be removed from the file, so its
18275 use will force @option{^-b^/BLANK_LINES^} mode if
18276 @option{^-c^/COMMENTS^}
18277 has not been specified explicitly.
18278
18279 Note that if the file to be preprocessed contains multiple units, then
18280 it will be necessary to @code{gnatchop} the output file from
18281 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18282 in the preprocessed file, it will be respected by
18283 @code{gnatchop ^-r^/REFERENCE^}
18284 so that the final chopped files will correctly refer to the original
18285 input source file for @code{gnatprep}.
18286
18287 @item ^-s^/SYMBOLS^
18288 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18289 Causes a sorted list of symbol names and values to be
18290 listed on the standard output file.
18291
18292 @item ^-u^/UNDEFINED^
18293 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18294 Causes undefined symbols to be treated as having the value FALSE in the context
18295 of a preprocessor test. In the absence of this option, an undefined symbol in
18296 a @code{#if} or @code{#elsif} test will be treated as an error.
18297
18298 @end table
18299
18300 @ifclear vms
18301 @noindent
18302 Note: if neither @option{-b} nor @option{-c} is present,
18303 then preprocessor lines and
18304 deleted lines are completely removed from the output, unless -r is
18305 specified, in which case -b is assumed.
18306 @end ifclear
18307
18308 @node Form of Definitions File
18309 @section Form of Definitions File
18310
18311 @noindent
18312 The definitions file contains lines of the form
18313
18314 @smallexample
18315 symbol := value
18316 @end smallexample
18317
18318 @noindent
18319 where symbol is a preprocessing symbol, and value is one of the following:
18320
18321 @itemize @bullet
18322 @item
18323 Empty, corresponding to a null substitution
18324 @item
18325 A string literal using normal Ada syntax
18326 @item
18327 Any sequence of characters from the set
18328 (letters, digits, period, underline).
18329 @end itemize
18330
18331 @noindent
18332 Comment lines may also appear in the definitions file, starting with
18333 the usual @code{--},
18334 and comments may be added to the definitions lines.
18335
18336 @node Form of Input Text for gnatprep
18337 @section Form of Input Text for @code{gnatprep}
18338
18339 @noindent
18340 The input text may contain preprocessor conditional inclusion lines,
18341 as well as general symbol substitution sequences.
18342
18343 The preprocessor conditional inclusion commands have the form
18344
18345 @smallexample
18346 @group
18347 @cartouche
18348 #if @i{expression} @r{[}then@r{]}
18349    lines
18350 #elsif @i{expression} @r{[}then@r{]}
18351    lines
18352 #elsif @i{expression} @r{[}then@r{]}
18353    lines
18354 @dots{}
18355 #else
18356    lines
18357 #end if;
18358 @end cartouche
18359 @end group
18360 @end smallexample
18361
18362 @noindent
18363 In this example, @i{expression} is defined by the following grammar:
18364 @smallexample
18365 @i{expression} ::=  <symbol>
18366 @i{expression} ::=  <symbol> = "<value>"
18367 @i{expression} ::=  <symbol> = <symbol>
18368 @i{expression} ::=  <symbol> 'Defined
18369 @i{expression} ::=  not @i{expression}
18370 @i{expression} ::=  @i{expression} and @i{expression}
18371 @i{expression} ::=  @i{expression} or @i{expression}
18372 @i{expression} ::=  @i{expression} and then @i{expression}
18373 @i{expression} ::=  @i{expression} or else @i{expression}
18374 @i{expression} ::=  ( @i{expression} )
18375 @end smallexample
18376
18377 The following restriction exists: it is not allowed to have "and" or "or"
18378 following "not" in the same expression without parentheses. For example, this
18379 is not allowed:
18380
18381 @smallexample
18382    not X or Y
18383 @end smallexample
18384
18385 This should be one of the following:
18386
18387 @smallexample
18388    (not X) or Y
18389    not (X or Y)
18390 @end smallexample
18391
18392 @noindent
18393 For the first test (@i{expression} ::= <symbol>) the symbol must have
18394 either the value true or false, that is to say the right-hand of the
18395 symbol definition must be one of the (case-insensitive) literals
18396 @code{True} or @code{False}. If the value is true, then the
18397 corresponding lines are included, and if the value is false, they are
18398 excluded.
18399
18400 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18401 the symbol has been defined in the definition file or by a @option{-D}
18402 switch on the command line. Otherwise, the test is false.
18403
18404 The equality tests are case insensitive, as are all the preprocessor lines.
18405
18406 If the symbol referenced is not defined in the symbol definitions file,
18407 then the effect depends on whether or not switch @option{-u}
18408 is specified. If so, then the symbol is treated as if it had the value
18409 false and the test fails. If this switch is not specified, then
18410 it is an error to reference an undefined symbol. It is also an error to
18411 reference a symbol that is defined with a value other than @code{True}
18412 or @code{False}.
18413
18414 The use of the @code{not} operator inverts the sense of this logical test.
18415 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18416 operators, without parentheses. For example, "if not X or Y then" is not
18417 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18418
18419 The @code{then} keyword is optional as shown
18420
18421 The @code{#} must be the first non-blank character on a line, but
18422 otherwise the format is free form. Spaces or tabs may appear between
18423 the @code{#} and the keyword. The keywords and the symbols are case
18424 insensitive as in normal Ada code. Comments may be used on a
18425 preprocessor line, but other than that, no other tokens may appear on a
18426 preprocessor line. Any number of @code{elsif} clauses can be present,
18427 including none at all. The @code{else} is optional, as in Ada.
18428
18429 The @code{#} marking the start of a preprocessor line must be the first
18430 non-blank character on the line, i.e., it must be preceded only by
18431 spaces or horizontal tabs.
18432
18433 Symbol substitution outside of preprocessor lines is obtained by using
18434 the sequence
18435
18436 @smallexample
18437 $symbol
18438 @end smallexample
18439
18440 @noindent
18441 anywhere within a source line, except in a comment or within a
18442 string literal. The identifier
18443 following the @code{$} must match one of the symbols defined in the symbol
18444 definition file, and the result is to substitute the value of the
18445 symbol in place of @code{$symbol} in the output file.
18446
18447 Note that although the substitution of strings within a string literal
18448 is not possible, it is possible to have a symbol whose defined value is
18449 a string literal. So instead of setting XYZ to @code{hello} and writing:
18450
18451 @smallexample
18452 Header : String := "$XYZ";
18453 @end smallexample
18454
18455 @noindent
18456 you should set XYZ to @code{"hello"} and write:
18457
18458 @smallexample
18459 Header : String := $XYZ;
18460 @end smallexample
18461
18462 @noindent
18463 and then the substitution will occur as desired.
18464
18465 @ifset vms
18466 @node The GNAT Run-Time Library Builder gnatlbr
18467 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18468 @findex gnatlbr
18469 @cindex Library builder
18470
18471 @noindent
18472 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18473 supplied configuration pragmas.
18474
18475 @menu
18476 * Running gnatlbr::
18477 * Switches for gnatlbr::
18478 * Examples of gnatlbr Usage::
18479 @end menu
18480
18481 @node Running gnatlbr
18482 @section Running @code{gnatlbr}
18483
18484 @noindent
18485 The @code{gnatlbr} command has the form
18486
18487 @smallexample
18488 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18489 @end smallexample
18490
18491 @node Switches for gnatlbr
18492 @section Switches for @code{gnatlbr}
18493
18494 @noindent
18495 @code{gnatlbr} recognizes the following switches:
18496
18497 @table @option
18498 @c !sort!
18499 @item /CREATE=directory
18500 @cindex @code{/CREATE} (@code{gnatlbr})
18501 Create the new run-time library in the specified directory.
18502
18503 @item /SET=directory
18504 @cindex @code{/SET} (@code{gnatlbr})
18505 Make the library in the specified directory the current run-time library.
18506
18507 @item /DELETE=directory
18508 @cindex @code{/DELETE} (@code{gnatlbr})
18509 Delete the run-time library in the specified directory.
18510
18511 @item /CONFIG=file
18512 @cindex @code{/CONFIG} (@code{gnatlbr})
18513 With /CREATE: Use the configuration pragmas in the specified file when
18514 building the library.
18515
18516 With /SET: Use the configuration pragmas in the specified file when
18517 compiling.
18518
18519 @end table
18520
18521 @node Examples of gnatlbr Usage
18522 @section Example of @code{gnatlbr} Usage
18523
18524 @smallexample
18525 Contents of VAXFLOAT.ADC:
18526 pragma Float_Representation (VAX_Float);
18527
18528 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18529
18530 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18531
18532 @end smallexample
18533 @end ifset
18534
18535 @node The GNAT Library Browser gnatls
18536 @chapter The GNAT Library Browser @code{gnatls}
18537 @findex gnatls
18538 @cindex Library browser
18539
18540 @noindent
18541 @code{gnatls} is a tool that outputs information about compiled
18542 units. It gives the relationship between objects, unit names and source
18543 files. It can also be used to check the source dependencies of a unit
18544 as well as various characteristics.
18545
18546 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18547 driver (see @ref{The GNAT Driver and Project Files}).
18548
18549 @menu
18550 * Running gnatls::
18551 * Switches for gnatls::
18552 * Examples of gnatls Usage::
18553 @end menu
18554
18555 @node Running gnatls
18556 @section Running @code{gnatls}
18557
18558 @noindent
18559 The @code{gnatls} command has the form
18560
18561 @smallexample
18562 $ gnatls switches @var{object_or_ali_file}
18563 @end smallexample
18564
18565 @noindent
18566 The main argument is the list of object or @file{ali} files
18567 (@pxref{The Ada Library Information Files})
18568 for which information is requested.
18569
18570 In normal mode, without additional option, @code{gnatls} produces a
18571 four-column listing. Each line represents information for a specific
18572 object. The first column gives the full path of the object, the second
18573 column gives the name of the principal unit in this object, the third
18574 column gives the status of the source and the fourth column gives the
18575 full path of the source representing this unit.
18576 Here is a simple example of use:
18577
18578 @smallexample
18579 $ gnatls *.o
18580 ^./^[]^demo1.o            demo1            DIF demo1.adb
18581 ^./^[]^demo2.o            demo2             OK demo2.adb
18582 ^./^[]^hello.o            h1                OK hello.adb
18583 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18584 ^./^[]^instr.o            instr             OK instr.adb
18585 ^./^[]^tef.o              tef              DIF tef.adb
18586 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18587 ^./^[]^tgef.o             tgef             DIF tgef.adb
18588 @end smallexample
18589
18590 @noindent
18591 The first line can be interpreted as follows: the main unit which is
18592 contained in
18593 object file @file{demo1.o} is demo1, whose main source is in
18594 @file{demo1.adb}. Furthermore, the version of the source used for the
18595 compilation of demo1 has been modified (DIF). Each source file has a status
18596 qualifier which can be:
18597
18598 @table @code
18599 @item OK (unchanged)
18600 The version of the source file used for the compilation of the
18601 specified unit corresponds exactly to the actual source file.
18602
18603 @item MOK (slightly modified)
18604 The version of the source file used for the compilation of the
18605 specified unit differs from the actual source file but not enough to
18606 require recompilation. If you use gnatmake with the qualifier
18607 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18608 MOK will not be recompiled.
18609
18610 @item DIF (modified)
18611 No version of the source found on the path corresponds to the source
18612 used to build this object.
18613
18614 @item ??? (file not found)
18615 No source file was found for this unit.
18616
18617 @item HID (hidden,  unchanged version not first on PATH)
18618 The version of the source that corresponds exactly to the source used
18619 for compilation has been found on the path but it is hidden by another
18620 version of the same source that has been modified.
18621
18622 @end table
18623
18624 @node Switches for gnatls
18625 @section Switches for @code{gnatls}
18626
18627 @noindent
18628 @code{gnatls} recognizes the following switches:
18629
18630 @table @option
18631 @c !sort!
18632 @cindex @option{--version} @command{gnatls}
18633 Display Copyright and version, then exit disregarding all other options.
18634
18635 @item --help
18636 @cindex @option{--help} @command{gnatls}
18637 If @option{--version} was not used, display usage, then exit disregarding
18638 all other options.
18639
18640 @item ^-a^/ALL_UNITS^
18641 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18642 Consider all units, including those of the predefined Ada library.
18643 Especially useful with @option{^-d^/DEPENDENCIES^}.
18644
18645 @item ^-d^/DEPENDENCIES^
18646 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18647 List sources from which specified units depend on.
18648
18649 @item ^-h^/OUTPUT=OPTIONS^
18650 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18651 Output the list of options.
18652
18653 @item ^-o^/OUTPUT=OBJECTS^
18654 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18655 Only output information about object files.
18656
18657 @item ^-s^/OUTPUT=SOURCES^
18658 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18659 Only output information about source files.
18660
18661 @item ^-u^/OUTPUT=UNITS^
18662 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18663 Only output information about compilation units.
18664
18665 @item ^-files^/FILES^=@var{file}
18666 @cindex @option{^-files^/FILES^} (@code{gnatls})
18667 Take as arguments the files listed in text file @var{file}.
18668 Text file @var{file} may contain empty lines that are ignored.
18669 Each nonempty line should contain the name of an existing file.
18670 Several such switches may be specified simultaneously.
18671
18672 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18673 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18674 @itemx ^-I^/SEARCH=^@var{dir}
18675 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18676 @itemx -nostdinc
18677 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18678 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18679 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18680 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18681 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18682 flags (@pxref{Switches for gnatmake}).
18683
18684 @item --RTS=@var{rts-path}
18685 @cindex @option{--RTS} (@code{gnatls})
18686 Specifies the default location of the runtime library. Same meaning as the
18687 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18688
18689 @item ^-v^/OUTPUT=VERBOSE^
18690 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18691 Verbose mode. Output the complete source, object and project paths. Do not use
18692 the default column layout but instead use long format giving as much as
18693 information possible on each requested units, including special
18694 characteristics such as:
18695
18696 @table @code
18697 @item  Preelaborable
18698 The unit is preelaborable in the Ada sense.
18699
18700 @item No_Elab_Code
18701 No elaboration code has been produced by the compiler for this unit.
18702
18703 @item Pure
18704 The unit is pure in the Ada sense.
18705
18706 @item Elaborate_Body
18707 The unit contains a pragma Elaborate_Body.
18708
18709 @item Remote_Types
18710 The unit contains a pragma Remote_Types.
18711
18712 @item Shared_Passive
18713 The unit contains a pragma Shared_Passive.
18714
18715 @item Predefined
18716 This unit is part of the predefined environment and cannot be modified
18717 by the user.
18718
18719 @item Remote_Call_Interface
18720 The unit contains a pragma Remote_Call_Interface.
18721
18722 @end table
18723
18724 @end table
18725
18726 @node Examples of gnatls Usage
18727 @section Example of @code{gnatls} Usage
18728 @ifclear vms
18729
18730 @noindent
18731 Example of using the verbose switch. Note how the source and
18732 object paths are affected by the -I switch.
18733
18734 @smallexample
18735 $ gnatls -v -I.. demo1.o
18736
18737 GNATLS 5.03w (20041123-34)
18738 Copyright 1997-2004 Free Software Foundation, Inc.
18739
18740 Source Search Path:
18741    <Current_Directory>
18742    ../
18743    /home/comar/local/adainclude/
18744
18745 Object Search Path:
18746    <Current_Directory>
18747    ../
18748    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18749
18750 Project Search Path:
18751    <Current_Directory>
18752    /home/comar/local/lib/gnat/
18753
18754 ./demo1.o
18755    Unit =>
18756      Name   => demo1
18757      Kind   => subprogram body
18758      Flags  => No_Elab_Code
18759      Source => demo1.adb    modified
18760 @end smallexample
18761
18762 @noindent
18763 The following is an example of use of the dependency list.
18764 Note the use of the -s switch
18765 which gives a straight list of source files. This can be useful for
18766 building specialized scripts.
18767
18768 @smallexample
18769 $ gnatls -d demo2.o
18770 ./demo2.o   demo2        OK demo2.adb
18771                          OK gen_list.ads
18772                          OK gen_list.adb
18773                          OK instr.ads
18774                          OK instr-child.ads
18775
18776 $ gnatls -d -s -a demo1.o
18777 demo1.adb
18778 /home/comar/local/adainclude/ada.ads
18779 /home/comar/local/adainclude/a-finali.ads
18780 /home/comar/local/adainclude/a-filico.ads
18781 /home/comar/local/adainclude/a-stream.ads
18782 /home/comar/local/adainclude/a-tags.ads
18783 gen_list.ads
18784 gen_list.adb
18785 /home/comar/local/adainclude/gnat.ads
18786 /home/comar/local/adainclude/g-io.ads
18787 instr.ads
18788 /home/comar/local/adainclude/system.ads
18789 /home/comar/local/adainclude/s-exctab.ads
18790 /home/comar/local/adainclude/s-finimp.ads
18791 /home/comar/local/adainclude/s-finroo.ads
18792 /home/comar/local/adainclude/s-secsta.ads
18793 /home/comar/local/adainclude/s-stalib.ads
18794 /home/comar/local/adainclude/s-stoele.ads
18795 /home/comar/local/adainclude/s-stratt.ads
18796 /home/comar/local/adainclude/s-tasoli.ads
18797 /home/comar/local/adainclude/s-unstyp.ads
18798 /home/comar/local/adainclude/unchconv.ads
18799 @end smallexample
18800 @end ifclear
18801
18802 @ifset vms
18803 @smallexample
18804 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18805
18806 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18807 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18808 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18809 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18810 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18811 demo1.adb
18812 gen_list.ads
18813 gen_list.adb
18814 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18815 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18816 instr.ads
18817 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18818 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18819 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18820 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18822 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18823 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18824 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18825 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18826 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18827 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18828 @end smallexample
18829 @end ifset
18830
18831 @node Cleaning Up Using gnatclean
18832 @chapter Cleaning Up Using @code{gnatclean}
18833 @findex gnatclean
18834 @cindex Cleaning tool
18835
18836 @noindent
18837 @code{gnatclean} is a tool that allows the deletion of files produced by the
18838 compiler, binder and linker, including ALI files, object files, tree files,
18839 expanded source files, library files, interface copy source files, binder
18840 generated files and executable files.
18841
18842 @menu
18843 * Running gnatclean::
18844 * Switches for gnatclean::
18845 @c * Examples of gnatclean Usage::
18846 @end menu
18847
18848 @node Running gnatclean
18849 @section Running @code{gnatclean}
18850
18851 @noindent
18852 The @code{gnatclean} command has the form:
18853
18854 @smallexample
18855 $ gnatclean switches @var{names}
18856 @end smallexample
18857
18858 @noindent
18859 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18860 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18861 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18862
18863 @noindent
18864 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18865 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18866 the linker. In informative-only mode, specified by switch
18867 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18868 normal mode is listed, but no file is actually deleted.
18869
18870 @node Switches for gnatclean
18871 @section Switches for @code{gnatclean}
18872
18873 @noindent
18874 @code{gnatclean} recognizes the following switches:
18875
18876 @table @option
18877 @c !sort!
18878 @cindex @option{--version} @command{gnatclean}
18879 Display Copyright and version, then exit disregarding all other options.
18880
18881 @item --help
18882 @cindex @option{--help} @command{gnatclean}
18883 If @option{--version} was not used, display usage, then exit disregarding
18884 all other options.
18885
18886 @item ^-c^/COMPILER_FILES_ONLY^
18887 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18888 Only attempt to delete the files produced by the compiler, not those produced
18889 by the binder or the linker. The files that are not to be deleted are library
18890 files, interface copy files, binder generated files and executable files.
18891
18892 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18893 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18894 Indicate that ALI and object files should normally be found in directory
18895 @var{dir}.
18896
18897 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18898 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18899 When using project files, if some errors or warnings are detected during
18900 parsing and verbose mode is not in effect (no use of switch
18901 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18902 file, rather than its simple file name.
18903
18904 @item ^-h^/HELP^
18905 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18906 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18907
18908 @item ^-n^/NODELETE^
18909 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18910 Informative-only mode. Do not delete any files. Output the list of the files
18911 that would have been deleted if this switch was not specified.
18912
18913 @item ^-P^/PROJECT_FILE=^@var{project}
18914 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18915 Use project file @var{project}. Only one such switch can be used.
18916 When cleaning a project file, the files produced by the compilation of the
18917 immediate sources or inherited sources of the project files are to be
18918 deleted. This is not depending on the presence or not of executable names
18919 on the command line.
18920
18921 @item ^-q^/QUIET^
18922 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18923 Quiet output. If there are no errors, do not output anything, except in
18924 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18925 (switch ^-n^/NODELETE^).
18926
18927 @item ^-r^/RECURSIVE^
18928 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18929 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18930 clean all imported and extended project files, recursively. If this switch
18931 is not specified, only the files related to the main project file are to be
18932 deleted. This switch has no effect if no project file is specified.
18933
18934 @item ^-v^/VERBOSE^
18935 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18936 Verbose mode.
18937
18938 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18939 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18940 Indicates the verbosity of the parsing of GNAT project files.
18941 @xref{Switches Related to Project Files}.
18942
18943 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18944 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18945 Indicates that external variable @var{name} has the value @var{value}.
18946 The Project Manager will use this value for occurrences of
18947 @code{external(name)} when parsing the project file.
18948 @xref{Switches Related to Project Files}.
18949
18950 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18951 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18952 When searching for ALI and object files, look in directory
18953 @var{dir}.
18954
18955 @item ^-I^/SEARCH=^@var{dir}
18956 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18957 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18958
18959 @item ^-I-^/NOCURRENT_DIRECTORY^
18960 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18961 @cindex Source files, suppressing search
18962 Do not look for ALI or object files in the directory
18963 where @code{gnatclean} was invoked.
18964
18965 @end table
18966
18967 @c @node Examples of gnatclean Usage
18968 @c @section Examples of @code{gnatclean} Usage
18969
18970 @ifclear vms
18971 @node GNAT and Libraries
18972 @chapter GNAT and Libraries
18973 @cindex Library, building, installing, using
18974
18975 @noindent
18976 This chapter describes how to build and use libraries with GNAT, and also shows
18977 how to recompile the GNAT run-time library. You should be familiar with the
18978 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18979 chapter.
18980
18981 @menu
18982 * Introduction to Libraries in GNAT::
18983 * General Ada Libraries::
18984 * Stand-alone Ada Libraries::
18985 * Rebuilding the GNAT Run-Time Library::
18986 @end menu
18987
18988 @node Introduction to Libraries in GNAT
18989 @section Introduction to Libraries in GNAT
18990
18991 @noindent
18992 A library is, conceptually, a collection of objects which does not have its
18993 own main thread of execution, but rather provides certain services to the
18994 applications that use it. A library can be either statically linked with the
18995 application, in which case its code is directly included in the application,
18996 or, on platforms that support it, be dynamically linked, in which case
18997 its code is shared by all applications making use of this library.
18998
18999 GNAT supports both types of libraries.
19000 In the static case, the compiled code can be provided in different ways. The
19001 simplest approach is to provide directly the set of objects resulting from
19002 compilation of the library source files. Alternatively, you can group the
19003 objects into an archive using whatever commands are provided by the operating
19004 system. For the latter case, the objects are grouped into a shared library.
19005
19006 In the GNAT environment, a library has three types of components:
19007 @itemize @bullet
19008 @item
19009 Source files.
19010 @item
19011 @file{ALI} files.
19012 @xref{The Ada Library Information Files}.
19013 @item
19014 Object files, an archive or a shared library.
19015 @end itemize
19016
19017 @noindent
19018 A GNAT library may expose all its source files, which is useful for
19019 documentation purposes. Alternatively, it may expose only the units needed by
19020 an external user to make use of the library. That is to say, the specs
19021 reflecting the library services along with all the units needed to compile
19022 those specs, which can include generic bodies or any body implementing an
19023 inlined routine. In the case of @emph{stand-alone libraries} those exposed
19024 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
19025
19026 All compilation units comprising an application, including those in a library,
19027 need to be elaborated in an order partially defined by Ada's semantics. GNAT
19028 computes the elaboration order from the @file{ALI} files and this is why they
19029 constitute a mandatory part of GNAT libraries.
19030 @emph{Stand-alone libraries} are the exception to this rule because a specific
19031 library elaboration routine is produced independently of the application(s)
19032 using the library.
19033
19034 @node General Ada Libraries
19035 @section General Ada Libraries
19036
19037 @menu
19038 * Building a library::
19039 * Installing a library::
19040 * Using a library::
19041 @end menu
19042
19043 @node Building a library
19044 @subsection Building a library
19045
19046 @noindent
19047 The easiest way to build a library is to use the Project Manager,
19048 which supports a special type of project called a @emph{Library Project}
19049 (@pxref{Library Projects}).
19050
19051 A project is considered a library project, when two project-level attributes
19052 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19053 control different aspects of library configuration, additional optional
19054 project-level attributes can be specified:
19055 @table @code
19056 @item Library_Kind
19057 This attribute controls whether the library is to be static or dynamic
19058
19059 @item Library_Version
19060 This attribute specifies the library version; this value is used
19061 during dynamic linking of shared libraries to determine if the currently
19062 installed versions of the binaries are compatible.
19063
19064 @item Library_Options
19065 @item Library_GCC
19066 These attributes specify additional low-level options to be used during
19067 library generation, and redefine the actual application used to generate
19068 library.
19069 @end table
19070
19071 @noindent
19072 The GNAT Project Manager takes full care of the library maintenance task,
19073 including recompilation of the source files for which objects do not exist
19074 or are not up to date, assembly of the library archive, and installation of
19075 the library (i.e., copying associated source, object and @file{ALI} files
19076 to the specified location).
19077
19078 Here is a simple library project file:
19079 @smallexample @c ada
19080 project My_Lib is
19081    for Source_Dirs use ("src1", "src2");
19082    for Object_Dir use "obj";
19083    for Library_Name use "mylib";
19084    for Library_Dir use "lib";
19085    for Library_Kind use "dynamic";
19086 end My_lib;
19087 @end smallexample
19088
19089 @noindent
19090 and the compilation command to build and install the library:
19091
19092 @smallexample @c ada
19093   $ gnatmake -Pmy_lib
19094 @end smallexample
19095
19096 @noindent
19097 It is not entirely trivial to perform manually all the steps required to
19098 produce a library. We recommend that you use the GNAT Project Manager
19099 for this task. In special cases where this is not desired, the necessary
19100 steps are discussed below.
19101
19102 There are various possibilities for compiling the units that make up the
19103 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19104 with a conventional script. For simple libraries, it is also possible to create
19105 a dummy main program which depends upon all the packages that comprise the
19106 interface of the library. This dummy main program can then be given to
19107 @command{gnatmake}, which will ensure that all necessary objects are built.
19108
19109 After this task is accomplished, you should follow the standard procedure
19110 of the underlying operating system to produce the static or shared library.
19111
19112 Here is an example of such a dummy program:
19113 @smallexample @c ada
19114 @group
19115 with My_Lib.Service1;
19116 with My_Lib.Service2;
19117 with My_Lib.Service3;
19118 procedure My_Lib_Dummy is
19119 begin
19120    null;
19121 end;
19122 @end group
19123 @end smallexample
19124
19125 @noindent
19126 Here are the generic commands that will build an archive or a shared library.
19127
19128 @smallexample
19129 # compiling the library
19130 $ gnatmake -c my_lib_dummy.adb
19131
19132 # we don't need the dummy object itself
19133 $ rm my_lib_dummy.o my_lib_dummy.ali
19134
19135 # create an archive with the remaining objects
19136 $ ar rc libmy_lib.a *.o
19137 # some systems may require "ranlib" to be run as well
19138
19139 # or create a shared library
19140 $ gcc -shared -o libmy_lib.so *.o
19141 # some systems may require the code to have been compiled with -fPIC
19142
19143 # remove the object files that are now in the library
19144 $ rm *.o
19145
19146 # Make the ALI files read-only so that gnatmake will not try to
19147 # regenerate the objects that are in the library
19148 $ chmod -w *.ali
19149 @end smallexample
19150
19151 @noindent
19152 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19153 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19154 be accessed by the directive @option{-l@var{xxx}} at link time.
19155
19156 @node Installing a library
19157 @subsection Installing a library
19158 @cindex @code{ADA_PROJECT_PATH}
19159 @cindex @code{GPR_PROJECT_PATH}
19160
19161 @noindent
19162 If you use project files, library installation is part of the library build
19163 process. Thus no further action is needed in order to make use of the
19164 libraries that are built as part of the general application build. A usable
19165 version of the library is installed in the directory specified by the
19166 @code{Library_Dir} attribute of the library project file.
19167
19168 You may want to install a library in a context different from where the library
19169 is built. This situation arises with third party suppliers, who may want
19170 to distribute a library in binary form where the user is not expected to be
19171 able to recompile the library. The simplest option in this case is to provide
19172 a project file slightly different from the one used to build the library, by
19173 using the @code{externally_built} attribute. For instance, the project
19174 file used to build the library in the previous section can be changed into the
19175 following one when the library is installed:
19176
19177 @smallexample @c projectfile
19178 project My_Lib is
19179    for Source_Dirs use ("src1", "src2");
19180    for Library_Name use "mylib";
19181    for Library_Dir use "lib";
19182    for Library_Kind use "dynamic";
19183    for Externally_Built use "true";
19184 end My_lib;
19185 @end smallexample
19186
19187 @noindent
19188 This project file assumes that the directories @file{src1},
19189 @file{src2}, and @file{lib} exist in
19190 the directory containing the project file. The @code{externally_built}
19191 attribute makes it clear to the GNAT builder that it should not attempt to
19192 recompile any of the units from this library. It allows the library provider to
19193 restrict the source set to the minimum necessary for clients to make use of the
19194 library as described in the first section of this chapter. It is the
19195 responsibility of the library provider to install the necessary sources, ALI
19196 files and libraries in the directories mentioned in the project file. For
19197 convenience, the user's library project file should be installed in a location
19198 that will be searched automatically by the GNAT
19199 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19200 environment variable (@pxref{Importing Projects}), and also the default GNAT
19201 library location that can be queried with @command{gnatls -v} and is usually of
19202 the form $gnat_install_root/lib/gnat.
19203
19204 When project files are not an option, it is also possible, but not recommended,
19205 to install the library so that the sources needed to use the library are on the
19206 Ada source path and the ALI files & libraries be on the Ada Object path (see
19207 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19208 administrator can place general-purpose libraries in the default compiler
19209 paths, by specifying the libraries' location in the configuration files
19210 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19211 must be located in the GNAT installation tree at the same place as the gcc spec
19212 file. The location of the gcc spec file can be determined as follows:
19213 @smallexample
19214 $ gcc -v
19215 @end smallexample
19216
19217 @noindent
19218 The configuration files mentioned above have a simple format: each line
19219 must contain one unique directory name.
19220 Those names are added to the corresponding path
19221 in their order of appearance in the file. The names can be either absolute
19222 or relative; in the latter case, they are relative to where theses files
19223 are located.
19224
19225 The files @file{ada_source_path} and @file{ada_object_path} might not be
19226 present in a
19227 GNAT installation, in which case, GNAT will look for its run-time library in
19228 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19229 objects and @file{ALI} files). When the files exist, the compiler does not
19230 look in @file{adainclude} and @file{adalib}, and thus the
19231 @file{ada_source_path} file
19232 must contain the location for the GNAT run-time sources (which can simply
19233 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19234 contain the location for the GNAT run-time objects (which can simply
19235 be @file{adalib}).
19236
19237 You can also specify a new default path to the run-time library at compilation
19238 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19239 the run-time library you want your program to be compiled with. This switch is
19240 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19241 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19242
19243 It is possible to install a library before or after the standard GNAT
19244 library, by reordering the lines in the configuration files. In general, a
19245 library must be installed before the GNAT library if it redefines
19246 any part of it.
19247
19248 @node Using a library
19249 @subsection Using a library
19250
19251 @noindent Once again, the project facility greatly simplifies the use of
19252 libraries. In this context, using a library is just a matter of adding a
19253 @code{with} clause in the user project. For instance, to make use of the
19254 library @code{My_Lib} shown in examples in earlier sections, you can
19255 write:
19256
19257 @smallexample @c projectfile
19258 with "my_lib";
19259 project My_Proj is
19260   @dots{}
19261 end My_Proj;
19262 @end smallexample
19263
19264 Even if you have a third-party, non-Ada library, you can still use GNAT's
19265 Project Manager facility to provide a wrapper for it. For example, the
19266 following project, when @code{with}ed by your main project, will link with the
19267 third-party library @file{liba.a}:
19268
19269 @smallexample @c projectfile
19270 @group
19271 project Liba is
19272    for Externally_Built use "true";
19273    for Source_Files use ();
19274    for Library_Dir use "lib";
19275    for Library_Name use "a";
19276    for Library_Kind use "static";
19277 end Liba;
19278 @end group
19279 @end smallexample
19280 This is an alternative to the use of @code{pragma Linker_Options}. It is
19281 especially interesting in the context of systems with several interdependent
19282 static libraries where finding a proper linker order is not easy and best be
19283 left to the tools having visibility over project dependence information.
19284
19285 @noindent
19286 In order to use an Ada library manually, you need to make sure that this
19287 library is on both your source and object path
19288 (see @ref{Search Paths and the Run-Time Library (RTL)}
19289 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19290 in an archive or a shared library, you need to specify the desired
19291 library at link time.
19292
19293 For example, you can use the library @file{mylib} installed in
19294 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19295
19296 @smallexample
19297 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19298   -largs -lmy_lib
19299 @end smallexample
19300
19301 @noindent
19302 This can be expressed more simply:
19303 @smallexample
19304 $ gnatmake my_appl
19305 @end smallexample
19306 @noindent
19307 when the following conditions are met:
19308 @itemize @bullet
19309 @item
19310 @file{/dir/my_lib_src} has been added by the user to the environment
19311 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19312 @file{ada_source_path}
19313 @item
19314 @file{/dir/my_lib_obj} has been added by the user to the environment
19315 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19316 @file{ada_object_path}
19317 @item
19318 a pragma @code{Linker_Options} has been added to one of the sources.
19319 For example:
19320
19321 @smallexample @c ada
19322 pragma Linker_Options ("-lmy_lib");
19323 @end smallexample
19324 @end itemize
19325
19326 @node Stand-alone Ada Libraries
19327 @section Stand-alone Ada Libraries
19328 @cindex Stand-alone library, building, using
19329
19330 @menu
19331 * Introduction to Stand-alone Libraries::
19332 * Building a Stand-alone Library::
19333 * Creating a Stand-alone Library to be used in a non-Ada context::
19334 * Restrictions in Stand-alone Libraries::
19335 @end menu
19336
19337 @node Introduction to Stand-alone Libraries
19338 @subsection Introduction to Stand-alone Libraries
19339
19340 @noindent
19341 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19342 necessary code to
19343 elaborate the Ada units that are included in the library. In contrast with
19344 an ordinary library, which consists of all sources, objects and @file{ALI}
19345 files of the
19346 library, a SAL may specify a restricted subset of compilation units
19347 to serve as a library interface. In this case, the fully
19348 self-sufficient set of files will normally consist of an objects
19349 archive, the sources of interface units' specs, and the @file{ALI}
19350 files of interface units.
19351 If an interface spec contains a generic unit or an inlined subprogram,
19352 the body's
19353 source must also be provided; if the units that must be provided in the source
19354 form depend on other units, the source and @file{ALI} files of those must
19355 also be provided.
19356
19357 The main purpose of a SAL is to minimize the recompilation overhead of client
19358 applications when a new version of the library is installed. Specifically,
19359 if the interface sources have not changed, client applications do not need to
19360 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19361 version, controlled by @code{Library_Version} attribute, is not changed,
19362 then the clients do not need to be relinked.
19363
19364 SALs also allow the library providers to minimize the amount of library source
19365 text exposed to the clients.  Such ``information hiding'' might be useful or
19366 necessary for various reasons.
19367
19368 Stand-alone libraries are also well suited to be used in an executable whose
19369 main routine is not written in Ada.
19370
19371 @node Building a Stand-alone Library
19372 @subsection Building a Stand-alone Library
19373
19374 @noindent
19375 GNAT's Project facility provides a simple way of building and installing
19376 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19377 To be a Stand-alone Library Project, in addition to the two attributes
19378 that make a project a Library Project (@code{Library_Name} and
19379 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19380 @code{Library_Interface} must be defined.  For example:
19381
19382 @smallexample @c projectfile
19383 @group
19384    for Library_Dir use "lib_dir";
19385    for Library_Name use "dummy";
19386    for Library_Interface use ("int1", "int1.child");
19387 @end group
19388 @end smallexample
19389
19390 @noindent
19391 Attribute @code{Library_Interface} has a non-empty string list value,
19392 each string in the list designating a unit contained in an immediate source
19393 of the project file.
19394
19395 When a Stand-alone Library is built, first the binder is invoked to build
19396 a package whose name depends on the library name
19397 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19398 This binder-generated package includes initialization and
19399 finalization procedures whose
19400 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19401 in the example
19402 above). The object corresponding to this package is included in the library.
19403
19404 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19405 calling of these procedures if a static SAL is built, or if a shared SAL
19406 is built
19407 with the project-level attribute @code{Library_Auto_Init} set to
19408 @code{"false"}.
19409
19410 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19411 (those that are listed in attribute @code{Library_Interface}) are copied to
19412 the Library Directory. As a consequence, only the Interface Units may be
19413 imported from Ada units outside of the library. If other units are imported,
19414 the binding phase will fail.
19415
19416 The attribute @code{Library_Src_Dir} may be specified for a
19417 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19418 single string value. Its value must be the path (absolute or relative to the
19419 project directory) of an existing directory. This directory cannot be the
19420 object directory or one of the source directories, but it can be the same as
19421 the library directory. The sources of the Interface
19422 Units of the library that are needed by an Ada client of the library will be
19423 copied to the designated directory, called the Interface Copy directory.
19424 These sources include the specs of the Interface Units, but they may also
19425 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19426 are used, or when there is a generic unit in the spec. Before the sources
19427 are copied to the Interface Copy directory, an attempt is made to delete all
19428 files in the Interface Copy directory.
19429
19430 Building stand-alone libraries by hand is somewhat tedious, but for those
19431 occasions when it is necessary here are the steps that you need to perform:
19432 @itemize @bullet
19433 @item
19434 Compile all library sources.
19435
19436 @item
19437 Invoke the binder with the switch @option{-n} (No Ada main program),
19438 with all the @file{ALI} files of the interfaces, and
19439 with the switch @option{-L} to give specific names to the @code{init}
19440 and @code{final} procedures.  For example:
19441 @smallexample
19442   gnatbind -n int1.ali int2.ali -Lsal1
19443 @end smallexample
19444
19445 @item
19446 Compile the binder generated file:
19447 @smallexample
19448   gcc -c b~int2.adb
19449 @end smallexample
19450
19451 @item
19452 Link the dynamic library with all the necessary object files,
19453 indicating to the linker the names of the @code{init} (and possibly
19454 @code{final}) procedures for automatic initialization (and finalization).
19455 The built library should be placed in a directory different from
19456 the object directory.
19457
19458 @item
19459 Copy the @code{ALI} files of the interface to the library directory,
19460 add in this copy an indication that it is an interface to a SAL
19461 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19462 with letter ``P'') and make the modified copy of the @file{ALI} file
19463 read-only.
19464 @end itemize
19465
19466 @noindent
19467 Using SALs is not different from using other libraries
19468 (see @ref{Using a library}).
19469
19470 @node Creating a Stand-alone Library to be used in a non-Ada context
19471 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19472
19473 @noindent
19474 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19475 a non-Ada context.
19476
19477 The only extra step required is to ensure that library interface subprograms
19478 are compatible with the main program, by means of @code{pragma Export}
19479 or @code{pragma Convention}.
19480
19481 Here is an example of simple library interface for use with C main program:
19482
19483 @smallexample @c ada
19484 package My_Package is
19485
19486    procedure Do_Something;
19487    pragma Export (C, Do_Something, "do_something");
19488
19489    procedure Do_Something_Else;
19490    pragma Export (C, Do_Something_Else, "do_something_else");
19491
19492 end My_Package;
19493 @end smallexample
19494
19495 @noindent
19496 On the foreign language side, you must provide a ``foreign'' view of the
19497 library interface; remember that it should contain elaboration routines in
19498 addition to interface subprograms.
19499
19500 The example below shows the content of @code{mylib_interface.h} (note
19501 that there is no rule for the naming of this file, any name can be used)
19502 @smallexample
19503 /* the library elaboration procedure */
19504 extern void mylibinit (void);
19505
19506 /* the library finalization procedure */
19507 extern void mylibfinal (void);
19508
19509 /* the interface exported by the library */
19510 extern void do_something (void);
19511 extern void do_something_else (void);
19512 @end smallexample
19513
19514 @noindent
19515 Libraries built as explained above can be used from any program, provided
19516 that the elaboration procedures (named @code{mylibinit} in the previous
19517 example) are called before the library services are used. Any number of
19518 libraries can be used simultaneously, as long as the elaboration
19519 procedure of each library is called.
19520
19521 Below is an example of a C program that uses the @code{mylib} library.
19522
19523 @smallexample
19524 #include "mylib_interface.h"
19525
19526 int
19527 main (void)
19528 @{
19529    /* First, elaborate the library before using it */
19530    mylibinit ();
19531
19532    /* Main program, using the library exported entities */
19533    do_something ();
19534    do_something_else ();
19535
19536    /* Library finalization at the end of the program */
19537    mylibfinal ();
19538    return 0;
19539 @}
19540 @end smallexample
19541
19542 @noindent
19543 Note that invoking any library finalization procedure generated by
19544 @code{gnatbind} shuts down the Ada run-time environment.
19545 Consequently, the
19546 finalization of all Ada libraries must be performed at the end of the program.
19547 No call to these libraries or to the Ada run-time library should be made
19548 after the finalization phase.
19549
19550 @node Restrictions in Stand-alone Libraries
19551 @subsection Restrictions in Stand-alone Libraries
19552
19553 @noindent
19554 The pragmas listed below should be used with caution inside libraries,
19555 as they can create incompatibilities with other Ada libraries:
19556 @itemize @bullet
19557 @item pragma @code{Locking_Policy}
19558 @item pragma @code{Queuing_Policy}
19559 @item pragma @code{Task_Dispatching_Policy}
19560 @item pragma @code{Unreserve_All_Interrupts}
19561 @end itemize
19562
19563 @noindent
19564 When using a library that contains such pragmas, the user must make sure
19565 that all libraries use the same pragmas with the same values. Otherwise,
19566 @code{Program_Error} will
19567 be raised during the elaboration of the conflicting
19568 libraries. The usage of these pragmas and its consequences for the user
19569 should therefore be well documented.
19570
19571 Similarly, the traceback in the exception occurrence mechanism should be
19572 enabled or disabled in a consistent manner across all libraries.
19573 Otherwise, Program_Error will be raised during the elaboration of the
19574 conflicting libraries.
19575
19576 If the @code{Version} or @code{Body_Version}
19577 attributes are used inside a library, then you need to
19578 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19579 libraries, so that version identifiers can be properly computed.
19580 In practice these attributes are rarely used, so this is unlikely
19581 to be a consideration.
19582
19583 @node  Rebuilding the GNAT Run-Time Library
19584 @section Rebuilding the GNAT Run-Time Library
19585 @cindex GNAT Run-Time Library, rebuilding
19586 @cindex Building the GNAT Run-Time Library
19587 @cindex Rebuilding the GNAT Run-Time Library
19588 @cindex Run-Time Library, rebuilding
19589
19590 @noindent
19591 It may be useful to recompile the GNAT library in various contexts, the
19592 most important one being the use of partition-wide configuration pragmas
19593 such as @code{Normalize_Scalars}. A special Makefile called
19594 @code{Makefile.adalib} is provided to that effect and can be found in
19595 the directory containing the GNAT library. The location of this
19596 directory depends on the way the GNAT environment has been installed and can
19597 be determined by means of the command:
19598
19599 @smallexample
19600 $ gnatls -v
19601 @end smallexample
19602
19603 @noindent
19604 The last entry in the object search path usually contains the
19605 gnat library. This Makefile contains its own documentation and in
19606 particular the set of instructions needed to rebuild a new library and
19607 to use it.
19608
19609 @node Using the GNU make Utility
19610 @chapter Using the GNU @code{make} Utility
19611 @findex make
19612
19613 @noindent
19614 This chapter offers some examples of makefiles that solve specific
19615 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19616 make, make, GNU @code{make}}), nor does it try to replace the
19617 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19618
19619 All the examples in this section are specific to the GNU version of
19620 make. Although @command{make} is a standard utility, and the basic language
19621 is the same, these examples use some advanced features found only in
19622 @code{GNU make}.
19623
19624 @menu
19625 * Using gnatmake in a Makefile::
19626 * Automatically Creating a List of Directories::
19627 * Generating the Command Line Switches::
19628 * Overcoming Command Line Length Limits::
19629 @end menu
19630
19631 @node Using gnatmake in a Makefile
19632 @section Using gnatmake in a Makefile
19633 @findex makefile
19634 @cindex GNU make
19635
19636 @noindent
19637 Complex project organizations can be handled in a very powerful way by
19638 using GNU make combined with gnatmake. For instance, here is a Makefile
19639 which allows you to build each subsystem of a big project into a separate
19640 shared library. Such a makefile allows you to significantly reduce the link
19641 time of very big applications while maintaining full coherence at
19642 each step of the build process.
19643
19644 The list of dependencies are handled automatically by
19645 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19646 the appropriate directories.
19647
19648 Note that you should also read the example on how to automatically
19649 create the list of directories
19650 (@pxref{Automatically Creating a List of Directories})
19651 which might help you in case your project has a lot of subdirectories.
19652
19653 @smallexample
19654 @iftex
19655 @leftskip=0cm
19656 @font@heightrm=cmr8
19657 @heightrm
19658 @end iftex
19659 ## This Makefile is intended to be used with the following directory
19660 ## configuration:
19661 ##  - The sources are split into a series of csc (computer software components)
19662 ##    Each of these csc is put in its own directory.
19663 ##    Their name are referenced by the directory names.
19664 ##    They will be compiled into shared library (although this would also work
19665 ##    with static libraries
19666 ##  - The main program (and possibly other packages that do not belong to any
19667 ##    csc is put in the top level directory (where the Makefile is).
19668 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19669 ##                    \_ second_csc (sources) __ lib (will contain the library)
19670 ##                    \_ @dots{}
19671 ## Although this Makefile is build for shared library, it is easy to modify
19672 ## to build partial link objects instead (modify the lines with -shared and
19673 ## gnatlink below)
19674 ##
19675 ## With this makefile, you can change any file in the system or add any new
19676 ## file, and everything will be recompiled correctly (only the relevant shared
19677 ## objects will be recompiled, and the main program will be re-linked).
19678
19679 # The list of computer software component for your project. This might be
19680 # generated automatically.
19681 CSC_LIST=aa bb cc
19682
19683 # Name of the main program (no extension)
19684 MAIN=main
19685
19686 # If we need to build objects with -fPIC, uncomment the following line
19687 #NEED_FPIC=-fPIC
19688
19689 # The following variable should give the directory containing libgnat.so
19690 # You can get this directory through 'gnatls -v'. This is usually the last
19691 # directory in the Object_Path.
19692 GLIB=@dots{}
19693
19694 # The directories for the libraries
19695 # (This macro expands the list of CSC to the list of shared libraries, you
19696 # could simply use the expanded form:
19697 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19698 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19699
19700 $@{MAIN@}: objects $@{LIB_DIR@}
19701     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19702     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19703
19704 objects::
19705     # recompile the sources
19706     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19707
19708 # Note: In a future version of GNAT, the following commands will be simplified
19709 # by a new tool, gnatmlib
19710 $@{LIB_DIR@}:
19711     mkdir -p $@{dir $@@ @}
19712     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19713     cd $@{dir $@@ @} && cp -f ../*.ali .
19714
19715 # The dependencies for the modules
19716 # Note that we have to force the expansion of *.o, since in some cases
19717 # make won't be able to do it itself.
19718 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19719 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19720 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19721
19722 # Make sure all of the shared libraries are in the path before starting the
19723 # program
19724 run::
19725     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19726
19727 clean::
19728     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19729     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19730     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19731     $@{RM@} *.o *.ali $@{MAIN@}
19732 @end smallexample
19733
19734 @node Automatically Creating a List of Directories
19735 @section Automatically Creating a List of Directories
19736
19737 @noindent
19738 In most makefiles, you will have to specify a list of directories, and
19739 store it in a variable. For small projects, it is often easier to
19740 specify each of them by hand, since you then have full control over what
19741 is the proper order for these directories, which ones should be
19742 included.
19743
19744 However, in larger projects, which might involve hundreds of
19745 subdirectories, it might be more convenient to generate this list
19746 automatically.
19747
19748 The example below presents two methods. The first one, although less
19749 general, gives you more control over the list. It involves wildcard
19750 characters, that are automatically expanded by @command{make}. Its
19751 shortcoming is that you need to explicitly specify some of the
19752 organization of your project, such as for instance the directory tree
19753 depth, whether some directories are found in a separate tree, @enddots{}
19754
19755 The second method is the most general one. It requires an external
19756 program, called @command{find}, which is standard on all Unix systems. All
19757 the directories found under a given root directory will be added to the
19758 list.
19759
19760 @smallexample
19761 @iftex
19762 @leftskip=0cm
19763 @font@heightrm=cmr8
19764 @heightrm
19765 @end iftex
19766 # The examples below are based on the following directory hierarchy:
19767 # All the directories can contain any number of files
19768 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19769 #                       ->  ab
19770 #                       ->  ac
19771 #                ->  b  ->  ba  ->  baa
19772 #                       ->  bb
19773 #                       ->  bc
19774 # This Makefile creates a variable called DIRS, that can be reused any time
19775 # you need this list (see the other examples in this section)
19776
19777 # The root of your project's directory hierarchy
19778 ROOT_DIRECTORY=.
19779
19780 ####
19781 # First method: specify explicitly the list of directories
19782 # This allows you to specify any subset of all the directories you need.
19783 ####
19784
19785 DIRS := a/aa/ a/ab/ b/ba/
19786
19787 ####
19788 # Second method: use wildcards
19789 # Note that the argument(s) to wildcard below should end with a '/'.
19790 # Since wildcards also return file names, we have to filter them out
19791 # to avoid duplicate directory names.
19792 # We thus use make's @code{dir} and @code{sort} functions.
19793 # It sets DIRs to the following value (note that the directories aaa and baa
19794 # are not given, unless you change the arguments to wildcard).
19795 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19796 ####
19797
19798 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19799                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19800
19801 ####
19802 # Third method: use an external program
19803 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19804 # This is the most complete command: it sets DIRs to the following value:
19805 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19806 ####
19807
19808 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19809
19810 @end smallexample
19811
19812 @node Generating the Command Line Switches
19813 @section Generating the Command Line Switches
19814
19815 @noindent
19816 Once you have created the list of directories as explained in the
19817 previous section (@pxref{Automatically Creating a List of Directories}),
19818 you can easily generate the command line arguments to pass to gnatmake.
19819
19820 For the sake of completeness, this example assumes that the source path
19821 is not the same as the object path, and that you have two separate lists
19822 of directories.
19823
19824 @smallexample
19825 # see "Automatically creating a list of directories" to create
19826 # these variables
19827 SOURCE_DIRS=
19828 OBJECT_DIRS=
19829
19830 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19831 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19832
19833 all:
19834         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19835 @end smallexample
19836
19837 @node Overcoming Command Line Length Limits
19838 @section Overcoming Command Line Length Limits
19839
19840 @noindent
19841 One problem that might be encountered on big projects is that many
19842 operating systems limit the length of the command line. It is thus hard to give
19843 gnatmake the list of source and object directories.
19844
19845 This example shows how you can set up environment variables, which will
19846 make @command{gnatmake} behave exactly as if the directories had been
19847 specified on the command line, but have a much higher length limit (or
19848 even none on most systems).
19849
19850 It assumes that you have created a list of directories in your Makefile,
19851 using one of the methods presented in
19852 @ref{Automatically Creating a List of Directories}.
19853 For the sake of completeness, we assume that the object
19854 path (where the ALI files are found) is different from the sources patch.
19855
19856 Note a small trick in the Makefile below: for efficiency reasons, we
19857 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19858 expanded immediately by @code{make}. This way we overcome the standard
19859 make behavior which is to expand the variables only when they are
19860 actually used.
19861
19862 On Windows, if you are using the standard Windows command shell, you must
19863 replace colons with semicolons in the assignments to these variables.
19864
19865 @smallexample
19866 @iftex
19867 @leftskip=0cm
19868 @font@heightrm=cmr8
19869 @heightrm
19870 @end iftex
19871 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19872 # This is the same thing as putting the -I arguments on the command line.
19873 # (the equivalent of using -aI on the command line would be to define
19874 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19875 # You can of course have different values for these variables.
19876 #
19877 # Note also that we need to keep the previous values of these variables, since
19878 # they might have been set before running 'make' to specify where the GNAT
19879 # library is installed.
19880
19881 # see "Automatically creating a list of directories" to create these
19882 # variables
19883 SOURCE_DIRS=
19884 OBJECT_DIRS=
19885
19886 empty:=
19887 space:=$@{empty@} $@{empty@}
19888 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19889 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19890 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19891 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19892 export ADA_INCLUDE_PATH
19893 export ADA_OBJECT_PATH
19894
19895 all:
19896         gnatmake main_unit
19897 @end smallexample
19898 @end ifclear
19899
19900 @node Memory Management Issues
19901 @chapter Memory Management Issues
19902
19903 @noindent
19904 This chapter describes some useful memory pools provided in the GNAT library
19905 and in particular the GNAT Debug Pool facility, which can be used to detect
19906 incorrect uses of access values (including ``dangling references'').
19907 @ifclear vms
19908 It also describes the @command{gnatmem} tool, which can be used to track down
19909 ``memory leaks''.
19910 @end ifclear
19911
19912 @menu
19913 * Some Useful Memory Pools::
19914 * The GNAT Debug Pool Facility::
19915 @ifclear vms
19916 * The gnatmem Tool::
19917 @end ifclear
19918 @end menu
19919
19920 @node Some Useful Memory Pools
19921 @section Some Useful Memory Pools
19922 @findex Memory Pool
19923 @cindex storage, pool
19924
19925 @noindent
19926 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19927 storage pool. Allocations use the standard system call @code{malloc} while
19928 deallocations use the standard system call @code{free}. No reclamation is
19929 performed when the pool goes out of scope. For performance reasons, the
19930 standard default Ada allocators/deallocators do not use any explicit storage
19931 pools but if they did, they could use this storage pool without any change in
19932 behavior. That is why this storage pool is used  when the user
19933 manages to make the default implicit allocator explicit as in this example:
19934 @smallexample @c ada
19935    type T1 is access Something;
19936     -- no Storage pool is defined for T2
19937    type T2 is access Something_Else;
19938    for T2'Storage_Pool use T1'Storage_Pool;
19939    -- the above is equivalent to
19940    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19941 @end smallexample
19942
19943 @noindent
19944 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19945 pool. The allocation strategy is similar to @code{Pool_Local}'s
19946 except that the all
19947 storage allocated with this pool is reclaimed when the pool object goes out of
19948 scope. This pool provides a explicit mechanism similar to the implicit one
19949 provided by several Ada 83 compilers for allocations performed through a local
19950 access type and whose purpose was to reclaim memory when exiting the
19951 scope of a given local access. As an example, the following program does not
19952 leak memory even though it does not perform explicit deallocation:
19953
19954 @smallexample @c ada
19955 with System.Pool_Local;
19956 procedure Pooloc1 is
19957    procedure Internal is
19958       type A is access Integer;
19959       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19960       for A'Storage_Pool use X;
19961       v : A;
19962    begin
19963       for I in  1 .. 50 loop
19964          v := new Integer;
19965       end loop;
19966    end Internal;
19967 begin
19968    for I in  1 .. 100 loop
19969       Internal;
19970    end loop;
19971 end Pooloc1;
19972 @end smallexample
19973
19974 @noindent
19975 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19976 @code{Storage_Size} is specified for an access type.
19977 The whole storage for the pool is
19978 allocated at once, usually on the stack at the point where the access type is
19979 elaborated. It is automatically reclaimed when exiting the scope where the
19980 access type is defined. This package is not intended to be used directly by the
19981 user and it is implicitly used for each such declaration:
19982
19983 @smallexample @c ada
19984    type T1 is access Something;
19985    for T1'Storage_Size use 10_000;
19986 @end smallexample
19987
19988 @node The GNAT Debug Pool Facility
19989 @section The GNAT Debug Pool Facility
19990 @findex Debug Pool
19991 @cindex storage, pool, memory corruption
19992
19993 @noindent
19994 The use of unchecked deallocation and unchecked conversion can easily
19995 lead to incorrect memory references. The problems generated by such
19996 references are usually difficult to tackle because the symptoms can be
19997 very remote from the origin of the problem. In such cases, it is
19998 very helpful to detect the problem as early as possible. This is the
19999 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
20000
20001 In order to use the GNAT specific debugging pool, the user must
20002 associate a debug pool object with each of the access types that may be
20003 related to suspected memory problems. See Ada Reference Manual 13.11.
20004 @smallexample @c ada
20005 type Ptr is access Some_Type;
20006 Pool : GNAT.Debug_Pools.Debug_Pool;
20007 for Ptr'Storage_Pool use Pool;
20008 @end smallexample
20009
20010 @noindent
20011 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
20012 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
20013 allow the user to redefine allocation and deallocation strategies. They
20014 also provide a checkpoint for each dereference, through the use of
20015 the primitive operation @code{Dereference} which is implicitly called at
20016 each dereference of an access value.
20017
20018 Once an access type has been associated with a debug pool, operations on
20019 values of the type may raise four distinct exceptions,
20020 which correspond to four potential kinds of memory corruption:
20021 @itemize @bullet
20022 @item
20023 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
20024 @item
20025 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
20026 @item
20027 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
20028 @item
20029 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
20030 @end itemize
20031
20032 @noindent
20033 For types associated with a Debug_Pool, dynamic allocation is performed using
20034 the standard GNAT allocation routine. References to all allocated chunks of
20035 memory are kept in an internal dictionary. Several deallocation strategies are
20036 provided, whereupon the user can choose to release the memory to the system,
20037 keep it allocated for further invalid access checks, or fill it with an easily
20038 recognizable pattern for debug sessions. The memory pattern is the old IBM
20039 hexadecimal convention: @code{16#DEADBEEF#}.
20040
20041 See the documentation in the file g-debpoo.ads for more information on the
20042 various strategies.
20043
20044 Upon each dereference, a check is made that the access value denotes a
20045 properly allocated memory location. Here is a complete example of use of
20046 @code{Debug_Pools}, that includes typical instances of  memory corruption:
20047 @smallexample @c ada
20048 @iftex
20049 @leftskip=0cm
20050 @end iftex
20051 with Gnat.Io; use Gnat.Io;
20052 with Unchecked_Deallocation;
20053 with Unchecked_Conversion;
20054 with GNAT.Debug_Pools;
20055 with System.Storage_Elements;
20056 with Ada.Exceptions; use Ada.Exceptions;
20057 procedure Debug_Pool_Test is
20058
20059    type T is access Integer;
20060    type U is access all T;
20061
20062    P : GNAT.Debug_Pools.Debug_Pool;
20063    for T'Storage_Pool use P;
20064
20065    procedure Free is new Unchecked_Deallocation (Integer, T);
20066    function UC is new Unchecked_Conversion (U, T);
20067    A, B : aliased T;
20068
20069    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20070
20071 begin
20072    Info (P);
20073    A := new Integer;
20074    B := new Integer;
20075    B := A;
20076    Info (P);
20077    Free (A);
20078    begin
20079       Put_Line (Integer'Image(B.all));
20080    exception
20081       when E : others => Put_Line ("raised: " & Exception_Name (E));
20082    end;
20083    begin
20084       Free (B);
20085    exception
20086       when E : others => Put_Line ("raised: " & Exception_Name (E));
20087    end;
20088    B := UC(A'Access);
20089    begin
20090       Put_Line (Integer'Image(B.all));
20091    exception
20092       when E : others => Put_Line ("raised: " & Exception_Name (E));
20093    end;
20094    begin
20095       Free (B);
20096    exception
20097       when E : others => Put_Line ("raised: " & Exception_Name (E));
20098    end;
20099    Info (P);
20100 end Debug_Pool_Test;
20101 @end smallexample
20102
20103 @noindent
20104 The debug pool mechanism provides the following precise diagnostics on the
20105 execution of this erroneous program:
20106 @smallexample
20107 Debug Pool info:
20108   Total allocated bytes :  0
20109   Total deallocated bytes :  0
20110   Current Water Mark:  0
20111   High Water Mark:  0
20112
20113 Debug Pool info:
20114   Total allocated bytes :  8
20115   Total deallocated bytes :  0
20116   Current Water Mark:  8
20117   High Water Mark:  8
20118
20119 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20120 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20121 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20122 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20123 Debug Pool info:
20124   Total allocated bytes :  8
20125   Total deallocated bytes :  4
20126   Current Water Mark:  4
20127   High Water Mark:  8
20128 @end smallexample
20129
20130 @ifclear vms
20131 @node The gnatmem Tool
20132 @section The @command{gnatmem} Tool
20133 @findex gnatmem
20134
20135 @noindent
20136 The @code{gnatmem} utility monitors dynamic allocation and
20137 deallocation activity in a program, and displays information about
20138 incorrect deallocations and possible sources of memory leaks.
20139 It is designed to work in association with a static runtime library
20140 only and in this context provides three types of information:
20141 @itemize @bullet
20142 @item
20143 General information concerning memory management, such as the total
20144 number of allocations and deallocations, the amount of allocated
20145 memory and the high water mark, i.e.@: the largest amount of allocated
20146 memory in the course of program execution.
20147
20148 @item
20149 Backtraces for all incorrect deallocations, that is to say deallocations
20150 which do not correspond to a valid allocation.
20151
20152 @item
20153 Information on each allocation that is potentially the origin of a memory
20154 leak.
20155 @end itemize
20156
20157 @menu
20158 * Running gnatmem::
20159 * Switches for gnatmem::
20160 * Example of gnatmem Usage::
20161 @end menu
20162
20163 @node Running gnatmem
20164 @subsection Running @code{gnatmem}
20165
20166 @noindent
20167 @code{gnatmem} makes use of the output created by the special version of
20168 allocation and deallocation routines that record call information. This
20169 allows to obtain accurate dynamic memory usage history at a minimal cost to
20170 the execution speed. Note however, that @code{gnatmem} is not supported on
20171 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20172 Solaris and Windows NT/2000/XP (x86).
20173
20174 @noindent
20175 The @code{gnatmem} command has the form
20176
20177 @smallexample
20178 @c    $ gnatmem @ovar{switches} user_program
20179 @c Expanding @ovar macro inline (explanation in macro def comments)
20180       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
20181 @end smallexample
20182
20183 @noindent
20184 The program must have been linked with the instrumented version of the
20185 allocation and deallocation routines. This is done by linking with the
20186 @file{libgmem.a} library. For correct symbolic backtrace information,
20187 the user program should be compiled with debugging options
20188 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20189
20190 @smallexample
20191 $ gnatmake -g my_program -largs -lgmem
20192 @end smallexample
20193
20194 @noindent
20195 As library @file{libgmem.a} contains an alternate body for package
20196 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20197 when an executable is linked with library @file{libgmem.a}. It is then not
20198 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20199
20200 @noindent
20201 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20202 This file contains information about all allocations and deallocations
20203 performed by the program. It is produced by the instrumented allocations and
20204 deallocations routines and will be used by @code{gnatmem}.
20205
20206 In order to produce symbolic backtrace information for allocations and
20207 deallocations performed by the GNAT run-time library, you need to use a
20208 version of that library that has been compiled with the @option{-g} switch
20209 (see @ref{Rebuilding the GNAT Run-Time Library}).
20210
20211 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20212 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20213 @option{-i} switch, gnatmem will assume that this file can be found in the
20214 current directory. For example, after you have executed @file{my_program},
20215 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20216
20217 @smallexample
20218 $ gnatmem my_program
20219 @end smallexample
20220
20221 @noindent
20222 This will produce the output with the following format:
20223
20224 *************** debut cc
20225 @smallexample
20226 $ gnatmem my_program
20227
20228 Global information
20229 ------------------
20230    Total number of allocations        :  45
20231    Total number of deallocations      :   6
20232    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20233    High Water Mark                    :  11.40 Kilobytes
20234
20235 .
20236 .
20237 .
20238 Allocation Root # 2
20239 -------------------
20240  Number of non freed allocations    :  11
20241  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20242  High Water Mark                    :   1.27 Kilobytes
20243  Backtrace                          :
20244    my_program.adb:23 my_program.alloc
20245 .
20246 .
20247 .
20248 @end smallexample
20249
20250 The first block of output gives general information. In this case, the
20251 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20252 Unchecked_Deallocation routine occurred.
20253
20254 @noindent
20255 Subsequent paragraphs display  information on all allocation roots.
20256 An allocation root is a specific point in the execution of the program
20257 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20258 construct. This root is represented by an execution backtrace (or subprogram
20259 call stack). By default the backtrace depth for allocations roots is 1, so
20260 that a root corresponds exactly to a source location. The backtrace can
20261 be made deeper, to make the root more specific.
20262
20263 @node Switches for gnatmem
20264 @subsection Switches for @code{gnatmem}
20265
20266 @noindent
20267 @code{gnatmem} recognizes the following switches:
20268
20269 @table @option
20270
20271 @item -q
20272 @cindex @option{-q} (@code{gnatmem})
20273 Quiet. Gives the minimum output needed to identify the origin of the
20274 memory leaks. Omits statistical information.
20275
20276 @item @var{N}
20277 @cindex @var{N} (@code{gnatmem})
20278 N is an integer literal (usually between 1 and 10) which controls the
20279 depth of the backtraces defining allocation root. The default value for
20280 N is 1. The deeper the backtrace, the more precise the localization of
20281 the root. Note that the total number of roots can depend on this
20282 parameter. This parameter must be specified @emph{before} the name of the
20283 executable to be analyzed, to avoid ambiguity.
20284
20285 @item -b n
20286 @cindex @option{-b} (@code{gnatmem})
20287 This switch has the same effect as just depth parameter.
20288
20289 @item -i @var{file}
20290 @cindex @option{-i} (@code{gnatmem})
20291 Do the @code{gnatmem} processing starting from @file{file}, rather than
20292 @file{gmem.out} in the current directory.
20293
20294 @item -m n
20295 @cindex @option{-m} (@code{gnatmem})
20296 This switch causes @code{gnatmem} to mask the allocation roots that have less
20297 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20298 examine even the roots that didn't result in leaks.
20299
20300 @item -s order
20301 @cindex @option{-s} (@code{gnatmem})
20302 This switch causes @code{gnatmem} to sort the allocation roots according to the
20303 specified order of sort criteria, each identified by a single letter. The
20304 currently supported criteria are @code{n, h, w} standing respectively for
20305 number of unfreed allocations, high watermark, and final watermark
20306 corresponding to a specific root. The default order is @code{nwh}.
20307
20308 @end table
20309
20310 @node Example of gnatmem Usage
20311 @subsection Example of @code{gnatmem} Usage
20312
20313 @noindent
20314 The following example shows the use of @code{gnatmem}
20315 on a simple memory-leaking program.
20316 Suppose that we have the following Ada program:
20317
20318 @smallexample @c ada
20319 @group
20320 @cartouche
20321 with Unchecked_Deallocation;
20322 procedure Test_Gm is
20323
20324    type T is array (1..1000) of Integer;
20325    type Ptr is access T;
20326    procedure Free is new Unchecked_Deallocation (T, Ptr);
20327    A : Ptr;
20328
20329    procedure My_Alloc is
20330    begin
20331       A := new T;
20332    end My_Alloc;
20333
20334    procedure My_DeAlloc is
20335       B : Ptr := A;
20336    begin
20337       Free (B);
20338    end My_DeAlloc;
20339
20340 begin
20341    My_Alloc;
20342    for I in 1 .. 5 loop
20343       for J in I .. 5 loop
20344          My_Alloc;
20345       end loop;
20346       My_Dealloc;
20347    end loop;
20348 end;
20349 @end cartouche
20350 @end group
20351 @end smallexample
20352
20353 @noindent
20354 The program needs to be compiled with debugging option and linked with
20355 @code{gmem} library:
20356
20357 @smallexample
20358 $ gnatmake -g test_gm -largs -lgmem
20359 @end smallexample
20360
20361 @noindent
20362 Then we execute the program as usual:
20363
20364 @smallexample
20365 $ test_gm
20366 @end smallexample
20367
20368 @noindent
20369 Then @code{gnatmem} is invoked simply with
20370 @smallexample
20371 $ gnatmem test_gm
20372 @end smallexample
20373
20374 @noindent
20375 which produces the following output (result may vary on different platforms):
20376
20377 @smallexample
20378 Global information
20379 ------------------
20380    Total number of allocations        :  18
20381    Total number of deallocations      :   5
20382    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20383    High Water Mark                    :  56.90 Kilobytes
20384
20385 Allocation Root # 1
20386 -------------------
20387  Number of non freed allocations    :  11
20388  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20389  High Water Mark                    :  46.88 Kilobytes
20390  Backtrace                          :
20391    test_gm.adb:11 test_gm.my_alloc
20392
20393 Allocation Root # 2
20394 -------------------
20395  Number of non freed allocations    :   1
20396  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20397  High Water Mark                    :  10.02 Kilobytes
20398  Backtrace                          :
20399    s-secsta.adb:81 system.secondary_stack.ss_init
20400
20401 Allocation Root # 3
20402 -------------------
20403  Number of non freed allocations    :   1
20404  Final Water Mark (non freed mem)   :  12 Bytes
20405  High Water Mark                    :  12 Bytes
20406  Backtrace                          :
20407    s-secsta.adb:181 system.secondary_stack.ss_init
20408 @end smallexample
20409
20410 @noindent
20411 Note that the GNAT run time contains itself a certain number of
20412 allocations that have no  corresponding deallocation,
20413 as shown here for root #2 and root
20414 #3. This is a normal behavior when the number of non-freed allocations
20415 is one, it allocates dynamic data structures that the run time needs for
20416 the complete lifetime of the program. Note also that there is only one
20417 allocation root in the user program with a single line back trace:
20418 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20419 program shows that 'My_Alloc' is called at 2 different points in the
20420 source (line 21 and line 24). If those two allocation roots need to be
20421 distinguished, the backtrace depth parameter can be used:
20422
20423 @smallexample
20424 $ gnatmem 3 test_gm
20425 @end smallexample
20426
20427 @noindent
20428 which will give the following output:
20429
20430 @smallexample
20431 Global information
20432 ------------------
20433    Total number of allocations        :  18
20434    Total number of deallocations      :   5
20435    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20436    High Water Mark                    :  56.90 Kilobytes
20437
20438 Allocation Root # 1
20439 -------------------
20440  Number of non freed allocations    :  10
20441  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20442  High Water Mark                    :  42.97 Kilobytes
20443  Backtrace                          :
20444    test_gm.adb:11 test_gm.my_alloc
20445    test_gm.adb:24 test_gm
20446    b_test_gm.c:52 main
20447
20448 Allocation Root # 2
20449 -------------------
20450  Number of non freed allocations    :   1
20451  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20452  High Water Mark                    :  10.02 Kilobytes
20453  Backtrace                          :
20454    s-secsta.adb:81  system.secondary_stack.ss_init
20455    s-secsta.adb:283 <system__secondary_stack___elabb>
20456    b_test_gm.c:33   adainit
20457
20458 Allocation Root # 3
20459 -------------------
20460  Number of non freed allocations    :   1
20461  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20462  High Water Mark                    :   3.91 Kilobytes
20463  Backtrace                          :
20464    test_gm.adb:11 test_gm.my_alloc
20465    test_gm.adb:21 test_gm
20466    b_test_gm.c:52 main
20467
20468 Allocation Root # 4
20469 -------------------
20470  Number of non freed allocations    :   1
20471  Final Water Mark (non freed mem)   :  12 Bytes
20472  High Water Mark                    :  12 Bytes
20473  Backtrace                          :
20474    s-secsta.adb:181 system.secondary_stack.ss_init
20475    s-secsta.adb:283 <system__secondary_stack___elabb>
20476    b_test_gm.c:33   adainit
20477 @end smallexample
20478
20479 @noindent
20480 The allocation root #1 of the first example has been split in 2 roots #1
20481 and #3 thanks to the more precise associated backtrace.
20482
20483 @end ifclear
20484
20485 @node Stack Related Facilities
20486 @chapter Stack Related Facilities
20487
20488 @noindent
20489 This chapter describes some useful tools associated with stack
20490 checking and analysis. In
20491 particular, it deals with dynamic and static stack usage measurements.
20492
20493 @menu
20494 * Stack Overflow Checking::
20495 * Static Stack Usage Analysis::
20496 * Dynamic Stack Usage Analysis::
20497 @end menu
20498
20499 @node Stack Overflow Checking
20500 @section Stack Overflow Checking
20501 @cindex Stack Overflow Checking
20502 @cindex -fstack-check
20503
20504 @noindent
20505 For most operating systems, @command{gcc} does not perform stack overflow
20506 checking by default. This means that if the main environment task or
20507 some other task exceeds the available stack space, then unpredictable
20508 behavior will occur. Most native systems offer some level of protection by
20509 adding a guard page at the end of each task stack. This mechanism is usually
20510 not enough for dealing properly with stack overflow situations because
20511 a large local variable could ``jump'' above the guard page.
20512 Furthermore, when the
20513 guard page is hit, there may not be any space left on the stack for executing
20514 the exception propagation code. Enabling stack checking avoids
20515 such situations.
20516
20517 To activate stack checking, compile all units with the gcc option
20518 @option{-fstack-check}. For example:
20519
20520 @smallexample
20521 gcc -c -fstack-check package1.adb
20522 @end smallexample
20523
20524 @noindent
20525 Units compiled with this option will generate extra instructions to check
20526 that any use of the stack (for procedure calls or for declaring local
20527 variables in declare blocks) does not exceed the available stack space.
20528 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20529
20530 For declared tasks, the stack size is controlled by the size
20531 given in an applicable @code{Storage_Size} pragma or by the value specified
20532 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20533 the default size as defined in the GNAT runtime otherwise.
20534
20535 For the environment task, the stack size depends on
20536 system defaults and is unknown to the compiler. Stack checking
20537 may still work correctly if a fixed
20538 size stack is allocated, but this cannot be guaranteed.
20539 @ifclear vms
20540 To ensure that a clean exception is signalled for stack
20541 overflow, set the environment variable
20542 @env{GNAT_STACK_LIMIT} to indicate the maximum
20543 stack area that can be used, as in:
20544 @cindex GNAT_STACK_LIMIT
20545
20546 @smallexample
20547 SET GNAT_STACK_LIMIT 1600
20548 @end smallexample
20549
20550 @noindent
20551 The limit is given in kilobytes, so the above declaration would
20552 set the stack limit of the environment task to 1.6 megabytes.
20553 Note that the only purpose of this usage is to limit the amount
20554 of stack used by the environment task. If it is necessary to
20555 increase the amount of stack for the environment task, then this
20556 is an operating systems issue, and must be addressed with the
20557 appropriate operating systems commands.
20558 @end ifclear
20559 @ifset vms
20560 To have a fixed size stack in the environment task, the stack must be put
20561 in the P0 address space and its size specified.  Use these switches to
20562 create a p0 image:
20563
20564 @smallexample
20565 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20566 @end smallexample
20567
20568 @noindent
20569 The quotes are required to keep case.  The number after @samp{STACK=} is the
20570 size of the environmental task stack in pagelets (512 bytes).  In this example
20571 the stack size is about 2 megabytes.
20572
20573 @noindent
20574 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20575 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20576 more details about the @option{/p0image} qualifier and the @option{stack}
20577 option.
20578 @end ifset
20579
20580 @node Static Stack Usage Analysis
20581 @section Static Stack Usage Analysis
20582 @cindex Static Stack Usage Analysis
20583 @cindex -fstack-usage
20584
20585 @noindent
20586 A unit compiled with @option{-fstack-usage} will generate an extra file
20587 that specifies
20588 the maximum amount of stack used, on a per-function basis.
20589 The file has the same
20590 basename as the target object file with a @file{.su} extension.
20591 Each line of this file is made up of three fields:
20592
20593 @itemize
20594 @item
20595 The name of the function.
20596 @item
20597 A number of bytes.
20598 @item
20599 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20600 @end itemize
20601
20602 The second field corresponds to the size of the known part of the function
20603 frame.
20604
20605 The qualifier @code{static} means that the function frame size
20606 is purely static.
20607 It usually means that all local variables have a static size.
20608 In this case, the second field is a reliable measure of the function stack
20609 utilization.
20610
20611 The qualifier @code{dynamic} means that the function frame size is not static.
20612 It happens mainly when some local variables have a dynamic size. When this
20613 qualifier appears alone, the second field is not a reliable measure
20614 of the function stack analysis. When it is qualified with  @code{bounded}, it
20615 means that the second field is a reliable maximum of the function stack
20616 utilization.
20617
20618 @node Dynamic Stack Usage Analysis
20619 @section Dynamic Stack Usage Analysis
20620
20621 @noindent
20622 It is possible to measure the maximum amount of stack used by a task, by
20623 adding a switch to @command{gnatbind}, as:
20624
20625 @smallexample
20626 $ gnatbind -u0 file
20627 @end smallexample
20628
20629 @noindent
20630 With this option, at each task termination, its stack usage is  output on
20631 @file{stderr}.
20632 It is not always convenient to output the stack usage when the program
20633 is still running. Hence, it is possible to delay this output until program
20634 termination. for a given number of tasks specified as the argument of the
20635 @option{-u} option. For instance:
20636
20637 @smallexample
20638 $ gnatbind -u100 file
20639 @end smallexample
20640
20641 @noindent
20642 will buffer the stack usage information of the first 100 tasks to terminate and
20643 output this info at program termination. Results are displayed in four
20644 columns:
20645
20646 @noindent
20647 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20648
20649 @noindent
20650 where:
20651
20652 @table @emph
20653 @item Index
20654 is a number associated with each task.
20655
20656 @item Task Name
20657 is the name of the task analyzed.
20658
20659 @item Stack Size
20660 is the maximum size for the stack.
20661
20662 @item Stack Usage
20663 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20664 is not entirely analyzed, and it's not possible to know exactly how
20665 much has actually been used. The report thus contains the theoretical stack usage
20666 (Value) and the possible variation (Variation) around this value.
20667
20668 @end table
20669
20670 @noindent
20671 The environment task stack, e.g., the stack that contains the main unit, is
20672 only processed when the environment variable GNAT_STACK_LIMIT is set.
20673
20674
20675 @c *********************************
20676 @c *            GNATCHECK          *
20677 @c *********************************
20678 @node Verifying Properties Using gnatcheck
20679 @chapter Verifying Properties Using @command{gnatcheck}
20680 @findex gnatcheck
20681 @cindex @command{gnatcheck}
20682
20683 @noindent
20684 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20685 of Ada source files according to a given set of semantic rules.
20686 @cindex ASIS
20687
20688 In order to check compliance with a given rule, @command{gnatcheck} has to
20689 semantically analyze the Ada sources.
20690 Therefore, checks can only be performed on
20691 legal Ada units. Moreover, when a unit depends semantically upon units located
20692 outside the current directory, the source search path has to be provided when
20693 calling @command{gnatcheck}, either through a specified project file or
20694 through @command{gnatcheck} switches as described below.
20695
20696 A number of rules are predefined in @command{gnatcheck} and are described
20697 later in this chapter.
20698 You can also add new rules, by modifying the @command{gnatcheck} code and
20699 rebuilding the tool. In order to add a simple rule making some local checks,
20700 a small amount of straightforward ASIS-based programming is usually needed.
20701
20702 Project support for @command{gnatcheck} is provided by the GNAT
20703 driver (see @ref{The GNAT Driver and Project Files}).
20704
20705 Invoking @command{gnatcheck} on the command line has the form:
20706
20707 @smallexample
20708 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
20709 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20710 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20711 @c Expanding @ovar macro inline (explanation in macro def comments)
20712 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
20713       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20714       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20715 @end smallexample
20716
20717 @noindent
20718 where
20719 @itemize @bullet
20720 @item
20721 @var{switches} specify the general tool options
20722
20723 @item
20724 Each @var{filename} is the name (including the extension) of a source
20725 file to process. ``Wildcards'' are allowed, and
20726 the file name may contain path information.
20727
20728 @item
20729 Each @var{arg_list_filename} is the name (including the extension) of a text
20730 file containing the names of the source files to process, separated by spaces
20731 or line breaks.
20732
20733 @item
20734 @var{gcc_switches} is a list of switches for
20735 @command{gcc}. They will be passed on to all compiler invocations made by
20736 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20737 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20738 and use the @option{-gnatec} switch to set the configuration file.
20739
20740 @item
20741 @var{rule_options} is a list of options for controlling a set of
20742 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20743 @end itemize
20744
20745 @noindent
20746 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20747 supplied.
20748
20749 @menu
20750 * Format of the Report File::
20751 * General gnatcheck Switches::
20752 * gnatcheck Rule Options::
20753 * Adding the Results of Compiler Checks to gnatcheck Output::
20754 * Project-Wide Checks::
20755 * Rule exemption::
20756 * Predefined Rules::
20757 * Example of gnatcheck Usage::
20758 @end menu
20759
20760 @node Format of the Report File
20761 @section Format of the Report File
20762 @cindex Report file (for @code{gnatcheck})
20763
20764 @noindent
20765 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20766 rule violations.
20767 It also creates a text file  that
20768 contains the complete report of the last gnatcheck run. By default this file
20769 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20770 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20771 name and/or location of the report file. This report contains:
20772 @itemize @bullet
20773 @item date and time of @command{gnatcheck} run, the version of
20774 the tool that has generated this report and the full parameters
20775 of the  @command{gnatcheck} invocation;
20776 @item list of enabled rules;
20777 @item total number of detected violations;
20778 @item list of source files where rule violations have been detected;
20779 @item list of source files where no violations have been detected.
20780 @end itemize
20781
20782 @node General gnatcheck Switches
20783 @section General @command{gnatcheck} Switches
20784
20785 @noindent
20786 The following switches control the general @command{gnatcheck} behavior
20787
20788 @table @option
20789 @c !sort!
20790 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20791 @item ^-a^/ALL^
20792 Process all units including those with read-only ALI files such as
20793 those from the GNAT Run-Time library.
20794
20795 @ifclear vms
20796 @ignore
20797 @cindex @option{-d} (@command{gnatcheck})
20798 @item -d
20799 Debug mode
20800 @end ignore
20801
20802 @cindex @option{-dd} (@command{gnatcheck})
20803 @item -dd
20804 Progress indicator mode (for use in GPS).
20805 @end ifclear
20806
20807 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20808 @item ^-h^/HELP^
20809 List the predefined and user-defined rules. For more details see
20810 @ref{Predefined Rules}.
20811
20812 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20813 @item ^-l^/LOCS^
20814 Use full source locations references in the report file. For a construct from
20815 a generic instantiation a full source location is a chain from the location
20816 of this construct in the generic unit to the place where this unit is
20817 instantiated.
20818
20819 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20820 @item ^-log^/LOG^
20821 Duplicate all the output sent to @file{stderr} into a log file. The log file
20822 is named @file{gnatcheck.log} and is located in the current directory.
20823
20824 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20825 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20826 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20827 the range 0@dots{}1000;
20828 the default value is 500. Zero means that there is no limitation on
20829 the number of diagnostic messages to be output.
20830
20831 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20832 @item ^-q^/QUIET^
20833 Quiet mode. All the diagnostics about rule violations are placed in the
20834 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20835
20836 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20837 @item ^-s^/SHORT^
20838 Short format of the report file (no version information, no list of applied
20839 rules, no list of checked sources is included)
20840
20841 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
20842 @item ^--include-file^/INCLUDE_FILE^
20843 Append the content of the specified text file to the report file
20844
20845 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20846 @item ^-t^/TIME^
20847 Print out execution time.
20848
20849 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20850 @item ^-v^/VERBOSE^
20851 Verbose mode; @command{gnatcheck} generates version information and then
20852 a trace of sources being processed.
20853
20854 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20855 @item ^-o ^/OUTPUT=^@var{report_file}
20856 Set name of report file file to @var{report_file} .
20857
20858 @end table
20859
20860 @node gnatcheck Rule Options
20861 @section @command{gnatcheck} Rule Options
20862
20863 @noindent
20864 The following options control the processing performed by
20865 @command{gnatcheck}.
20866
20867 @table @option
20868 @cindex @option{+ALL} (@command{gnatcheck})
20869 @item +ALL
20870 Turn all the rule checks ON.
20871
20872 @cindex @option{-ALL} (@command{gnatcheck})
20873 @item -ALL
20874 Turn all the rule checks OFF.
20875
20876 @cindex @option{+R} (@command{gnatcheck})
20877 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20878 Turn on the check for a specified rule with the specified parameter, if any.
20879 @var{rule_id} must be the identifier of one of the currently implemented rules
20880 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20881 are not case-sensitive. The @var{param} item must
20882 be a string representing a valid parameter(s) for the specified rule.
20883 If it contains any space characters then this string must be enclosed in
20884 quotation marks.
20885
20886 @cindex @option{-R} (@command{gnatcheck})
20887 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20888 Turn off the check for a specified rule with the specified parameter, if any.
20889
20890 @cindex @option{-from} (@command{gnatcheck})
20891 @item -from=@var{rule_option_filename}
20892 Read the rule options from the text file @var{rule_option_filename}, referred
20893 to as a ``coding standard file'' below.
20894
20895 @end table
20896
20897 @noindent
20898 The default behavior is that all the rule checks are disabled.
20899
20900 A coding standard file is a text file that contains a set of rule options
20901 described above.
20902 @cindex Coding standard file (for @code{gnatcheck})
20903 The file may contain empty lines and Ada-style comments (comment
20904 lines and end-of-line comments). There can be several rule options on a
20905 single line (separated by a space).
20906
20907 A coding standard file may reference other coding standard files by including
20908 more @option{-from=@var{rule_option_filename}}
20909 options, each such option being replaced with the content of the
20910 corresponding coding standard file during processing. In case a
20911 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20912 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20913 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20914 processing fails with an error message.
20915
20916
20917 @node Adding the Results of Compiler Checks to gnatcheck Output
20918 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20919
20920 @noindent
20921 The @command{gnatcheck} tool can include in the generated diagnostic messages
20922 and in
20923 the report file the results of the checks performed by the compiler. Though
20924 disabled by default, this effect may be obtained by using @option{+R} with
20925 the following rule identifiers and parameters:
20926
20927 @table @option
20928 @item Restrictions
20929 To record restrictions violations (which are performed by the compiler if the
20930 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20931 use the @code{Restrictions} rule
20932 with the same parameters as pragma
20933 @code{Restrictions} or @code{Restriction_Warnings}.
20934
20935 @item Style_Checks
20936 To record compiler style checks (@pxref{Style Checking}), use the
20937 @code{Style_Checks} rule.
20938 This rule takes a parameter in one of the following forms:
20939 @itemize
20940 @item
20941 @code{All_Checks},
20942 which enables the standard style checks corresponding to the @option{-gnatyy}
20943 GNAT style check option, or
20944
20945 @item
20946 a string with the same
20947 structure and semantics as the @code{string_LITERAL} parameter of the
20948 GNAT pragma @code{Style_Checks}
20949 (for further information about this pragma,
20950 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20951 @end itemize
20952
20953 @noindent
20954 For example, the
20955 @code{+RStyle_Checks:O} rule option activates
20956 the compiler style check that corresponds to
20957 @code{-gnatyO} style check option.
20958
20959 @item Warnings
20960 To record compiler warnings (@pxref{Warning Message Control}), use the
20961 @code{Warnings} rule with a parameter that is a valid
20962 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20963 (for further information about this pragma,
20964 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20965 Note that in case of gnatcheck
20966 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20967 all the specific warnings, but not suppresses the warning mode,
20968 and 'e' parameter, corresponding to @option{-gnatwe} that means
20969 "treat warnings as errors", does not have any effect.
20970
20971 @end table
20972
20973 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20974 option with the corresponding restriction name as a parameter. @code{-R} is
20975 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20976 warnings and style checks, use the corresponding warning and style options.
20977
20978 @node Project-Wide Checks
20979 @section Project-Wide Checks
20980 @cindex Project-wide checks (for @command{gnatcheck})
20981
20982 @noindent
20983 In order to perform checks on all units of a given project, you can use
20984 the GNAT driver along with the @option{-P} option:
20985 @smallexample
20986    gnat check -Pproj -rules -from=my_rules
20987 @end smallexample
20988
20989 @noindent
20990 If the project @code{proj} depends upon other projects, you can perform
20991 checks on the project closure using the @option{-U} option:
20992 @smallexample
20993    gnat check -Pproj -U -rules -from=my_rules
20994 @end smallexample
20995
20996 @noindent
20997 Finally, if not all the units are relevant to a particular main
20998 program in the project closure, you can perform checks for the set
20999 of units needed to create a given main program (unit closure) using
21000 the @option{-U} option followed by the name of the main unit:
21001 @smallexample
21002    gnat check -Pproj -U main -rules -from=my_rules
21003 @end smallexample
21004
21005
21006 @node Rule exemption
21007 @section Rule exemption
21008 @cindex Rule exemption (for @command{gnatcheck})
21009
21010 @noindent
21011 One of the most useful applications of @command{gnatcheck} is to
21012 automate the enforcement of project-specific coding standards,
21013 for example in safety-critical systems where particular features
21014 must be restricted in order to simplify the certification effort.
21015 However, it may sometimes be appropriate to violate a coding standard rule,
21016 and in such cases the rationale for the violation should be provided
21017 in the source program itself so that the individuals
21018 reviewing or maintaining the program can immediately understand the intent.
21019
21020 The @command{gnatcheck} tool supports this practice with the notion of
21021 a ``rule exemption'' covering a specific source code section. Normally
21022 rule violation messages are issued both on @file{stderr}
21023 and in a report file. In contrast, exempted violations are not listed on
21024 @file{stderr}; thus users invoking @command{gnatcheck} interactively
21025 (e.g. in its GPS interface) do not need to pay attention to known and
21026 justified violations. However, exempted violations along with their
21027 justification are documented in a special section of the report file that
21028 @command{gnatcheck} generates.
21029
21030 @menu
21031 * Using pragma Annotate to Control Rule Exemption::
21032 * gnatcheck Annotations Rules::
21033 @end menu
21034
21035 @node Using pragma Annotate to Control Rule Exemption
21036 @subsection Using pragma @code{Annotate} to Control Rule Exemption
21037 @cindex Using pragma Annotate to control rule exemption
21038
21039 @noindent
21040 Rule exemption is controlled by pragma @code{Annotate} when its first
21041 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21042 exemption control annotations is as follows:
21043
21044 @smallexample @c ada
21045 @group
21046 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21047
21048 @i{exemption_control} ::= Exempt_On | Exempt_Off
21049
21050 @i{Rule_Name}         ::= string_literal
21051
21052 @i{justification}     ::= string_literal
21053 @end group
21054 @end smallexample
21055
21056 @noindent
21057 When a @command{gnatcheck} annotation has more then four arguments,
21058 @command{gnatcheck} issues a warning and ignores the additional arguments.
21059 If the additional arguments do not follow the syntax above,
21060 @command{gnatcheck} emits a warning and ignores the annotation.
21061
21062 The @i{@code{Rule_Name}} argument should be the name of some existing
21063 @command{gnatcheck} rule.
21064 Otherwise a warning message is generated and the pragma is
21065 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21066 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21067
21068 A source code section where an exemption is active for a given rule is
21069 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21070
21071 @smallexample @c ada
21072 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
21073 -- source code section
21074 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
21075 @end smallexample
21076
21077
21078 @node gnatcheck Annotations Rules
21079 @subsection @command{gnatcheck} Annotations Rules
21080 @cindex @command{gnatcheck} annotations rules
21081
21082 @itemize @bullet
21083
21084 @item
21085 An ``Exempt_Off'' annotation can only appear after a corresponding
21086 ``Exempt_On'' annotation.
21087
21088 @item
21089 Exempted source code sections are only based on the source location of the
21090 annotations. Any source construct between the two
21091 annotations is part of the exempted source code section.
21092
21093 @item
21094 Exempted source code sections for different rules are independent. They can
21095 be nested or intersect with one another without limitation.
21096 Creating nested or intersecting source code sections for the same rule is
21097 not allowed.
21098
21099 @item
21100 Malformed exempted source code sections are reported by a warning, and
21101 the corresponding rule exemptions are ignored.
21102
21103 @item
21104 When an exempted source code section does not contain at least one violation
21105 of the exempted rule, a warning is emitted on @file{stderr}.
21106
21107 @item
21108 If an ``Exempt_On'' annotation pragma does not have a matching
21109 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21110 exemption for the given rule is ignored and a warning is issued.
21111 @end itemize
21112
21113
21114 @node Predefined Rules
21115 @section Predefined Rules
21116 @cindex Predefined rules (for @command{gnatcheck})
21117
21118 @ignore
21119 @c (Jan 2007) Since the global rules are still under development and are not
21120 @c documented, there is no point in explaining the difference between
21121 @c global and local rules
21122 @noindent
21123 A rule in @command{gnatcheck} is either local or global.
21124 A @emph{local rule} is a rule that applies to a well-defined section
21125 of a program and that can be checked by analyzing only this section.
21126 A @emph{global rule} requires analysis of some global properties of the
21127 whole program (mostly related to the program call graph).
21128 As of @value{NOW}, the implementation of global rules should be
21129 considered to be at a preliminary stage. You can use the
21130 @option{+GLOBAL} option to enable all the global rules, and the
21131 @option{-GLOBAL} rule option to disable all the global rules.
21132
21133 All the global rules in the list below are
21134 so indicated by marking them ``GLOBAL''.
21135 This +GLOBAL and -GLOBAL options are not
21136 included in the list of gnatcheck options above, because at the moment they
21137 are considered as a temporary debug options.
21138
21139 @command{gnatcheck} performs rule checks for generic
21140 instances only for global rules.  This limitation may be relaxed in a later
21141 release.
21142 @end ignore
21143
21144 @noindent
21145 The predefined rules implemented in @command{gnatcheck}
21146 are described in a companion document,
21147 @cite{GNATcheck Reference Manual -- Predefined Rules}.
21148 The rule identifier is
21149 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
21150 switches.
21151
21152
21153 @node Example of gnatcheck Usage
21154 @section Example of @command{gnatcheck} Usage
21155
21156 @noindent
21157 Here is a simple example. Suppose that in the current directory we have a
21158 project file named @file{gnatcheck_example.gpr} with the following content:
21159
21160 @smallexample @c projectfile
21161 project Gnatcheck_Example is
21162
21163    for Source_Dirs use ("src");
21164    for Object_Dir use "obj";
21165    for Main use ("main.adb");
21166
21167    package Check is
21168       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
21169    end Check;
21170
21171 end Gnatcheck_Example;
21172 @end smallexample
21173
21174 @noindent
21175 And the file named @file{coding_standard} is also located in the current
21176 directory and has the following content:
21177
21178 @smallexample
21179 -----------------------------------------------------
21180 -- This is a sample gnatcheck coding standard file --
21181 -----------------------------------------------------
21182
21183 --  First, turning on rules, that are directly implemented in gnatcheck
21184 +RAbstract_Type_Declarations
21185 +RAnonymous_Arrays
21186 +RLocal_Packages
21187 +RFloat_Equality_Checks
21188 +REXIT_Statements_With_No_Loop_Name
21189
21190 --  Then, activating compiler checks of interest:
21191 +RStyle_Checks:e
21192 --  This style check checks if a unit name is present on END keyword that
21193 --  is the end of the unit declaration
21194 @end smallexample
21195
21196 @noindent
21197 And the subdirectory @file{src} contains the following Ada sources:
21198
21199 @file{pack.ads}:
21200
21201 @smallexample @c ada
21202 package Pack is
21203    type T is abstract tagged private;
21204    procedure P (X : T) is abstract;
21205
21206    package Inner is
21207       type My_Float is digits 8;
21208       function Is_Equal (L, R : My_Float) return Boolean;
21209    end Inner;
21210 private
21211    type T is abstract tagged null record;
21212 end;
21213 @end smallexample
21214
21215 @noindent
21216 @file{pack.adb}:
21217
21218 @smallexample @c ada
21219 package body Pack is
21220    package body Inner is
21221       function Is_Equal (L, R : My_Float) return Boolean is
21222       begin
21223          return L = R;
21224       end;
21225    end Inner;
21226 end Pack;
21227 @end smallexample
21228
21229 @noindent
21230 and @file{main.adb}
21231
21232 @smallexample @c ada
21233 with Pack; use Pack;
21234 procedure Main is
21235
21236    pragma Annotate
21237      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
21238    Float_Array : array (1 .. 10) of Inner.My_Float;
21239    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
21240
21241    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
21242
21243    use Inner;
21244
21245    B : Boolean := False;
21246
21247 begin
21248    for J in Float_Array'Range loop
21249       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
21250          B := True;
21251          exit;
21252       end if;
21253    end loop;
21254 end Main;
21255 @end smallexample
21256
21257 @noindent
21258 And suppose we call @command{gnatcheck} from the current directory using
21259 the @command{gnat} driver:
21260
21261 @smallexample
21262    gnat check -Pgnatcheck_example.gpr
21263 @end smallexample
21264
21265 @noindent
21266 As a result, @command{gnatcheck} is called to check all the files from the
21267 project @file{gnatcheck_example.gpr} using the coding standard defined by
21268 the file @file{coding_standard}. As the result, the @command{gnatcheck}
21269 report file named @file{gnatcheck.out} will be created in the current
21270 directory, and it will have the following content:
21271
21272 @smallexample
21273 RULE CHECKING REPORT
21274
21275 1. OVERVIEW
21276
21277 Date and time of execution: 2009.10.28 14:17
21278 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
21279 Command line:
21280
21281 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
21282
21283 Coding standard (applied rules):
21284    Abstract_Type_Declarations
21285    Anonymous_Arrays
21286    EXIT_Statements_With_No_Loop_Name
21287    Float_Equality_Checks
21288    Local_Packages
21289
21290    Compiler style checks: -gnatye
21291
21292 Number of coding standard violations: 6
21293 Number of exempted coding standard violations: 1
21294
21295 2. DETECTED RULE VIOLATIONS
21296
21297 2.1. NON-EXEMPTED VIOLATIONS
21298
21299 Source files with non-exempted violations
21300    pack.ads
21301    pack.adb
21302    main.adb
21303
21304 List of violations grouped by files, and ordered by increasing source location:
21305
21306 pack.ads:2:4: declaration of abstract type
21307 pack.ads:5:4: declaration of local package
21308 pack.ads:10:30: declaration of abstract type
21309 pack.ads:11:1: (style) "end Pack" required
21310 pack.adb:5:19: use of equality operation for float values
21311 pack.adb:6:7: (style) "end Is_Equal" required
21312 main.adb:9:26: anonymous array type
21313 main.adb:19:10: exit statement with no loop name
21314
21315 2.2. EXEMPTED VIOLATIONS
21316
21317 Source files with exempted violations
21318    main.adb
21319
21320 List of violations grouped by files, and ordered by increasing source location:
21321
21322 main.adb:6:18: anonymous array type
21323    (this one is fine)
21324
21325 2.3. SOURCE FILES WITH NO VIOLATION
21326
21327    No files without violations
21328
21329 END OF REPORT
21330 @end smallexample
21331
21332
21333 @c *********************************
21334 @node Creating Sample Bodies Using gnatstub
21335 @chapter Creating Sample Bodies Using @command{gnatstub}
21336 @findex gnatstub
21337
21338 @noindent
21339 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
21340 for library unit declarations.
21341
21342 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
21343 driver (see @ref{The GNAT Driver and Project Files}).
21344
21345 To create a body stub, @command{gnatstub} has to compile the library
21346 unit declaration. Therefore, bodies can be created only for legal
21347 library units. Moreover, if a library unit depends semantically upon
21348 units located outside the current directory, you have to provide
21349 the source search path when calling @command{gnatstub}, see the description
21350 of @command{gnatstub} switches below.
21351
21352 By default, all the program unit body stubs generated by @code{gnatstub}
21353 raise the predefined @code{Program_Error} exception, which will catch
21354 accidental calls of generated stubs. This behavior can be changed with
21355 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
21356
21357 @menu
21358 * Running gnatstub::
21359 * Switches for gnatstub::
21360 @end menu
21361
21362 @node Running gnatstub
21363 @section Running @command{gnatstub}
21364
21365 @noindent
21366 @command{gnatstub} has the command-line interface of the form
21367
21368 @smallexample
21369 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
21370 @c Expanding @ovar macro inline (explanation in macro def comments)
21371 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
21372 @end smallexample
21373
21374 @noindent
21375 where
21376 @table @var
21377 @item filename
21378 is the name of the source file that contains a library unit declaration
21379 for which a body must be created. The file name may contain the path
21380 information.
21381 The file name does not have to follow the GNAT file name conventions. If the
21382 name
21383 does not follow GNAT file naming conventions, the name of the body file must
21384 be provided
21385 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
21386 If the file name follows the GNAT file naming
21387 conventions and the name of the body file is not provided,
21388 @command{gnatstub}
21389 creates the name
21390 of the body file from the argument file name by replacing the @file{.ads}
21391 suffix
21392 with the @file{.adb} suffix.
21393
21394 @item directory
21395 indicates the directory in which the body stub is to be placed (the default
21396 is the
21397 current directory)
21398
21399 @item @samp{@var{gcc_switches}} is a list of switches for
21400 @command{gcc}. They will be passed on to all compiler invocations made by
21401 @command{gnatelim} to generate the ASIS trees. Here you can provide
21402 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
21403 use the @option{-gnatec} switch to set the configuration file etc.
21404
21405 @item switches
21406 is an optional sequence of switches as described in the next section
21407 @end table
21408
21409 @node Switches for gnatstub
21410 @section Switches for @command{gnatstub}
21411
21412 @table @option
21413 @c !sort!
21414
21415 @item ^-f^/FULL^
21416 @cindex @option{^-f^/FULL^} (@command{gnatstub})
21417 If the destination directory already contains a file with the name of the
21418 body file
21419 for the argument spec file, replace it with the generated body stub.
21420
21421 @item ^-hs^/HEADER=SPEC^
21422 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
21423 Put the comment header (i.e., all the comments preceding the
21424 compilation unit) from the source of the library unit declaration
21425 into the body stub.
21426
21427 @item ^-hg^/HEADER=GENERAL^
21428 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
21429 Put a sample comment header into the body stub.
21430
21431 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
21432 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
21433 Use the content of the file as the comment header for a generated body stub.
21434
21435 @ifclear vms
21436 @item -IDIR
21437 @cindex @option{-IDIR} (@command{gnatstub})
21438 @itemx -I-
21439 @cindex @option{-I-} (@command{gnatstub})
21440 @end ifclear
21441 @ifset vms
21442 @item /NOCURRENT_DIRECTORY
21443 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
21444 @end ifset
21445 ^These switches have ^This switch has^ the same meaning as in calls to
21446 @command{gcc}.
21447 ^They define ^It defines ^ the source search path in the call to
21448 @command{gcc} issued
21449 by @command{gnatstub} to compile an argument source file.
21450
21451 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
21452 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
21453 This switch has the same meaning as in calls to @command{gcc}.
21454 It defines the additional configuration file to be passed to the call to
21455 @command{gcc} issued
21456 by @command{gnatstub} to compile an argument source file.
21457
21458 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
21459 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
21460 (@var{n} is a non-negative integer). Set the maximum line length in the
21461 body stub to @var{n}; the default is 79. The maximum value that can be
21462 specified is 32767. Note that in the special case of configuration
21463 pragma files, the maximum is always 32767 regardless of whether or
21464 not this switch appears.
21465
21466 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
21467 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
21468 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
21469 the generated body sample to @var{n}.
21470 The default indentation is 3.
21471
21472 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
21473 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
21474 Order local bodies alphabetically. (By default local bodies are ordered
21475 in the same way as the corresponding local specs in the argument spec file.)
21476
21477 @item ^-i^/INDENTATION=^@var{n}
21478 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
21479 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
21480
21481 @item ^-k^/TREE_FILE=SAVE^
21482 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
21483 Do not remove the tree file (i.e., the snapshot of the compiler internal
21484 structures used by @command{gnatstub}) after creating the body stub.
21485
21486 @item ^-l^/LINE_LENGTH=^@var{n}
21487 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
21488 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
21489
21490 @item ^--no-exception^/NO_EXCEPTION^
21491 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
21492 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
21493 This is not always possible for function stubs.
21494
21495 @item ^--no-local-header^/NO_LOCAL_HEADER^
21496 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
21497 Do not place local comment header with unit name before body stub for a
21498 unit.
21499
21500 @item ^-o ^/BODY=^@var{body-name}
21501 @cindex @option{^-o^/BODY^} (@command{gnatstub})
21502 Body file name.  This should be set if the argument file name does not
21503 follow
21504 the GNAT file naming
21505 conventions. If this switch is omitted the default name for the body will be
21506 obtained
21507 from the argument file name according to the GNAT file naming conventions.
21508
21509 @item ^-q^/QUIET^
21510 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
21511 Quiet mode: do not generate a confirmation when a body is
21512 successfully created, and do not generate a message when a body is not
21513 required for an
21514 argument unit.
21515
21516 @item ^-r^/TREE_FILE=REUSE^
21517 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
21518 Reuse the tree file (if it exists) instead of creating it.  Instead of
21519 creating the tree file for the library unit declaration, @command{gnatstub}
21520 tries to find it in the current directory and use it for creating
21521 a body. If the tree file is not found, no body is created. This option
21522 also implies @option{^-k^/SAVE^}, whether or not
21523 the latter is set explicitly.
21524
21525 @item ^-t^/TREE_FILE=OVERWRITE^
21526 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
21527 Overwrite the existing tree file.  If the current directory already
21528 contains the file which, according to the GNAT file naming rules should
21529 be considered as a tree file for the argument source file,
21530 @command{gnatstub}
21531 will refuse to create the tree file needed to create a sample body
21532 unless this option is set.
21533
21534 @item ^-v^/VERBOSE^
21535 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
21536 Verbose mode: generate version information.
21537
21538 @end table
21539
21540 @c *********************************
21541 @node Generating Ada Bindings for C and C++ headers
21542 @chapter Generating Ada Bindings for C and C++ headers
21543 @findex binding
21544
21545 @noindent
21546 GNAT now comes with a binding generator for C and C++ headers which is
21547 intended to do 95% of the tedious work of generating Ada specs from C
21548 or C++ header files.
21549
21550 Note that this capability is not intended to generate 100% correct Ada specs,
21551 and will is some cases require manual adjustments, although it can often
21552 be used out of the box in practice.
21553
21554 Some of the known limitations include:
21555
21556 @itemize @bullet
21557 @item only very simple character constant macros are translated into Ada
21558 constants. Function macros (macros with arguments) are partially translated
21559 as comments, to be completed manually if needed.
21560 @item some extensions (e.g. vector types) are not supported
21561 @item pointers to pointers or complex structures are mapped to System.Address
21562 @end itemize
21563
21564 The code generated is using the Ada 2005 syntax, which makes it
21565 easier to interface with other languages than previous versions of Ada.
21566
21567 @menu
21568 * Running the binding generator::
21569 * Generating bindings for C++ headers::
21570 * Switches::
21571 @end menu
21572
21573 @node Running the binding generator
21574 @section Running the binding generator
21575
21576 @noindent
21577 The binding generator is part of the @command{gcc} compiler and can be
21578 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
21579 spec files for the header files specified on the command line, and all
21580 header files needed by these files transitivitely. For example:
21581
21582 @smallexample
21583 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
21584 $ gcc -c -gnat05 *.ads
21585 @end smallexample
21586
21587 will generate, under GNU/Linux, the following files: @file{time_h.ads},
21588 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
21589 correspond to the files @file{/usr/include/time.h},
21590 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
21591 mode these Ada specs.
21592
21593 The @code{-C} switch tells @command{gcc} to extract comments from headers,
21594 and will attempt to generate corresponding Ada comments.
21595
21596 If you want to generate a single Ada file and not the transitive closure, you
21597 can use instead the @option{-fdump-ada-spec-slim} switch.
21598
21599 Note that we recommend when possible to use the @command{g++} driver to
21600 generate bindings, even for most C headers, since this will in general
21601 generate better Ada specs. For generating bindings for C++ headers, it is
21602 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
21603 is equivalent in this case. If @command{g++} cannot work on your C headers
21604 because of incompatibilities between C and C++, then you can fallback to
21605 @command{gcc} instead.
21606
21607 For an example of better bindings generated from the C++ front-end,
21608 the name of the parameters (when available) are actually ignored by the C
21609 front-end. Consider the following C header:
21610
21611 @smallexample
21612 extern void foo (int variable);
21613 @end smallexample
21614
21615 with the C front-end, @code{variable} is ignored, and the above is handled as:
21616
21617 @smallexample
21618 extern void foo (int);
21619 @end smallexample
21620
21621 generating a generic:
21622
21623 @smallexample
21624 procedure foo (param1 : int);
21625 @end smallexample
21626
21627 with the C++ front-end, the name is available, and we generate:
21628
21629 @smallexample
21630 procedure foo (variable : int);
21631 @end smallexample
21632
21633 In some cases, the generated bindings will be more complete or more meaningful
21634 when defining some macros, which you can do via the @option{-D} switch. This
21635 is for example the case with @file{Xlib.h} under GNU/Linux:
21636
21637 @smallexample
21638 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
21639 @end smallexample
21640
21641 The above will generate more complete bindings than a straight call without
21642 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
21643
21644 In other cases, it is not possible to parse a header file in a stand alone
21645 manner, because other include files need to be included first. In this
21646 case, the solution is to create a small header file including the needed
21647 @code{#include} and possible @code{#define} directives. For example, to
21648 generate Ada bindings for @file{readline/readline.h}, you need to first
21649 include @file{stdio.h}, so you can create a file with the following two
21650 lines in e.g. @file{readline1.h}:
21651
21652 @smallexample
21653 #include <stdio.h>
21654 #include <readline/readline.h>
21655 @end smallexample
21656
21657 and then generate Ada bindings from this file:
21658
21659 @smallexample
21660 $ g++ -c -fdump-ada-spec readline1.h
21661 @end smallexample
21662
21663 @node Generating bindings for C++ headers
21664 @section Generating bindings for C++ headers
21665
21666 @noindent
21667 Generating bindings for C++ headers is done using the same options, always
21668 with the @command{g++} compiler.
21669
21670 In this mode, C++ classes will be mapped to Ada tagged types, constructors
21671 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
21672 multiple inheritance of abstract classes will be mapped to Ada interfaces
21673 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
21674 information on interfacing to C++).
21675
21676 For example, given the following C++ header file:
21677
21678 @smallexample
21679 @group
21680 @cartouche
21681 class Carnivore @{
21682 public:
21683    virtual int Number_Of_Teeth () = 0;
21684 @};
21685
21686 class Domestic @{
21687 public:
21688    virtual void Set_Owner (char* Name) = 0;
21689 @};
21690
21691 class Animal @{
21692 public:
21693   int Age_Count;
21694   virtual void Set_Age (int New_Age);
21695 @};
21696
21697 class Dog : Animal, Carnivore, Domestic @{
21698  public:
21699   int  Tooth_Count;
21700   char *Owner;
21701
21702   virtual int  Number_Of_Teeth ();
21703   virtual void Set_Owner (char* Name);
21704
21705   Dog();
21706 @};
21707 @end cartouche
21708 @end group
21709 @end smallexample
21710
21711 The corresponding Ada code is generated:
21712
21713 @smallexample @c ada
21714 @group
21715 @cartouche
21716   package Class_Carnivore is
21717     type Carnivore is limited interface;
21718     pragma Import (CPP, Carnivore);
21719
21720     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
21721   end;
21722   use Class_Carnivore;
21723
21724   package Class_Domestic is
21725     type Domestic is limited interface;
21726     pragma Import (CPP, Domestic);
21727
21728     procedure Set_Owner
21729       (this : access Domestic;
21730        Name : Interfaces.C.Strings.chars_ptr) is abstract;
21731   end;
21732   use Class_Domestic;
21733
21734   package Class_Animal is
21735     type Animal is tagged limited record
21736       Age_Count : aliased int;
21737     end record;
21738     pragma Import (CPP, Animal);
21739
21740     procedure Set_Age (this : access Animal; New_Age : int);
21741     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
21742   end;
21743   use Class_Animal;
21744
21745   package Class_Dog is
21746     type Dog is new Animal and Carnivore and Domestic with record
21747       Tooth_Count : aliased int;
21748       Owner : Interfaces.C.Strings.chars_ptr;
21749     end record;
21750     pragma Import (CPP, Dog);
21751
21752     function Number_Of_Teeth (this : access Dog) return int;
21753     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
21754
21755     procedure Set_Owner
21756       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
21757     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
21758
21759     function New_Dog return Dog;
21760     pragma CPP_Constructor (New_Dog);
21761     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
21762   end;
21763   use Class_Dog;
21764 @end cartouche
21765 @end group
21766 @end smallexample
21767
21768 @node Switches
21769 @section Switches
21770
21771 @table @option
21772 @item -fdump-ada-spec
21773 @cindex @option{-fdump-ada-spec} (@command{gcc})
21774 Generate Ada spec files for the given header files transitively (including
21775 all header files that these headers depend upon).
21776
21777 @item -fdump-ada-spec-slim
21778 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
21779 Generate Ada spec files for the header files specified on the command line
21780 only.
21781
21782 @item -C
21783 @cindex @option{-C} (@command{gcc})
21784 Extract comments from headers and generate Ada comments in the Ada spec files.
21785 @end table
21786
21787 @node Other Utility Programs
21788 @chapter Other Utility Programs
21789
21790 @noindent
21791 This chapter discusses some other utility programs available in the Ada
21792 environment.
21793
21794 @menu
21795 * Using Other Utility Programs with GNAT::
21796 * The External Symbol Naming Scheme of GNAT::
21797 * Converting Ada Files to html with gnathtml::
21798 * Installing gnathtml::
21799 @ifset vms
21800 * LSE::
21801 * Profiling::
21802 @end ifset
21803 @end menu
21804
21805 @node Using Other Utility Programs with GNAT
21806 @section Using Other Utility Programs with GNAT
21807
21808 @noindent
21809 The object files generated by GNAT are in standard system format and in
21810 particular the debugging information uses this format. This means
21811 programs generated by GNAT can be used with existing utilities that
21812 depend on these formats.
21813
21814 @ifclear vms
21815 In general, any utility program that works with C will also often work with
21816 Ada programs generated by GNAT. This includes software utilities such as
21817 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
21818 as Purify.
21819 @end ifclear
21820
21821 @node The External Symbol Naming Scheme of GNAT
21822 @section The External Symbol Naming Scheme of GNAT
21823
21824 @noindent
21825 In order to interpret the output from GNAT, when using tools that are
21826 originally intended for use with other languages, it is useful to
21827 understand the conventions used to generate link names from the Ada
21828 entity names.
21829
21830 All link names are in all lowercase letters. With the exception of library
21831 procedure names, the mechanism used is simply to use the full expanded
21832 Ada name with dots replaced by double underscores. For example, suppose
21833 we have the following package spec:
21834
21835 @smallexample @c ada
21836 @group
21837 @cartouche
21838 package QRS is
21839    MN : Integer;
21840 end QRS;
21841 @end cartouche
21842 @end group
21843 @end smallexample
21844
21845 @noindent
21846 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
21847 the corresponding link name is @code{qrs__mn}.
21848 @findex Export
21849 Of course if a @code{pragma Export} is used this may be overridden:
21850
21851 @smallexample @c ada
21852 @group
21853 @cartouche
21854 package Exports is
21855    Var1 : Integer;
21856    pragma Export (Var1, C, External_Name => "var1_name");
21857    Var2 : Integer;
21858    pragma Export (Var2, C, Link_Name => "var2_link_name");
21859 end Exports;
21860 @end cartouche
21861 @end group
21862 @end smallexample
21863
21864 @noindent
21865 In this case, the link name for @var{Var1} is whatever link name the
21866 C compiler would assign for the C function @var{var1_name}. This typically
21867 would be either @var{var1_name} or @var{_var1_name}, depending on operating
21868 system conventions, but other possibilities exist. The link name for
21869 @var{Var2} is @var{var2_link_name}, and this is not operating system
21870 dependent.
21871
21872 @findex _main
21873 One exception occurs for library level procedures. A potential ambiguity
21874 arises between the required name @code{_main} for the C main program,
21875 and the name we would otherwise assign to an Ada library level procedure
21876 called @code{Main} (which might well not be the main program).
21877
21878 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
21879 names. So if we have a library level procedure such as
21880
21881 @smallexample @c ada
21882 @group
21883 @cartouche
21884 procedure Hello (S : String);
21885 @end cartouche
21886 @end group
21887 @end smallexample
21888
21889 @noindent
21890 the external name of this procedure will be @var{_ada_hello}.
21891
21892
21893 @node Converting Ada Files to html with gnathtml
21894 @section Converting Ada Files to HTML with @code{gnathtml}
21895
21896 @noindent
21897 This @code{Perl} script allows Ada source files to be browsed using
21898 standard Web browsers. For installation procedure, see the section
21899 @xref{Installing gnathtml}.
21900
21901 Ada reserved keywords are highlighted in a bold font and Ada comments in
21902 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
21903 switch to suppress the generation of cross-referencing information, user
21904 defined variables and types will appear in a different color; you will
21905 be able to click on any identifier and go to its declaration.
21906
21907 The command line is as follow:
21908 @smallexample
21909 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
21910 @c Expanding @ovar macro inline (explanation in macro def comments)
21911 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
21912 @end smallexample
21913
21914 @noindent
21915 You can pass it as many Ada files as you want. @code{gnathtml} will generate
21916 an html file for every ada file, and a global file called @file{index.htm}.
21917 This file is an index of every identifier defined in the files.
21918
21919 The available ^switches^options^ are the following ones:
21920
21921 @table @option
21922 @item -83
21923 @cindex @option{-83} (@code{gnathtml})
21924 Only the Ada 83 subset of keywords will be highlighted.
21925
21926 @item -cc @var{color}
21927 @cindex @option{-cc} (@code{gnathtml})
21928 This option allows you to change the color used for comments. The default
21929 value is green. The color argument can be any name accepted by html.
21930
21931 @item -d
21932 @cindex @option{-d} (@code{gnathtml})
21933 If the Ada files depend on some other files (for instance through
21934 @code{with} clauses, the latter files will also be converted to html.
21935 Only the files in the user project will be converted to html, not the files
21936 in the run-time library itself.
21937
21938 @item -D
21939 @cindex @option{-D} (@code{gnathtml})
21940 This command is the same as @option{-d} above, but @command{gnathtml} will
21941 also look for files in the run-time library, and generate html files for them.
21942
21943 @item -ext @var{extension}
21944 @cindex @option{-ext} (@code{gnathtml})
21945 This option allows you to change the extension of the generated HTML files.
21946 If you do not specify an extension, it will default to @file{htm}.
21947
21948 @item -f
21949 @cindex @option{-f} (@code{gnathtml})
21950 By default, gnathtml will generate html links only for global entities
21951 ('with'ed units, global variables and types,@dots{}).  If you specify
21952 @option{-f} on the command line, then links will be generated for local
21953 entities too.
21954
21955 @item -l @var{number}
21956 @cindex @option{-l} (@code{gnathtml})
21957 If this ^switch^option^ is provided and @var{number} is not 0, then
21958 @code{gnathtml} will number the html files every @var{number} line.
21959
21960 @item -I @var{dir}
21961 @cindex @option{-I} (@code{gnathtml})
21962 Specify a directory to search for library files (@file{.ALI} files) and
21963 source files. You can provide several -I switches on the command line,
21964 and the directories will be parsed in the order of the command line.
21965
21966 @item -o @var{dir}
21967 @cindex @option{-o} (@code{gnathtml})
21968 Specify the output directory for html files. By default, gnathtml will
21969 saved the generated html files in a subdirectory named @file{html/}.
21970
21971 @item -p @var{file}
21972 @cindex @option{-p} (@code{gnathtml})
21973 If you are using Emacs and the most recent Emacs Ada mode, which provides
21974 a full Integrated Development Environment for compiling, checking,
21975 running and debugging applications, you may use @file{.gpr} files
21976 to give the directories where Emacs can find sources and object files.
21977
21978 Using this ^switch^option^, you can tell gnathtml to use these files.
21979 This allows you to get an html version of your application, even if it
21980 is spread over multiple directories.
21981
21982 @item -sc @var{color}
21983 @cindex @option{-sc} (@code{gnathtml})
21984 This ^switch^option^ allows you to change the color used for symbol
21985 definitions.
21986 The default value is red. The color argument can be any name accepted by html.
21987
21988 @item -t @var{file}
21989 @cindex @option{-t} (@code{gnathtml})
21990 This ^switch^option^ provides the name of a file. This file contains a list of
21991 file names to be converted, and the effect is exactly as though they had
21992 appeared explicitly on the command line. This
21993 is the recommended way to work around the command line length limit on some
21994 systems.
21995
21996 @end table
21997
21998 @node Installing gnathtml
21999 @section Installing @code{gnathtml}
22000
22001 @noindent
22002 @code{Perl} needs to be installed on your machine to run this script.
22003 @code{Perl} is freely available for almost every architecture and
22004 Operating System via the Internet.
22005
22006 On Unix systems, you  may want to modify  the  first line of  the script
22007 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
22008 is. The syntax of this line is:
22009 @smallexample
22010 #!full_path_name_to_perl
22011 @end smallexample
22012
22013 @noindent
22014 Alternatively, you may run the script using the following command line:
22015
22016 @smallexample
22017 @c $ perl gnathtml.pl @ovar{switches} @var{files}
22018 @c Expanding @ovar macro inline (explanation in macro def comments)
22019 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
22020 @end smallexample
22021
22022 @ifset vms
22023 @node LSE
22024 @section LSE
22025 @findex LSE
22026
22027 @noindent
22028 The GNAT distribution provides an Ada 95 template for the HP Language
22029 Sensitive Editor (LSE), a component of DECset. In order to
22030 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22031
22032 @node Profiling
22033 @section Profiling
22034 @findex PCA
22035
22036 @noindent
22037 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22038 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22039 the collection phase with the /DEBUG qualifier.
22040
22041 @smallexample
22042 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
22043 $ DEFINE LIB$DEBUG PCA$COLLECTOR
22044 $ RUN/DEBUG <PROGRAM_NAME>
22045 @end smallexample
22046 @noindent
22047 @end ifset
22048
22049 @ifclear vms
22050 @c ******************************
22051 @node Code Coverage and Profiling
22052 @chapter Code Coverage and Profiling
22053 @cindex Code Coverage
22054 @cindex Profiling
22055
22056 @noindent
22057 This chapter describes how to use @code{gcov} - coverage testing tool - and
22058 @code{gprof} - profiler tool - on your Ada programs.
22059
22060 @menu
22061 * Code Coverage of Ada Programs using gcov::
22062 * Profiling an Ada Program using gprof::
22063 @end menu
22064
22065 @node Code Coverage of Ada Programs using gcov
22066 @section Code Coverage of Ada Programs using gcov
22067 @cindex gcov
22068 @cindex -fprofile-arcs
22069 @cindex -ftest-coverage
22070 @cindex -coverage
22071 @cindex Code Coverage
22072
22073 @noindent
22074 @code{gcov} is a test coverage program: it analyzes the execution of a given
22075 program on selected tests, to help you determine the portions of the program
22076 that are still untested.
22077
22078 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
22079 User's Guide. You can refer to this documentation for a more complete
22080 description.
22081
22082 This chapter provides a quick startup guide, and
22083 details some Gnat-specific features.
22084
22085 @menu
22086 * Quick startup guide::
22087 * Gnat specifics::
22088 @end menu
22089
22090 @node Quick startup guide
22091 @subsection Quick startup guide
22092
22093 In order to perform coverage analysis of a program using @code{gcov}, 3
22094 steps are needed:
22095
22096 @itemize @bullet
22097 @item
22098 Code instrumentation during the compilation process
22099 @item
22100 Execution of the instrumented program
22101 @item
22102 Execution of the @code{gcov} tool to generate the result.
22103 @end itemize
22104
22105 The code instrumentation needed by gcov is created at the object level:
22106 The source code is not modified in any way, because the instrumentation code is
22107 inserted by gcc during the compilation process. To compile your code with code
22108 coverage activated, you need to recompile your whole project using the
22109 switches
22110 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
22111 @code{-fprofile-arcs}.
22112
22113 @smallexample
22114 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
22115    -largs -fprofile-arcs
22116 @end smallexample
22117
22118 This compilation process will create @file{.gcno} files together with
22119 the usual object files.
22120
22121 Once the program is compiled with coverage instrumentation, you can
22122 run it as many times as needed - on portions of a test suite for
22123 example. The first execution will produce @file{.gcda} files at the
22124 same location as the @file{.gcno} files.  The following executions
22125 will update those files, so that a cumulative result of the covered
22126 portions of the program is generated.
22127
22128 Finally, you need to call the @code{gcov} tool. The different options of
22129 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
22130
22131 This will create annotated source files with a @file{.gcov} extension:
22132 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
22133
22134 @node Gnat specifics
22135 @subsection Gnat specifics
22136
22137 Because Ada semantics, portions of the source code may be shared among
22138 several object files. This is the case for example when generics are
22139 involved, when inlining is active  or when declarations generate  initialisation
22140 calls. In order to take
22141 into account this shared code, you need to call @code{gcov} on all
22142 source files of the tested program at once.
22143
22144 The list of source files might exceed the system's maximum command line
22145 length. In order to bypass this limitation, a new mechanism has been
22146 implemented in @code{gcov}: you can now list all your project's files into a
22147 text file, and provide this file to gcov as a parameter,  preceded by a @@
22148 (e.g. @samp{gcov @@mysrclist.txt}).
22149
22150 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
22151 not supported as there can be unresolved symbols during the final link.
22152
22153 @node Profiling an Ada Program using gprof
22154 @section Profiling an Ada Program using gprof
22155 @cindex gprof
22156 @cindex -pg
22157 @cindex Profiling
22158
22159 @noindent
22160 This section is not meant to be an exhaustive documentation of @code{gprof}.
22161 Full documentation for it can be found in the GNU Profiler User's Guide
22162 documentation that is part of this GNAT distribution.
22163
22164 Profiling a program helps determine the parts of a program that are executed
22165 most often, and are therefore the most time-consuming.
22166
22167 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
22168 better handle Ada programs and multitasking.
22169 It is currently supported on the following platforms
22170 @itemize @bullet
22171 @item
22172 linux x86/x86_64
22173 @item
22174 solaris sparc/sparc64/x86
22175 @item
22176 windows x86
22177 @end itemize
22178
22179 @noindent
22180 In order to profile a program using @code{gprof}, 3 steps are needed:
22181
22182 @itemize @bullet
22183 @item
22184 Code instrumentation, requiring a full recompilation of the project with the
22185 proper switches.
22186 @item
22187 Execution of the program under the analysis conditions, i.e. with the desired
22188 input.
22189 @item
22190 Analysis of the results using the @code{gprof} tool.
22191 @end itemize
22192
22193 @noindent
22194 The following sections detail the different steps, and indicate how
22195 to interpret the results:
22196 @menu
22197 * Compilation for profiling::
22198 * Program execution::
22199 * Running gprof::
22200 * Interpretation of profiling results::
22201 @end menu
22202
22203 @node Compilation for profiling
22204 @subsection Compilation for profiling
22205 @cindex -pg
22206 @cindex Profiling
22207
22208 In order to profile a program the first step is to tell the compiler
22209 to generate the necessary profiling information. The compiler switch to be used
22210 is @code{-pg}, which must be added to other compilation switches. This
22211 switch needs to be specified both during compilation and link stages, and can
22212 be specified once when using gnatmake:
22213
22214 @smallexample
22215 gnatmake -f -pg -P my_project
22216 @end smallexample
22217
22218 @noindent
22219 Note that only the objects that were compiled with the @samp{-pg} switch will be
22220 profiled; if you need to profile your whole project, use the
22221 @samp{-f} gnatmake switch to force full recompilation.
22222
22223 @node Program execution
22224 @subsection Program execution
22225
22226 @noindent
22227 Once the program has been compiled for profiling, you can run it as usual.
22228
22229 The only constraint imposed by profiling is that the program must terminate
22230 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
22231 properly analyzed.
22232
22233 Once the program completes execution, a data file called @file{gmon.out} is
22234 generated in the directory where the program was launched from. If this file
22235 already exists, it will be overwritten.
22236
22237 @node Running gprof
22238 @subsection Running gprof
22239
22240 @noindent
22241 The @code{gprof} tool is called as follow:
22242
22243 @smallexample
22244 gprof my_prog gmon.out
22245 @end smallexample
22246
22247 @noindent
22248 or simpler:
22249
22250 @smallexample
22251 gprof my_prog
22252 @end smallexample
22253
22254 @noindent
22255 The complete form of the gprof command line is the following:
22256
22257 @smallexample
22258 gprof [^switches^options^] [executable [data-file]]
22259 @end smallexample
22260
22261 @noindent
22262 @code{gprof} supports numerous ^switch^options^. The order of these
22263 ^switch^options^ does not matter. The full list of options can be found in
22264 the GNU Profiler User's Guide documentation that comes with this documentation.
22265
22266 The following is the subset of those switches that is most relevant:
22267
22268 @table @option
22269
22270 @item --demangle[=@var{style}]
22271 @itemx --no-demangle
22272 @cindex @option{--demangle} (@code{gprof})
22273 These options control whether symbol names should be demangled when
22274 printing output.  The default is to demangle C++ symbols.  The
22275 @code{--no-demangle} option may be used to turn off demangling. Different
22276 compilers have different mangling styles.  The optional demangling style
22277 argument can be used to choose an appropriate demangling style for your
22278 compiler, in particular Ada symbols generated by GNAT can be demangled using
22279 @code{--demangle=gnat}.
22280
22281 @item -e @var{function_name}
22282 @cindex @option{-e} (@code{gprof})
22283 The @samp{-e @var{function}} option tells @code{gprof} not to print
22284 information about the function @var{function_name} (and its
22285 children@dots{}) in the call graph.  The function will still be listed
22286 as a child of any functions that call it, but its index number will be
22287 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
22288 given; only one @var{function_name} may be indicated with each @samp{-e}
22289 option.
22290
22291 @item -E @var{function_name}
22292 @cindex @option{-E} (@code{gprof})
22293 The @code{-E @var{function}} option works like the @code{-e} option, but
22294 execution time spent in the function (and children who were not called from
22295 anywhere else), will not be used to compute the percentages-of-time for
22296 the call graph.  More than one @samp{-E} option may be given; only one
22297 @var{function_name} may be indicated with each @samp{-E} option.
22298
22299 @item -f @var{function_name}
22300 @cindex @option{-f} (@code{gprof})
22301 The @samp{-f @var{function}} option causes @code{gprof} to limit the
22302 call graph to the function @var{function_name} and its children (and
22303 their children@dots{}).  More than one @samp{-f} option may be given;
22304 only one @var{function_name} may be indicated with each @samp{-f}
22305 option.
22306
22307 @item -F @var{function_name}
22308 @cindex @option{-F} (@code{gprof})
22309 The @samp{-F @var{function}} option works like the @code{-f} option, but
22310 only time spent in the function and its children (and their
22311 children@dots{}) will be used to determine total-time and
22312 percentages-of-time for the call graph.  More than one @samp{-F} option
22313 may be given; only one @var{function_name} may be indicated with each
22314 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
22315
22316 @end table
22317
22318 @node Interpretation of profiling results
22319 @subsection Interpretation of profiling results
22320
22321 @noindent
22322
22323 The results of the profiling analysis are represented by two arrays: the
22324 'flat profile' and the 'call graph'. Full documentation of those outputs
22325 can be found in the GNU Profiler User's Guide.
22326
22327 The flat profile shows the time spent in each function of the program, and how
22328 many time it has been called. This allows you to locate easily the most
22329 time-consuming functions.
22330
22331 The call graph shows, for each subprogram, the subprograms that call it,
22332 and the subprograms that it calls. It also provides an estimate of the time
22333 spent in each of those callers/called subprograms.
22334 @end ifclear
22335
22336 @c ******************************
22337 @node Running and Debugging Ada Programs
22338 @chapter Running and Debugging Ada Programs
22339 @cindex Debugging
22340
22341 @noindent
22342 This chapter discusses how to debug Ada programs.
22343 @ifset vms
22344 It applies to GNAT on the Alpha OpenVMS platform;
22345 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
22346 since HP has implemented Ada support in the OpenVMS debugger on I64.
22347 @end ifset
22348
22349 An incorrect Ada program may be handled in three ways by the GNAT compiler:
22350
22351 @enumerate
22352 @item
22353 The illegality may be a violation of the static semantics of Ada. In
22354 that case GNAT diagnoses the constructs in the program that are illegal.
22355 It is then a straightforward matter for the user to modify those parts of
22356 the program.
22357
22358 @item
22359 The illegality may be a violation of the dynamic semantics of Ada. In
22360 that case the program compiles and executes, but may generate incorrect
22361 results, or may terminate abnormally with some exception.
22362
22363 @item
22364 When presented with a program that contains convoluted errors, GNAT
22365 itself may terminate abnormally without providing full diagnostics on
22366 the incorrect user program.
22367 @end enumerate
22368
22369 @menu
22370 * The GNAT Debugger GDB::
22371 * Running GDB::
22372 * Introduction to GDB Commands::
22373 * Using Ada Expressions::
22374 * Calling User-Defined Subprograms::
22375 * Using the Next Command in a Function::
22376 * Ada Exceptions::
22377 * Ada Tasks::
22378 * Debugging Generic Units::
22379 * Remote Debugging using gdbserver::
22380 * GNAT Abnormal Termination or Failure to Terminate::
22381 * Naming Conventions for GNAT Source Files::
22382 * Getting Internal Debugging Information::
22383 * Stack Traceback::
22384 @end menu
22385
22386 @cindex Debugger
22387 @findex gdb
22388
22389 @node The GNAT Debugger GDB
22390 @section The GNAT Debugger GDB
22391
22392 @noindent
22393 @code{GDB} is a general purpose, platform-independent debugger that
22394 can be used to debug mixed-language programs compiled with @command{gcc},
22395 and in particular is capable of debugging Ada programs compiled with
22396 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
22397 complex Ada data structures.
22398
22399 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
22400 @ifset vms
22401 located in the GNU:[DOCS] directory,
22402 @end ifset
22403 for full details on the usage of @code{GDB}, including a section on
22404 its usage on programs. This manual should be consulted for full
22405 details. The section that follows is a brief introduction to the
22406 philosophy and use of @code{GDB}.
22407
22408 When GNAT programs are compiled, the compiler optionally writes debugging
22409 information into the generated object file, including information on
22410 line numbers, and on declared types and variables. This information is
22411 separate from the generated code. It makes the object files considerably
22412 larger, but it does not add to the size of the actual executable that
22413 will be loaded into memory, and has no impact on run-time performance. The
22414 generation of debug information is triggered by the use of the
22415 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
22416 used to carry out the compilations. It is important to emphasize that
22417 the use of these options does not change the generated code.
22418
22419 The debugging information is written in standard system formats that
22420 are used by many tools, including debuggers and profilers. The format
22421 of the information is typically designed to describe C types and
22422 semantics, but GNAT implements a translation scheme which allows full
22423 details about Ada types and variables to be encoded into these
22424 standard C formats. Details of this encoding scheme may be found in
22425 the file exp_dbug.ads in the GNAT source distribution. However, the
22426 details of this encoding are, in general, of no interest to a user,
22427 since @code{GDB} automatically performs the necessary decoding.
22428
22429 When a program is bound and linked, the debugging information is
22430 collected from the object files, and stored in the executable image of
22431 the program. Again, this process significantly increases the size of
22432 the generated executable file, but it does not increase the size of
22433 the executable program itself. Furthermore, if this program is run in
22434 the normal manner, it runs exactly as if the debug information were
22435 not present, and takes no more actual memory.
22436
22437 However, if the program is run under control of @code{GDB}, the
22438 debugger is activated.  The image of the program is loaded, at which
22439 point it is ready to run.  If a run command is given, then the program
22440 will run exactly as it would have if @code{GDB} were not present. This
22441 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
22442 entirely non-intrusive until a breakpoint is encountered.  If no
22443 breakpoint is ever hit, the program will run exactly as it would if no
22444 debugger were present. When a breakpoint is hit, @code{GDB} accesses
22445 the debugging information and can respond to user commands to inspect
22446 variables, and more generally to report on the state of execution.
22447
22448 @c **************
22449 @node Running GDB
22450 @section Running GDB
22451
22452 @noindent
22453 This section describes how to initiate the debugger.
22454 @c The above sentence is really just filler, but it was otherwise
22455 @c clumsy to get the first paragraph nonindented given the conditional
22456 @c nature of the description
22457
22458 @ifclear vms
22459 The debugger can be launched from a @code{GPS} menu or
22460 directly from the command line. The description below covers the latter use.
22461 All the commands shown can be used in the @code{GPS} debug console window,
22462 but there are usually more GUI-based ways to achieve the same effect.
22463 @end ifclear
22464
22465 The command to run @code{GDB} is
22466
22467 @smallexample
22468 $ ^gdb program^GDB PROGRAM^
22469 @end smallexample
22470
22471 @noindent
22472 where @code{^program^PROGRAM^} is the name of the executable file. This
22473 activates the debugger and results in a prompt for debugger commands.
22474 The simplest command is simply @code{run}, which causes the program to run
22475 exactly as if the debugger were not present. The following section
22476 describes some of the additional commands that can be given to @code{GDB}.
22477
22478 @c *******************************
22479 @node Introduction to GDB Commands
22480 @section Introduction to GDB Commands
22481
22482 @noindent
22483 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
22484 Debugging with GDB, gdb, Debugging with GDB},
22485 @ifset vms
22486 located in the GNU:[DOCS] directory,
22487 @end ifset
22488 for extensive documentation on the use
22489 of these commands, together with examples of their use. Furthermore,
22490 the command @command{help} invoked from within GDB activates a simple help
22491 facility which summarizes the available commands and their options.
22492 In this section we summarize a few of the most commonly
22493 used commands to give an idea of what @code{GDB} is about. You should create
22494 a simple program with debugging information and experiment with the use of
22495 these @code{GDB} commands on the program as you read through the
22496 following section.
22497
22498 @table @code
22499 @item set args @var{arguments}
22500 The @var{arguments} list above is a list of arguments to be passed to
22501 the program on a subsequent run command, just as though the arguments
22502 had been entered on a normal invocation of the program. The @code{set args}
22503 command is not needed if the program does not require arguments.
22504
22505 @item run
22506 The @code{run} command causes execution of the program to start from
22507 the beginning. If the program is already running, that is to say if
22508 you are currently positioned at a breakpoint, then a prompt will ask
22509 for confirmation that you want to abandon the current execution and
22510 restart.
22511
22512 @item breakpoint @var{location}
22513 The breakpoint command sets a breakpoint, that is to say a point at which
22514 execution will halt and @code{GDB} will await further
22515 commands. @var{location} is
22516 either a line number within a file, given in the format @code{file:linenumber},
22517 or it is the name of a subprogram. If you request that a breakpoint be set on
22518 a subprogram that is overloaded, a prompt will ask you to specify on which of
22519 those subprograms you want to breakpoint. You can also
22520 specify that all of them should be breakpointed. If the program is run
22521 and execution encounters the breakpoint, then the program
22522 stops and @code{GDB} signals that the breakpoint was encountered by
22523 printing the line of code before which the program is halted.
22524
22525 @item catch exception @var{name}
22526 This command causes the program execution to stop whenever exception
22527 @var{name} is raised.  If @var{name} is omitted, then the execution is
22528 suspended when any exception is raised.
22529
22530 @item print @var{expression}
22531 This will print the value of the given expression. Most simple
22532 Ada expression formats are properly handled by @code{GDB}, so the expression
22533 can contain function calls, variables, operators, and attribute references.
22534
22535 @item continue
22536 Continues execution following a breakpoint, until the next breakpoint or the
22537 termination of the program.
22538
22539 @item step
22540 Executes a single line after a breakpoint. If the next statement
22541 is a subprogram call, execution continues into (the first statement of)
22542 the called subprogram.
22543
22544 @item next
22545 Executes a single line. If this line is a subprogram call, executes and
22546 returns from the call.
22547
22548 @item list
22549 Lists a few lines around the current source location. In practice, it
22550 is usually more convenient to have a separate edit window open with the
22551 relevant source file displayed. Successive applications of this command
22552 print subsequent lines. The command can be given an argument which is a
22553 line number, in which case it displays a few lines around the specified one.
22554
22555 @item backtrace
22556 Displays a backtrace of the call chain. This command is typically
22557 used after a breakpoint has occurred, to examine the sequence of calls that
22558 leads to the current breakpoint. The display includes one line for each
22559 activation record (frame) corresponding to an active subprogram.
22560
22561 @item up
22562 At a breakpoint, @code{GDB} can display the values of variables local
22563 to the current frame. The command @code{up} can be used to
22564 examine the contents of other active frames, by moving the focus up
22565 the stack, that is to say from callee to caller, one frame at a time.
22566
22567 @item down
22568 Moves the focus of @code{GDB} down from the frame currently being
22569 examined to the frame of its callee (the reverse of the previous command),
22570
22571 @item frame @var{n}
22572 Inspect the frame with the given number. The value 0 denotes the frame
22573 of the current breakpoint, that is to say the top of the call stack.
22574
22575 @end table
22576
22577 @noindent
22578 The above list is a very short introduction to the commands that
22579 @code{GDB} provides. Important additional capabilities, including conditional
22580 breakpoints, the ability to execute command sequences on a breakpoint,
22581 the ability to debug at the machine instruction level and many other
22582 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
22583 Debugging with GDB}.  Note that most commands can be abbreviated
22584 (for example, c for continue, bt for backtrace).
22585
22586 @node Using Ada Expressions
22587 @section Using Ada Expressions
22588 @cindex Ada expressions
22589
22590 @noindent
22591 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
22592 extensions. The philosophy behind the design of this subset is
22593
22594 @itemize @bullet
22595 @item
22596 That @code{GDB} should provide basic literals and access to operations for
22597 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
22598 leaving more sophisticated computations to subprograms written into the
22599 program (which therefore may be called from @code{GDB}).
22600
22601 @item
22602 That type safety and strict adherence to Ada language restrictions
22603 are not particularly important to the @code{GDB} user.
22604
22605 @item
22606 That brevity is important to the @code{GDB} user.
22607 @end itemize
22608
22609 @noindent
22610 Thus, for brevity, the debugger acts as if there were
22611 implicit @code{with} and @code{use} clauses in effect for all user-written
22612 packages, thus making it unnecessary to fully qualify most names with
22613 their packages, regardless of context. Where this causes ambiguity,
22614 @code{GDB} asks the user's intent.
22615
22616 For details on the supported Ada syntax, see @ref{Top,, Debugging with
22617 GDB, gdb, Debugging with GDB}.
22618
22619 @node Calling User-Defined Subprograms
22620 @section Calling User-Defined Subprograms
22621
22622 @noindent
22623 An important capability of @code{GDB} is the ability to call user-defined
22624 subprograms while debugging. This is achieved simply by entering
22625 a subprogram call statement in the form:
22626
22627 @smallexample
22628 call subprogram-name (parameters)
22629 @end smallexample
22630
22631 @noindent
22632 The keyword @code{call} can be omitted in the normal case where the
22633 @code{subprogram-name} does not coincide with any of the predefined
22634 @code{GDB} commands.
22635
22636 The effect is to invoke the given subprogram, passing it the
22637 list of parameters that is supplied. The parameters can be expressions and
22638 can include variables from the program being debugged. The
22639 subprogram must be defined
22640 at the library level within your program, and @code{GDB} will call the
22641 subprogram within the environment of your program execution (which
22642 means that the subprogram is free to access or even modify variables
22643 within your program).
22644
22645 The most important use of this facility is in allowing the inclusion of
22646 debugging routines that are tailored to particular data structures
22647 in your program. Such debugging routines can be written to provide a suitably
22648 high-level description of an abstract type, rather than a low-level dump
22649 of its physical layout. After all, the standard
22650 @code{GDB print} command only knows the physical layout of your
22651 types, not their abstract meaning. Debugging routines can provide information
22652 at the desired semantic level and are thus enormously useful.
22653
22654 For example, when debugging GNAT itself, it is crucial to have access to
22655 the contents of the tree nodes used to represent the program internally.
22656 But tree nodes are represented simply by an integer value (which in turn
22657 is an index into a table of nodes).
22658 Using the @code{print} command on a tree node would simply print this integer
22659 value, which is not very useful. But the PN routine (defined in file
22660 treepr.adb in the GNAT sources) takes a tree node as input, and displays
22661 a useful high level representation of the tree node, which includes the
22662 syntactic category of the node, its position in the source, the integers
22663 that denote descendant nodes and parent node, as well as varied
22664 semantic information. To study this example in more detail, you might want to
22665 look at the body of the PN procedure in the stated file.
22666
22667 @node Using the Next Command in a Function
22668 @section Using the Next Command in a Function
22669
22670 @noindent
22671 When you use the @code{next} command in a function, the current source
22672 location will advance to the next statement as usual. A special case
22673 arises in the case of a @code{return} statement.
22674
22675 Part of the code for a return statement is the ``epilog'' of the function.
22676 This is the code that returns to the caller. There is only one copy of
22677 this epilog code, and it is typically associated with the last return
22678 statement in the function if there is more than one return. In some
22679 implementations, this epilog is associated with the first statement
22680 of the function.
22681
22682 The result is that if you use the @code{next} command from a return
22683 statement that is not the last return statement of the function you
22684 may see a strange apparent jump to the last return statement or to
22685 the start of the function. You should simply ignore this odd jump.
22686 The value returned is always that from the first return statement
22687 that was stepped through.
22688
22689 @node Ada Exceptions
22690 @section Stopping when Ada Exceptions are Raised
22691 @cindex Exceptions
22692
22693 @noindent
22694 You can set catchpoints that stop the program execution when your program
22695 raises selected exceptions.
22696
22697 @table @code
22698 @item catch exception
22699 Set a catchpoint that stops execution whenever (any task in the) program
22700 raises any exception.
22701
22702 @item catch exception @var{name}
22703 Set a catchpoint that stops execution whenever (any task in the) program
22704 raises the exception @var{name}.
22705
22706 @item catch exception unhandled
22707 Set a catchpoint that stops executino whenever (any task in the) program
22708 raises an exception for which there is no handler.
22709
22710 @item info exceptions
22711 @itemx info exceptions @var{regexp}
22712 The @code{info exceptions} command permits the user to examine all defined
22713 exceptions within Ada programs. With a regular expression, @var{regexp}, as
22714 argument, prints out only those exceptions whose name matches @var{regexp}.
22715 @end table
22716
22717 @node Ada Tasks
22718 @section Ada Tasks
22719 @cindex Tasks
22720
22721 @noindent
22722 @code{GDB} allows the following task-related commands:
22723
22724 @table @code
22725 @item info tasks
22726 This command shows a list of current Ada tasks, as in the following example:
22727
22728 @smallexample
22729 @iftex
22730 @leftskip=0cm
22731 @end iftex
22732 (gdb) info tasks
22733   ID       TID P-ID   Thread Pri State                 Name
22734    1   8088000   0   807e000  15 Child Activation Wait main_task
22735    2   80a4000   1   80ae000  15 Accept/Select Wait    b
22736    3   809a800   1   80a4800  15 Child Activation Wait a
22737 *  4   80ae800   3   80b8000  15 Running               c
22738 @end smallexample
22739
22740 @noindent
22741 In this listing, the asterisk before the first task indicates it to be the
22742 currently running task. The first column lists the task ID that is used
22743 to refer to tasks in the following commands.
22744
22745 @item break @var{linespec} task @var{taskid}
22746 @itemx break @var{linespec} task @var{taskid} if @dots{}
22747 @cindex Breakpoints and tasks
22748 These commands are like the @code{break @dots{} thread @dots{}}.
22749 @var{linespec} specifies source lines.
22750
22751 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
22752 to specify that you only want @code{GDB} to stop the program when a
22753 particular Ada task reaches this breakpoint. @var{taskid} is one of the
22754 numeric task identifiers assigned by @code{GDB}, shown in the first
22755 column of the @samp{info tasks} display.
22756
22757 If you do not specify @samp{task @var{taskid}} when you set a
22758 breakpoint, the breakpoint applies to @emph{all} tasks of your
22759 program.
22760
22761 You can use the @code{task} qualifier on conditional breakpoints as
22762 well; in this case, place @samp{task @var{taskid}} before the
22763 breakpoint condition (before the @code{if}).
22764
22765 @item task @var{taskno}
22766 @cindex Task switching
22767
22768 This command allows to switch to the task referred by @var{taskno}. In
22769 particular, This allows to browse the backtrace of the specified
22770 task. It is advised to switch back to the original task before
22771 continuing execution otherwise the scheduling of the program may be
22772 perturbed.
22773 @end table
22774
22775 @noindent
22776 For more detailed information on the tasking support,
22777 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
22778
22779 @node Debugging Generic Units
22780 @section Debugging Generic Units
22781 @cindex Debugging Generic Units
22782 @cindex Generics
22783
22784 @noindent
22785 GNAT always uses code expansion for generic instantiation. This means that
22786 each time an instantiation occurs, a complete copy of the original code is
22787 made, with appropriate substitutions of formals by actuals.
22788
22789 It is not possible to refer to the original generic entities in
22790 @code{GDB}, but it is always possible to debug a particular instance of
22791 a generic, by using the appropriate expanded names. For example, if we have
22792
22793 @smallexample @c ada
22794 @group
22795 @cartouche
22796 procedure g is
22797
22798    generic package k is
22799       procedure kp (v1 : in out integer);
22800    end k;
22801
22802    package body k is
22803       procedure kp (v1 : in out integer) is
22804       begin
22805          v1 := v1 + 1;
22806       end kp;
22807    end k;
22808
22809    package k1 is new k;
22810    package k2 is new k;
22811
22812    var : integer := 1;
22813
22814 begin
22815    k1.kp (var);
22816    k2.kp (var);
22817    k1.kp (var);
22818    k2.kp (var);
22819 end;
22820 @end cartouche
22821 @end group
22822 @end smallexample
22823
22824 @noindent
22825 Then to break on a call to procedure kp in the k2 instance, simply
22826 use the command:
22827
22828 @smallexample
22829 (gdb) break g.k2.kp
22830 @end smallexample
22831
22832 @noindent
22833 When the breakpoint occurs, you can step through the code of the
22834 instance in the normal manner and examine the values of local variables, as for
22835 other units.
22836
22837 @node Remote Debugging using gdbserver
22838 @section Remote Debugging using gdbserver
22839 @cindex Remote Debugging using gdbserver
22840
22841 @noindent
22842 On platforms where gdbserver is supported, it is possible to use this tool
22843 to debug your application remotely.  This can be useful in situations
22844 where the program needs to be run on a target host that is different
22845 from the host used for development, particularly when the target has
22846 a limited amount of resources (either CPU and/or memory).
22847
22848 To do so, start your program using gdbserver on the target machine.
22849 gdbserver then automatically suspends the execution of your program
22850 at its entry point, waiting for a debugger to connect to it.  The
22851 following commands starts an application and tells gdbserver to
22852 wait for a connection with the debugger on localhost port 4444.
22853
22854 @smallexample
22855 $ gdbserver localhost:4444 program
22856 Process program created; pid = 5685
22857 Listening on port 4444
22858 @end smallexample
22859
22860 Once gdbserver has started listening, we can tell the debugger to establish
22861 a connection with this gdbserver, and then start the same debugging session
22862 as if the program was being debugged on the same host, directly under
22863 the control of GDB.
22864
22865 @smallexample
22866 $ gdb program
22867 (gdb) target remote targethost:4444
22868 Remote debugging using targethost:4444
22869 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
22870 (gdb) b foo.adb:3
22871 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
22872 (gdb) continue
22873 Continuing.
22874
22875 Breakpoint 1, foo () at foo.adb:4
22876 4       end foo;
22877 @end smallexample
22878
22879 It is also possible to use gdbserver to attach to an already running
22880 program, in which case the execution of that program is simply suspended
22881 until the connection between the debugger and gdbserver is established.
22882
22883 For more information on how to use gdbserver, @ref{Top, Server, Using
22884 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
22885 for gdbserver on x86-linux, x86-windows and x86_64-linux.
22886
22887 @node GNAT Abnormal Termination or Failure to Terminate
22888 @section GNAT Abnormal Termination or Failure to Terminate
22889 @cindex GNAT Abnormal Termination or Failure to Terminate
22890
22891 @noindent
22892 When presented with programs that contain serious errors in syntax
22893 or semantics,
22894 GNAT may on rare occasions  experience problems in operation, such
22895 as aborting with a
22896 segmentation fault or illegal memory access, raising an internal
22897 exception, terminating abnormally, or failing to terminate at all.
22898 In such cases, you can activate
22899 various features of GNAT that can help you pinpoint the construct in your
22900 program that is the likely source of the problem.
22901
22902 The following strategies are presented in increasing order of
22903 difficulty, corresponding to your experience in using GNAT and your
22904 familiarity with compiler internals.
22905
22906 @enumerate
22907 @item
22908 Run @command{gcc} with the @option{-gnatf}. This first
22909 switch causes all errors on a given line to be reported. In its absence,
22910 only the first error on a line is displayed.
22911
22912 The @option{-gnatdO} switch causes errors to be displayed as soon as they
22913 are encountered, rather than after compilation is terminated. If GNAT
22914 terminates prematurely or goes into an infinite loop, the last error
22915 message displayed may help to pinpoint the culprit.
22916
22917 @item
22918 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
22919 mode, @command{gcc} produces ongoing information about the progress of the
22920 compilation and provides the name of each procedure as code is
22921 generated. This switch allows you to find which Ada procedure was being
22922 compiled when it encountered a code generation problem.
22923
22924 @item
22925 @cindex @option{-gnatdc} switch
22926 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
22927 switch that does for the front-end what @option{^-v^VERBOSE^} does
22928 for the back end. The system prints the name of each unit,
22929 either a compilation unit or nested unit, as it is being analyzed.
22930 @item
22931 Finally, you can start
22932 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
22933 front-end of GNAT, and can be run independently (normally it is just
22934 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
22935 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
22936 @code{where} command is the first line of attack; the variable
22937 @code{lineno} (seen by @code{print lineno}), used by the second phase of
22938 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
22939 which the execution stopped, and @code{input_file name} indicates the name of
22940 the source file.
22941 @end enumerate
22942
22943 @node Naming Conventions for GNAT Source Files
22944 @section Naming Conventions for GNAT Source Files
22945
22946 @noindent
22947 In order to examine the workings of the GNAT system, the following
22948 brief description of its organization may be helpful:
22949
22950 @itemize @bullet
22951 @item
22952 Files with prefix @file{^sc^SC^} contain the lexical scanner.
22953
22954 @item
22955 All files prefixed with @file{^par^PAR^} are components of the parser. The
22956 numbers correspond to chapters of the Ada Reference Manual. For example,
22957 parsing of select statements can be found in @file{par-ch9.adb}.
22958
22959 @item
22960 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
22961 numbers correspond to chapters of the Ada standard. For example, all
22962 issues involving context clauses can be found in @file{sem_ch10.adb}. In
22963 addition, some features of the language require sufficient special processing
22964 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
22965 dynamic dispatching, etc.
22966
22967 @item
22968 All files prefixed with @file{^exp^EXP^} perform normalization and
22969 expansion of the intermediate representation (abstract syntax tree, or AST).
22970 these files use the same numbering scheme as the parser and semantics files.
22971 For example, the construction of record initialization procedures is done in
22972 @file{exp_ch3.adb}.
22973
22974 @item
22975 The files prefixed with @file{^bind^BIND^} implement the binder, which
22976 verifies the consistency of the compilation, determines an order of
22977 elaboration, and generates the bind file.
22978
22979 @item
22980 The files @file{atree.ads} and @file{atree.adb} detail the low-level
22981 data structures used by the front-end.
22982
22983 @item
22984 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
22985 the abstract syntax tree as produced by the parser.
22986
22987 @item
22988 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
22989 all entities, computed during semantic analysis.
22990
22991 @item
22992 Library management issues are dealt with in files with prefix
22993 @file{^lib^LIB^}.
22994
22995 @item
22996 @findex Ada
22997 @cindex Annex A
22998 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
22999 defined in Annex A.
23000
23001 @item
23002 @findex Interfaces
23003 @cindex Annex B
23004 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23005 defined in Annex B.
23006
23007 @item
23008 @findex System
23009 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23010 both language-defined children and GNAT run-time routines.
23011
23012 @item
23013 @findex GNAT
23014 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23015 general-purpose packages, fully documented in their specs. All
23016 the other @file{.c} files are modifications of common @command{gcc} files.
23017 @end itemize
23018
23019 @node Getting Internal Debugging Information
23020 @section Getting Internal Debugging Information
23021
23022 @noindent
23023 Most compilers have internal debugging switches and modes. GNAT
23024 does also, except GNAT internal debugging switches and modes are not
23025 secret. A summary and full description of all the compiler and binder
23026 debug flags are in the file @file{debug.adb}. You must obtain the
23027 sources of the compiler to see the full detailed effects of these flags.
23028
23029 The switches that print the source of the program (reconstructed from
23030 the internal tree) are of general interest for user programs, as are the
23031 options to print
23032 the full internal tree, and the entity table (the symbol table
23033 information). The reconstructed source provides a readable version of the
23034 program after the front-end has completed analysis and  expansion,
23035 and is useful when studying the performance of specific constructs.
23036 For example, constraint checks are indicated, complex aggregates
23037 are replaced with loops and assignments, and tasking primitives
23038 are replaced with run-time calls.
23039
23040 @node Stack Traceback
23041 @section Stack Traceback
23042 @cindex traceback
23043 @cindex stack traceback
23044 @cindex stack unwinding
23045
23046 @noindent
23047 Traceback is a mechanism to display the sequence of subprogram calls that
23048 leads to a specified execution point in a program. Often (but not always)
23049 the execution point is an instruction at which an exception has been raised.
23050 This mechanism is also known as @i{stack unwinding} because it obtains
23051 its information by scanning the run-time stack and recovering the activation
23052 records of all active subprograms. Stack unwinding is one of the most
23053 important tools for program debugging.
23054
23055 The first entry stored in traceback corresponds to the deepest calling level,
23056 that is to say the subprogram currently executing the instruction
23057 from which we want to obtain the traceback.
23058
23059 Note that there is no runtime performance penalty when stack traceback
23060 is enabled, and no exception is raised during program execution.
23061
23062 @menu
23063 * Non-Symbolic Traceback::
23064 * Symbolic Traceback::
23065 @end menu
23066
23067 @node Non-Symbolic Traceback
23068 @subsection Non-Symbolic Traceback
23069 @cindex traceback, non-symbolic
23070
23071 @noindent
23072 Note: this feature is not supported on all platforms. See
23073 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23074 platforms.
23075
23076 @menu
23077 * Tracebacks From an Unhandled Exception::
23078 * Tracebacks From Exception Occurrences (non-symbolic)::
23079 * Tracebacks From Anywhere in a Program (non-symbolic)::
23080 @end menu
23081
23082 @node Tracebacks From an Unhandled Exception
23083 @subsubsection Tracebacks From an Unhandled Exception
23084
23085 @noindent
23086 A runtime non-symbolic traceback is a list of addresses of call instructions.
23087 To enable this feature you must use the @option{-E}
23088 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23089 of exception information. You can retrieve this information using the
23090 @code{addr2line} tool.
23091
23092 Here is a simple example:
23093
23094 @smallexample @c ada
23095 @cartouche
23096 procedure STB is
23097
23098    procedure P1 is
23099    begin
23100       raise Constraint_Error;
23101    end P1;
23102
23103    procedure P2 is
23104    begin
23105       P1;
23106    end P2;
23107
23108 begin
23109    P2;
23110 end STB;
23111 @end cartouche
23112 @end smallexample
23113
23114 @smallexample
23115 $ gnatmake stb -bargs -E
23116 $ stb
23117
23118 Execution terminated by unhandled exception
23119 Exception name: CONSTRAINT_ERROR
23120 Message: stb.adb:5
23121 Call stack traceback locations:
23122 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23123 @end smallexample
23124
23125 @noindent
23126 As we see the traceback lists a sequence of addresses for the unhandled
23127 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
23128 guess that this exception come from procedure P1. To translate these
23129 addresses into the source lines where the calls appear, the
23130 @code{addr2line} tool, described below, is invaluable. The use of this tool
23131 requires the program to be compiled with debug information.
23132
23133 @smallexample
23134 $ gnatmake -g stb -bargs -E
23135 $ stb
23136
23137 Execution terminated by unhandled exception
23138 Exception name: CONSTRAINT_ERROR
23139 Message: stb.adb:5
23140 Call stack traceback locations:
23141 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23142
23143 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
23144    0x4011f1 0x77e892a4
23145
23146 00401373 at d:/stb/stb.adb:5
23147 0040138B at d:/stb/stb.adb:10
23148 0040139C at d:/stb/stb.adb:14
23149 00401335 at d:/stb/b~stb.adb:104
23150 004011C4 at /build/@dots{}/crt1.c:200
23151 004011F1 at /build/@dots{}/crt1.c:222
23152 77E892A4 in ?? at ??:0
23153 @end smallexample
23154
23155 @noindent
23156 The @code{addr2line} tool has several other useful options:
23157
23158 @table @code
23159 @item --functions
23160 to get the function name corresponding to any location
23161
23162 @item --demangle=gnat
23163 to use the gnat decoding mode for the function names. Note that
23164 for binutils version 2.9.x the option is simply @option{--demangle}.
23165 @end table
23166
23167 @smallexample
23168 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
23169    0x40139c 0x401335 0x4011c4 0x4011f1
23170
23171 00401373 in stb.p1 at d:/stb/stb.adb:5
23172 0040138B in stb.p2 at d:/stb/stb.adb:10
23173 0040139C in stb at d:/stb/stb.adb:14
23174 00401335 in main at d:/stb/b~stb.adb:104
23175 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
23176 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
23177 @end smallexample
23178
23179 @noindent
23180 From this traceback we can see that the exception was raised in
23181 @file{stb.adb} at line 5, which was reached from a procedure call in
23182 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
23183 which contains the call to the main program.
23184 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
23185 and the output will vary from platform to platform.
23186
23187 It is also possible to use @code{GDB} with these traceback addresses to debug
23188 the program. For example, we can break at a given code location, as reported
23189 in the stack traceback:
23190
23191 @smallexample
23192 $ gdb -nw stb
23193 @ifclear vms
23194 @noindent
23195 Furthermore, this feature is not implemented inside Windows DLL. Only
23196 the non-symbolic traceback is reported in this case.
23197 @end ifclear
23198
23199 (gdb) break *0x401373
23200 Breakpoint 1 at 0x401373: file stb.adb, line 5.
23201 @end smallexample
23202
23203 @noindent
23204 It is important to note that the stack traceback addresses
23205 do not change when debug information is included. This is particularly useful
23206 because it makes it possible to release software without debug information (to
23207 minimize object size), get a field report that includes a stack traceback
23208 whenever an internal bug occurs, and then be able to retrieve the sequence
23209 of calls with the same program compiled with debug information.
23210
23211 @node Tracebacks From Exception Occurrences (non-symbolic)
23212 @subsubsection Tracebacks From Exception Occurrences
23213
23214 @noindent
23215 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
23216 The stack traceback is attached to the exception information string, and can
23217 be retrieved in an exception handler within the Ada program, by means of the
23218 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
23219
23220 @smallexample @c ada
23221 with Ada.Text_IO;
23222 with Ada.Exceptions;
23223
23224 procedure STB is
23225
23226    use Ada;
23227    use Ada.Exceptions;
23228
23229    procedure P1 is
23230       K : Positive := 1;
23231    begin
23232       K := K - 1;
23233    exception
23234       when E : others =>
23235          Text_IO.Put_Line (Exception_Information (E));
23236    end P1;
23237
23238    procedure P2 is
23239    begin
23240       P1;
23241    end P2;
23242
23243 begin
23244    P2;
23245 end STB;
23246 @end smallexample
23247
23248 @noindent
23249 This program will output:
23250
23251 @smallexample
23252 $ stb
23253
23254 Exception name: CONSTRAINT_ERROR
23255 Message: stb.adb:12
23256 Call stack traceback locations:
23257 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
23258 @end smallexample
23259
23260 @node Tracebacks From Anywhere in a Program (non-symbolic)
23261 @subsubsection Tracebacks From Anywhere in a Program
23262
23263 @noindent
23264 It is also possible to retrieve a stack traceback from anywhere in a
23265 program. For this you need to
23266 use the @code{GNAT.Traceback} API. This package includes a procedure called
23267 @code{Call_Chain} that computes a complete stack traceback, as well as useful
23268 display procedures described below. It is not necessary to use the
23269 @option{-E gnatbind} option in this case, because the stack traceback mechanism
23270 is invoked explicitly.
23271
23272 @noindent
23273 In the following example we compute a traceback at a specific location in
23274 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
23275 convert addresses to strings:
23276
23277 @smallexample @c ada
23278 with Ada.Text_IO;
23279 with GNAT.Traceback;
23280 with GNAT.Debug_Utilities;
23281
23282 procedure STB is
23283
23284    use Ada;
23285    use GNAT;
23286    use GNAT.Traceback;
23287
23288    procedure P1 is
23289       TB  : Tracebacks_Array (1 .. 10);
23290       --  We are asking for a maximum of 10 stack frames.
23291       Len : Natural;
23292       --  Len will receive the actual number of stack frames returned.
23293    begin
23294       Call_Chain (TB, Len);
23295
23296       Text_IO.Put ("In STB.P1 : ");
23297
23298       for K in 1 .. Len loop
23299          Text_IO.Put (Debug_Utilities.Image (TB (K)));
23300          Text_IO.Put (' ');
23301       end loop;
23302
23303       Text_IO.New_Line;
23304    end P1;
23305
23306    procedure P2 is
23307    begin
23308       P1;
23309    end P2;
23310
23311 begin
23312    P2;
23313 end STB;
23314 @end smallexample
23315
23316 @smallexample
23317 $ gnatmake -g stb
23318 $ stb
23319
23320 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
23321 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
23322 @end smallexample
23323
23324 @noindent
23325 You can then get further information by invoking the @code{addr2line}
23326 tool as described earlier (note that the hexadecimal addresses
23327 need to be specified in C format, with a leading ``0x'').
23328
23329 @node Symbolic Traceback
23330 @subsection Symbolic Traceback
23331 @cindex traceback, symbolic
23332
23333 @noindent
23334 A symbolic traceback is a stack traceback in which procedure names are
23335 associated with each code location.
23336
23337 @noindent
23338 Note that this feature is not supported on all platforms. See
23339 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
23340 list of currently supported platforms.
23341
23342 @noindent
23343 Note that the symbolic traceback requires that the program be compiled
23344 with debug information. If it is not compiled with debug information
23345 only the non-symbolic information will be valid.
23346
23347 @menu
23348 * Tracebacks From Exception Occurrences (symbolic)::
23349 * Tracebacks From Anywhere in a Program (symbolic)::
23350 @end menu
23351
23352 @node Tracebacks From Exception Occurrences (symbolic)
23353 @subsubsection Tracebacks From Exception Occurrences
23354
23355 @smallexample @c ada
23356 with Ada.Text_IO;
23357 with GNAT.Traceback.Symbolic;
23358
23359 procedure STB is
23360
23361    procedure P1 is
23362    begin
23363       raise Constraint_Error;
23364    end P1;
23365
23366    procedure P2 is
23367    begin
23368       P1;
23369    end P2;
23370
23371    procedure P3 is
23372    begin
23373       P2;
23374    end P3;
23375
23376 begin
23377    P3;
23378 exception
23379    when E : others =>
23380       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
23381 end STB;
23382 @end smallexample
23383
23384 @smallexample
23385 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
23386 $ stb
23387
23388 0040149F in stb.p1 at stb.adb:8
23389 004014B7 in stb.p2 at stb.adb:13
23390 004014CF in stb.p3 at stb.adb:18
23391 004015DD in ada.stb at stb.adb:22
23392 00401461 in main at b~stb.adb:168
23393 004011C4 in __mingw_CRTStartup at crt1.c:200
23394 004011F1 in mainCRTStartup at crt1.c:222
23395 77E892A4 in ?? at ??:0
23396 @end smallexample
23397
23398 @noindent
23399 In the above example the ``.\'' syntax in the @command{gnatmake} command
23400 is currently required by @command{addr2line} for files that are in
23401 the current working directory.
23402 Moreover, the exact sequence of linker options may vary from platform
23403 to platform.
23404 The above @option{-largs} section is for Windows platforms. By contrast,
23405 under Unix there is no need for the @option{-largs} section.
23406 Differences across platforms are due to details of linker implementation.
23407
23408 @node Tracebacks From Anywhere in a Program (symbolic)
23409 @subsubsection Tracebacks From Anywhere in a Program
23410
23411 @noindent
23412 It is possible to get a symbolic stack traceback
23413 from anywhere in a program, just as for non-symbolic tracebacks.
23414 The first step is to obtain a non-symbolic
23415 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
23416 information. Here is an example:
23417
23418 @smallexample @c ada
23419 with Ada.Text_IO;
23420 with GNAT.Traceback;
23421 with GNAT.Traceback.Symbolic;
23422
23423 procedure STB is
23424
23425    use Ada;
23426    use GNAT.Traceback;
23427    use GNAT.Traceback.Symbolic;
23428
23429    procedure P1 is
23430       TB  : Tracebacks_Array (1 .. 10);
23431       --  We are asking for a maximum of 10 stack frames.
23432       Len : Natural;
23433       --  Len will receive the actual number of stack frames returned.
23434    begin
23435       Call_Chain (TB, Len);
23436       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
23437    end P1;
23438
23439    procedure P2 is
23440    begin
23441       P1;
23442    end P2;
23443
23444 begin
23445    P2;
23446 end STB;
23447 @end smallexample
23448
23449 @c ******************************
23450 @ifset vms
23451 @node Compatibility with HP Ada
23452 @chapter Compatibility with HP Ada
23453 @cindex Compatibility
23454
23455 @noindent
23456 @cindex DEC Ada
23457 @cindex HP Ada
23458 @cindex Compatibility between GNAT and HP Ada
23459 This chapter compares HP Ada (formerly known as ``DEC Ada'')
23460 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
23461 GNAT is highly compatible
23462 with HP Ada, and it should generally be straightforward to port code
23463 from the HP Ada environment to GNAT. However, there are a few language
23464 and implementation differences of which the user must be aware. These
23465 differences are discussed in this chapter. In
23466 addition, the operating environment and command structure for the
23467 compiler are different, and these differences are also discussed.
23468
23469 For further details on these and other compatibility issues,
23470 see Appendix E of the HP publication
23471 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
23472
23473 Except where otherwise indicated, the description of GNAT for OpenVMS
23474 applies to both the Alpha and I64 platforms.
23475
23476 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
23477 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23478
23479 The discussion in this chapter addresses specifically the implementation
23480 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
23481 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
23482 GNAT always follows the Alpha implementation.
23483
23484 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
23485 attributes are recognized, although only a subset of them can sensibly
23486 be implemented.  The description of pragmas in
23487 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
23488 indicates whether or not they are applicable to non-VMS systems.
23489
23490 @menu
23491 * Ada Language Compatibility::
23492 * Differences in the Definition of Package System::
23493 * Language-Related Features::
23494 * The Package STANDARD::
23495 * The Package SYSTEM::
23496 * Tasking and Task-Related Features::
23497 * Pragmas and Pragma-Related Features::
23498 * Library of Predefined Units::
23499 * Bindings::
23500 * Main Program Definition::
23501 * Implementation-Defined Attributes::
23502 * Compiler and Run-Time Interfacing::
23503 * Program Compilation and Library Management::
23504 * Input-Output::
23505 * Implementation Limits::
23506 * Tools and Utilities::
23507 @end menu
23508
23509 @node Ada Language Compatibility
23510 @section Ada Language Compatibility
23511
23512 @noindent
23513 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23514 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23515 with Ada 83, and therefore Ada 83 programs will compile
23516 and run under GNAT with
23517 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23518 provides details on specific incompatibilities.
23519
23520 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23521 as well as the pragma @code{ADA_83}, to force the compiler to
23522 operate in Ada 83 mode. This mode does not guarantee complete
23523 conformance to Ada 83, but in practice is sufficient to
23524 eliminate most sources of incompatibilities.
23525 In particular, it eliminates the recognition of the
23526 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23527 in Ada 83 programs is legal, and handles the cases of packages
23528 with optional bodies, and generics that instantiate unconstrained
23529 types without the use of @code{(<>)}.
23530
23531 @node Differences in the Definition of Package System
23532 @section Differences in the Definition of Package @code{System}
23533
23534 @noindent
23535 An Ada compiler is allowed to add
23536 implementation-dependent declarations to package @code{System}.
23537 In normal mode,
23538 GNAT does not take advantage of this permission, and the version of
23539 @code{System} provided by GNAT exactly matches that defined in the Ada
23540 Reference Manual.
23541
23542 However, HP Ada adds an extensive set of declarations to package
23543 @code{System},
23544 as fully documented in the HP Ada manuals. To minimize changes required
23545 for programs that make use of these extensions, GNAT provides the pragma
23546 @code{Extend_System} for extending the definition of package System. By using:
23547 @cindex pragma @code{Extend_System}
23548 @cindex @code{Extend_System} pragma
23549
23550 @smallexample @c ada
23551 @group
23552 @cartouche
23553 pragma Extend_System (Aux_DEC);
23554 @end cartouche
23555 @end group
23556 @end smallexample
23557
23558 @noindent
23559 the set of definitions in @code{System} is extended to include those in
23560 package @code{System.Aux_DEC}.
23561 @cindex @code{System.Aux_DEC} package
23562 @cindex @code{Aux_DEC} package (child of @code{System})
23563 These definitions are incorporated directly into package @code{System},
23564 as though they had been declared there. For a
23565 list of the declarations added, see the spec of this package,
23566 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23567 @cindex @file{s-auxdec.ads} file
23568 The pragma @code{Extend_System} is a configuration pragma, which means that
23569 it can be placed in the file @file{gnat.adc}, so that it will automatically
23570 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23571 for further details.
23572
23573 An alternative approach that avoids the use of the non-standard
23574 @code{Extend_System} pragma is to add a context clause to the unit that
23575 references these facilities:
23576
23577 @smallexample @c ada
23578 @cartouche
23579 with System.Aux_DEC;
23580 use  System.Aux_DEC;
23581 @end cartouche
23582 @end smallexample
23583
23584 @noindent
23585 The effect is not quite semantically identical to incorporating
23586 the declarations directly into package @code{System},
23587 but most programs will not notice a difference
23588 unless they use prefix notation (e.g.@: @code{System.Integer_8})
23589 to reference the entities directly in package @code{System}.
23590 For units containing such references,
23591 the prefixes must either be removed, or the pragma @code{Extend_System}
23592 must be used.
23593
23594 @node Language-Related Features
23595 @section Language-Related Features
23596
23597 @noindent
23598 The following sections highlight differences in types,
23599 representations of types, operations, alignment, and
23600 related topics.
23601
23602 @menu
23603 * Integer Types and Representations::
23604 * Floating-Point Types and Representations::
23605 * Pragmas Float_Representation and Long_Float::
23606 * Fixed-Point Types and Representations::
23607 * Record and Array Component Alignment::
23608 * Address Clauses::
23609 * Other Representation Clauses::
23610 @end menu
23611
23612 @node Integer Types and Representations
23613 @subsection Integer Types and Representations
23614
23615 @noindent
23616 The set of predefined integer types is identical in HP Ada and GNAT.
23617 Furthermore the representation of these integer types is also identical,
23618 including the capability of size clauses forcing biased representation.
23619
23620 In addition,
23621 HP Ada for OpenVMS Alpha systems has defined the
23622 following additional integer types in package @code{System}:
23623
23624 @itemize @bullet
23625
23626 @item
23627 @code{INTEGER_8}
23628
23629 @item
23630 @code{INTEGER_16}
23631
23632 @item
23633 @code{INTEGER_32}
23634
23635 @item
23636 @code{INTEGER_64}
23637
23638 @item
23639 @code{LARGEST_INTEGER}
23640 @end itemize
23641
23642 @noindent
23643 In GNAT, the first four of these types may be obtained from the
23644 standard Ada package @code{Interfaces}.
23645 Alternatively, by use of the pragma @code{Extend_System}, identical
23646 declarations can be referenced directly in package @code{System}.
23647 On both GNAT and HP Ada, the maximum integer size is 64 bits.
23648
23649 @node Floating-Point Types and Representations
23650 @subsection Floating-Point Types and Representations
23651 @cindex Floating-Point types
23652
23653 @noindent
23654 The set of predefined floating-point types is identical in HP Ada and GNAT.
23655 Furthermore the representation of these floating-point
23656 types is also identical. One important difference is that the default
23657 representation for HP Ada is @code{VAX_Float}, but the default representation
23658 for GNAT is IEEE.
23659
23660 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
23661 pragma @code{Float_Representation} as described in the HP Ada
23662 documentation.
23663 For example, the declarations:
23664
23665 @smallexample @c ada
23666 @cartouche
23667 type F_Float is digits 6;
23668 pragma Float_Representation (VAX_Float, F_Float);
23669 @end cartouche
23670 @end smallexample
23671
23672 @noindent
23673 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
23674 format.
23675 This set of declarations actually appears in @code{System.Aux_DEC},
23676 which contains
23677 the full set of additional floating-point declarations provided in
23678 the HP Ada version of package @code{System}.
23679 This and similar declarations may be accessed in a user program
23680 by using pragma @code{Extend_System}. The use of this
23681 pragma, and the related pragma @code{Long_Float} is described in further
23682 detail in the following section.
23683
23684 @node Pragmas Float_Representation and Long_Float
23685 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
23686
23687 @noindent
23688 HP Ada provides the pragma @code{Float_Representation}, which
23689 acts as a program library switch to allow control over
23690 the internal representation chosen for the predefined
23691 floating-point types declared in the package @code{Standard}.
23692 The format of this pragma is as follows:
23693
23694 @smallexample @c ada
23695 @cartouche
23696 pragma Float_Representation(VAX_Float | IEEE_Float);
23697 @end cartouche
23698 @end smallexample
23699
23700 @noindent
23701 This pragma controls the representation of floating-point
23702 types as follows:
23703
23704 @itemize @bullet
23705 @item
23706 @code{VAX_Float} specifies that floating-point
23707 types are represented by default with the VAX system hardware types
23708 @code{F-floating}, @code{D-floating}, @code{G-floating}.
23709 Note that the @code{H-floating}
23710 type was available only on VAX systems, and is not available
23711 in either HP Ada or GNAT.
23712
23713 @item
23714 @code{IEEE_Float} specifies that floating-point
23715 types are represented by default with the IEEE single and
23716 double floating-point types.
23717 @end itemize
23718
23719 @noindent
23720 GNAT provides an identical implementation of the pragma
23721 @code{Float_Representation}, except that it functions as a
23722 configuration pragma. Note that the
23723 notion of configuration pragma corresponds closely to the
23724 HP Ada notion of a program library switch.
23725
23726 When no pragma is used in GNAT, the default is @code{IEEE_Float},
23727 which is different
23728 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
23729 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
23730 advisable to change the format of numbers passed to standard library
23731 routines, and if necessary explicit type conversions may be needed.
23732
23733 The use of @code{IEEE_Float} is recommended in GNAT since it is more
23734 efficient, and (given that it conforms to an international standard)
23735 potentially more portable.
23736 The situation in which @code{VAX_Float} may be useful is in interfacing
23737 to existing code and data that expect the use of @code{VAX_Float}.
23738 In such a situation use the predefined @code{VAX_Float}
23739 types in package @code{System}, as extended by
23740 @code{Extend_System}. For example, use @code{System.F_Float}
23741 to specify the 32-bit @code{F-Float} format.
23742
23743 @noindent
23744 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
23745 to allow control over the internal representation chosen
23746 for the predefined type @code{Long_Float} and for floating-point
23747 type declarations with digits specified in the range 7 .. 15.
23748 The format of this pragma is as follows:
23749
23750 @smallexample @c ada
23751 @cartouche
23752 pragma Long_Float (D_FLOAT | G_FLOAT);
23753 @end cartouche
23754 @end smallexample
23755
23756 @node Fixed-Point Types and Representations
23757 @subsection Fixed-Point Types and Representations
23758
23759 @noindent
23760 On HP Ada for OpenVMS Alpha systems, rounding is
23761 away from zero for both positive and negative numbers.
23762 Therefore, @code{+0.5} rounds to @code{1},
23763 and @code{-0.5} rounds to @code{-1}.
23764
23765 On GNAT the results of operations
23766 on fixed-point types are in accordance with the Ada
23767 rules. In particular, results of operations on decimal
23768 fixed-point types are truncated.
23769
23770 @node Record and Array Component Alignment
23771 @subsection Record and Array Component Alignment
23772
23773 @noindent
23774 On HP Ada for OpenVMS Alpha, all non-composite components
23775 are aligned on natural boundaries. For example, 1-byte
23776 components are aligned on byte boundaries, 2-byte
23777 components on 2-byte boundaries, 4-byte components on 4-byte
23778 byte boundaries, and so on. The OpenVMS Alpha hardware
23779 runs more efficiently with naturally aligned data.
23780
23781 On GNAT, alignment rules are compatible
23782 with HP Ada for OpenVMS Alpha.
23783
23784 @node Address Clauses
23785 @subsection Address Clauses
23786
23787 @noindent
23788 In HP Ada and GNAT, address clauses are supported for
23789 objects and imported subprograms.
23790 The predefined type @code{System.Address} is a private type
23791 in both compilers on Alpha OpenVMS, with the same representation
23792 (it is simply a machine pointer). Addition, subtraction, and comparison
23793 operations are available in the standard Ada package
23794 @code{System.Storage_Elements}, or in package @code{System}
23795 if it is extended to include @code{System.Aux_DEC} using a
23796 pragma @code{Extend_System} as previously described.
23797
23798 Note that code that @code{with}'s both this extended package @code{System}
23799 and the package @code{System.Storage_Elements} should not @code{use}
23800 both packages, or ambiguities will result. In general it is better
23801 not to mix these two sets of facilities. The Ada package was
23802 designed specifically to provide the kind of features that HP Ada
23803 adds directly to package @code{System}.
23804
23805 The type @code{System.Address} is a 64-bit integer type in GNAT for
23806 I64 OpenVMS.  For more information,
23807 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23808
23809 GNAT is compatible with HP Ada in its handling of address
23810 clauses, except for some limitations in
23811 the form of address clauses for composite objects with
23812 initialization. Such address clauses are easily replaced
23813 by the use of an explicitly-defined constant as described
23814 in the Ada Reference Manual (13.1(22)). For example, the sequence
23815 of declarations:
23816
23817 @smallexample @c ada
23818 @cartouche
23819 X, Y : Integer := Init_Func;
23820 Q : String (X .. Y) := "abc";
23821 @dots{}
23822 for Q'Address use Compute_Address;
23823 @end cartouche
23824 @end smallexample
23825
23826 @noindent
23827 will be rejected by GNAT, since the address cannot be computed at the time
23828 that @code{Q} is declared. To achieve the intended effect, write instead:
23829
23830 @smallexample @c ada
23831 @group
23832 @cartouche
23833 X, Y : Integer := Init_Func;
23834 Q_Address : constant Address := Compute_Address;
23835 Q : String (X .. Y) := "abc";
23836 @dots{}
23837 for Q'Address use Q_Address;
23838 @end cartouche
23839 @end group
23840 @end smallexample
23841
23842 @noindent
23843 which will be accepted by GNAT (and other Ada compilers), and is also
23844 compatible with Ada 83. A fuller description of the restrictions
23845 on address specifications is found in @ref{Top, GNAT Reference Manual,
23846 About This Guide, gnat_rm, GNAT Reference Manual}.
23847
23848 @node Other Representation Clauses
23849 @subsection Other Representation Clauses
23850
23851 @noindent
23852 GNAT implements in a compatible manner all the representation
23853 clauses supported by HP Ada. In addition, GNAT
23854 implements the representation clause forms that were introduced in Ada 95,
23855 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
23856
23857 @node The Package STANDARD
23858 @section The Package @code{STANDARD}
23859
23860 @noindent
23861 The package @code{STANDARD}, as implemented by HP Ada, is fully
23862 described in the @cite{Ada Reference Manual} and in the
23863 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
23864 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
23865
23866 In addition, HP Ada supports the Latin-1 character set in
23867 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
23868 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
23869 the type @code{WIDE_CHARACTER}.
23870
23871 The floating-point types supported by GNAT are those
23872 supported by HP Ada, but the defaults are different, and are controlled by
23873 pragmas. See @ref{Floating-Point Types and Representations}, for details.
23874
23875 @node The Package SYSTEM
23876 @section The Package @code{SYSTEM}
23877
23878 @noindent
23879 HP Ada provides a specific version of the package
23880 @code{SYSTEM} for each platform on which the language is implemented.
23881 For the complete spec of the package @code{SYSTEM}, see
23882 Appendix F of the @cite{HP Ada Language Reference Manual}.
23883
23884 On HP Ada, the package @code{SYSTEM} includes the following conversion
23885 functions:
23886 @itemize @bullet
23887 @item @code{TO_ADDRESS(INTEGER)}
23888
23889 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
23890
23891 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
23892
23893 @item @code{TO_INTEGER(ADDRESS)}
23894
23895 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
23896
23897 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
23898 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
23899 @end itemize
23900
23901 @noindent
23902 By default, GNAT supplies a version of @code{SYSTEM} that matches
23903 the definition given in the @cite{Ada Reference Manual}.
23904 This
23905 is a subset of the HP system definitions, which is as
23906 close as possible to the original definitions. The only difference
23907 is that the definition of @code{SYSTEM_NAME} is different:
23908
23909 @smallexample @c ada
23910 @cartouche
23911 type Name is (SYSTEM_NAME_GNAT);
23912 System_Name : constant Name := SYSTEM_NAME_GNAT;
23913 @end cartouche
23914 @end smallexample
23915
23916 @noindent
23917 Also, GNAT adds the Ada declarations for
23918 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
23919
23920 However, the use of the following pragma causes GNAT
23921 to extend the definition of package @code{SYSTEM} so that it
23922 encompasses the full set of HP-specific extensions,
23923 including the functions listed above:
23924
23925 @smallexample @c ada
23926 @cartouche
23927 pragma Extend_System (Aux_DEC);
23928 @end cartouche
23929 @end smallexample
23930
23931 @noindent
23932 The pragma @code{Extend_System} is a configuration pragma that
23933 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
23934 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
23935
23936 HP Ada does not allow the recompilation of the package
23937 @code{SYSTEM}. Instead HP Ada provides several pragmas
23938 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
23939 to modify values in the package @code{SYSTEM}.
23940 On OpenVMS Alpha systems, the pragma
23941 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
23942 its single argument.
23943
23944 GNAT does permit the recompilation of package @code{SYSTEM} using
23945 the special switch @option{-gnatg}, and this switch can be used if
23946 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
23947 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
23948 or @code{MEMORY_SIZE} by any other means.
23949
23950 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
23951 enumeration literal @code{SYSTEM_NAME_GNAT}.
23952
23953 The definitions provided by the use of
23954
23955 @smallexample @c ada
23956 pragma Extend_System (AUX_Dec);
23957 @end smallexample
23958
23959 @noindent
23960 are virtually identical to those provided by the HP Ada 83 package
23961 @code{SYSTEM}. One important difference is that the name of the
23962 @code{TO_ADDRESS}
23963 function for type @code{UNSIGNED_LONGWORD} is changed to
23964 @code{TO_ADDRESS_LONG}.
23965 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
23966 discussion of why this change was necessary.
23967
23968 @noindent
23969 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
23970 is in fact
23971 an extension to Ada 83 not strictly compatible with the reference manual.
23972 GNAT, in order to be exactly compatible with the standard,
23973 does not provide this capability. In HP Ada 83, the
23974 point of this definition is to deal with a call like:
23975
23976 @smallexample @c ada
23977 TO_ADDRESS (16#12777#);
23978 @end smallexample
23979
23980 @noindent
23981 Normally, according to Ada 83 semantics, one would expect this to be
23982 ambiguous, since it matches both the @code{INTEGER} and
23983 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
23984 However, in HP Ada 83, there is no ambiguity, since the
23985 definition using @i{universal_integer} takes precedence.
23986
23987 In GNAT, since the version with @i{universal_integer} cannot be supplied,
23988 it is
23989 not possible to be 100% compatible. Since there are many programs using
23990 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
23991 GNAT was
23992 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
23993 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
23994
23995 @smallexample @c ada
23996 function To_Address (X : Integer) return Address;
23997 pragma Pure_Function (To_Address);
23998
23999 function To_Address_Long (X : Unsigned_Longword) return Address;
24000 pragma Pure_Function (To_Address_Long);
24001 @end smallexample
24002
24003 @noindent
24004 This means that programs using @code{TO_ADDRESS} for
24005 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24006
24007 @node Tasking and Task-Related Features
24008 @section Tasking and Task-Related Features
24009
24010 @noindent
24011 This section compares the treatment of tasking in GNAT
24012 and in HP Ada for OpenVMS Alpha.
24013 The GNAT description applies to both Alpha and I64 OpenVMS.
24014 For detailed information on tasking in
24015 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24016 relevant run-time reference manual.
24017
24018 @menu
24019 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24020 * Assigning Task IDs::
24021 * Task IDs and Delays::
24022 * Task-Related Pragmas::
24023 * Scheduling and Task Priority::
24024 * The Task Stack::
24025 * External Interrupts::
24026 @end menu
24027
24028 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24029 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24030
24031 @noindent
24032 On OpenVMS Alpha systems, each Ada task (except a passive
24033 task) is implemented as a single stream of execution
24034 that is created and managed by the kernel. On these
24035 systems, HP Ada tasking support is based on DECthreads,
24036 an implementation of the POSIX standard for threads.
24037
24038 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24039 code that calls DECthreads routines can be used together.
24040 The interaction between Ada tasks and DECthreads routines
24041 can have some benefits. For example when on OpenVMS Alpha,
24042 HP Ada can call C code that is already threaded.
24043
24044 GNAT uses the facilities of DECthreads,
24045 and Ada tasks are mapped to threads.
24046
24047 @node Assigning Task IDs
24048 @subsection Assigning Task IDs
24049
24050 @noindent
24051 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24052 the environment task that executes the main program. On
24053 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24054 that have been created but are not yet activated.
24055
24056 On OpenVMS Alpha systems, task IDs are assigned at
24057 activation. On GNAT systems, task IDs are also assigned at
24058 task creation but do not have the same form or values as
24059 task ID values in HP Ada. There is no null task, and the
24060 environment task does not have a specific task ID value.
24061
24062 @node Task IDs and Delays
24063 @subsection Task IDs and Delays
24064
24065 @noindent
24066 On OpenVMS Alpha systems, tasking delays are implemented
24067 using Timer System Services. The Task ID is used for the
24068 identification of the timer request (the @code{REQIDT} parameter).
24069 If Timers are used in the application take care not to use
24070 @code{0} for the identification, because cancelling such a timer
24071 will cancel all timers and may lead to unpredictable results.
24072
24073 @node Task-Related Pragmas
24074 @subsection Task-Related Pragmas
24075
24076 @noindent
24077 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24078 specification of the size of the guard area for a task
24079 stack. (The guard area forms an area of memory that has no
24080 read or write access and thus helps in the detection of
24081 stack overflow.) On OpenVMS Alpha systems, if the pragma
24082 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24083 area is created. In the absence of a pragma @code{TASK_STORAGE},
24084 a default guard area is created.
24085
24086 GNAT supplies the following task-related pragmas:
24087
24088 @itemize @bullet
24089 @item  @code{TASK_INFO}
24090
24091 This pragma appears within a task definition and
24092 applies to the task in which it appears. The argument
24093 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
24094
24095 @item  @code{TASK_STORAGE}
24096
24097 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
24098 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
24099 @code{SUPPRESS}, and @code{VOLATILE}.
24100 @end itemize
24101 @node Scheduling and Task Priority
24102 @subsection Scheduling and Task Priority
24103
24104 @noindent
24105 HP Ada implements the Ada language requirement that
24106 when two tasks are eligible for execution and they have
24107 different priorities, the lower priority task does not
24108 execute while the higher priority task is waiting. The HP
24109 Ada Run-Time Library keeps a task running until either the
24110 task is suspended or a higher priority task becomes ready.
24111
24112 On OpenVMS Alpha systems, the default strategy is round-
24113 robin with preemption. Tasks of equal priority take turns
24114 at the processor. A task is run for a certain period of
24115 time and then placed at the tail of the ready queue for
24116 its priority level.
24117
24118 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
24119 which can be used to enable or disable round-robin
24120 scheduling of tasks with the same priority.
24121 See the relevant HP Ada run-time reference manual for
24122 information on using the pragmas to control HP Ada task
24123 scheduling.
24124
24125 GNAT follows the scheduling rules of Annex D (Real-Time
24126 Annex) of the @cite{Ada Reference Manual}. In general, this
24127 scheduling strategy is fully compatible with HP Ada
24128 although it provides some additional constraints (as
24129 fully documented in Annex D).
24130 GNAT implements time slicing control in a manner compatible with
24131 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
24132 are identical to the HP Ada 83 pragma of the same name.
24133 Note that it is not possible to mix GNAT tasking and
24134 HP Ada 83 tasking in the same program, since the two run-time
24135 libraries are not compatible.
24136
24137 @node The Task Stack
24138 @subsection The Task Stack
24139
24140 @noindent
24141 In HP Ada, a task stack is allocated each time a
24142 non-passive task is activated. As soon as the task is
24143 terminated, the storage for the task stack is deallocated.
24144 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
24145 a default stack size is used. Also, regardless of the size
24146 specified, some additional space is allocated for task
24147 management purposes. On OpenVMS Alpha systems, at least
24148 one page is allocated.
24149
24150 GNAT handles task stacks in a similar manner. In accordance with
24151 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
24152 an alternative method for controlling the task stack size.
24153 The specification of the attribute @code{T'STORAGE_SIZE} is also
24154 supported in a manner compatible with HP Ada.
24155
24156 @node External Interrupts
24157 @subsection External Interrupts
24158
24159 @noindent
24160 On HP Ada, external interrupts can be associated with task entries.
24161 GNAT is compatible with HP Ada in its handling of external interrupts.
24162
24163 @node Pragmas and Pragma-Related Features
24164 @section Pragmas and Pragma-Related Features
24165
24166 @noindent
24167 Both HP Ada and GNAT supply all language-defined pragmas
24168 as specified by the Ada 83 standard. GNAT also supplies all
24169 language-defined pragmas introduced by Ada 95 and Ada 2005.
24170 In addition, GNAT implements the implementation-defined pragmas
24171 from HP Ada 83.
24172
24173 @itemize @bullet
24174 @item  @code{AST_ENTRY}
24175
24176 @item  @code{COMMON_OBJECT}
24177
24178 @item  @code{COMPONENT_ALIGNMENT}
24179
24180 @item  @code{EXPORT_EXCEPTION}
24181
24182 @item  @code{EXPORT_FUNCTION}
24183
24184 @item  @code{EXPORT_OBJECT}
24185
24186 @item  @code{EXPORT_PROCEDURE}
24187
24188 @item  @code{EXPORT_VALUED_PROCEDURE}
24189
24190 @item  @code{FLOAT_REPRESENTATION}
24191
24192 @item  @code{IDENT}
24193
24194 @item  @code{IMPORT_EXCEPTION}
24195
24196 @item  @code{IMPORT_FUNCTION}
24197
24198 @item  @code{IMPORT_OBJECT}
24199
24200 @item  @code{IMPORT_PROCEDURE}
24201
24202 @item  @code{IMPORT_VALUED_PROCEDURE}
24203
24204 @item  @code{INLINE_GENERIC}
24205
24206 @item  @code{INTERFACE_NAME}
24207
24208 @item  @code{LONG_FLOAT}
24209
24210 @item  @code{MAIN_STORAGE}
24211
24212 @item  @code{PASSIVE}
24213
24214 @item  @code{PSECT_OBJECT}
24215
24216 @item  @code{SHARE_GENERIC}
24217
24218 @item  @code{SUPPRESS_ALL}
24219
24220 @item  @code{TASK_STORAGE}
24221
24222 @item  @code{TIME_SLICE}
24223
24224 @item  @code{TITLE}
24225 @end itemize
24226
24227 @noindent
24228 These pragmas are all fully implemented, with the exception of @code{TITLE},
24229 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
24230 recognized, but which have no
24231 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
24232 use of Ada protected objects. In GNAT, all generics are inlined.
24233
24234 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
24235 a separate subprogram specification which must appear before the
24236 subprogram body.
24237
24238 GNAT also supplies a number of implementation-defined pragmas as follows:
24239 @itemize @bullet
24240 @item  @code{ABORT_DEFER}
24241
24242 @item  @code{ADA_83}
24243
24244 @item  @code{ADA_95}
24245
24246 @item  @code{ADA_05}
24247
24248 @item  @code{ANNOTATE}
24249
24250 @item  @code{ASSERT}
24251
24252 @item  @code{C_PASS_BY_COPY}
24253
24254 @item  @code{CPP_CLASS}
24255
24256 @item  @code{CPP_CONSTRUCTOR}
24257
24258 @item  @code{CPP_DESTRUCTOR}
24259
24260 @item  @code{DEBUG}
24261
24262 @item  @code{EXTEND_SYSTEM}
24263
24264 @item  @code{LINKER_ALIAS}
24265
24266 @item  @code{LINKER_SECTION}
24267
24268 @item  @code{MACHINE_ATTRIBUTE}
24269
24270 @item  @code{NO_RETURN}
24271
24272 @item  @code{PURE_FUNCTION}
24273
24274 @item  @code{SOURCE_FILE_NAME}
24275
24276 @item  @code{SOURCE_REFERENCE}
24277
24278 @item  @code{TASK_INFO}
24279
24280 @item  @code{UNCHECKED_UNION}
24281
24282 @item  @code{UNIMPLEMENTED_UNIT}
24283
24284 @item  @code{UNIVERSAL_DATA}
24285
24286 @item  @code{UNSUPPRESS}
24287
24288 @item  @code{WARNINGS}
24289
24290 @item  @code{WEAK_EXTERNAL}
24291 @end itemize
24292
24293 @noindent
24294 For full details on these GNAT implementation-defined pragmas,
24295 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
24296 Manual}.
24297
24298 @menu
24299 * Restrictions on the Pragma INLINE::
24300 * Restrictions on the Pragma INTERFACE::
24301 * Restrictions on the Pragma SYSTEM_NAME::
24302 @end menu
24303
24304 @node Restrictions on the Pragma INLINE
24305 @subsection Restrictions on Pragma @code{INLINE}
24306
24307 @noindent
24308 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
24309 @itemize @bullet
24310 @item  Parameters cannot have a task type.
24311
24312 @item  Function results cannot be task types, unconstrained
24313 array types, or unconstrained types with discriminants.
24314
24315 @item  Bodies cannot declare the following:
24316 @itemize @bullet
24317 @item  Subprogram body or stub (imported subprogram is allowed)
24318
24319 @item  Tasks
24320
24321 @item  Generic declarations
24322
24323 @item  Instantiations
24324
24325 @item  Exceptions
24326
24327 @item  Access types (types derived from access types allowed)
24328
24329 @item  Array or record types
24330
24331 @item  Dependent tasks
24332
24333 @item  Direct recursive calls of subprogram or containing
24334 subprogram, directly or via a renaming
24335
24336 @end itemize
24337 @end itemize
24338
24339 @noindent
24340 In GNAT, the only restriction on pragma @code{INLINE} is that the
24341 body must occur before the call if both are in the same
24342 unit, and the size must be appropriately small. There are
24343 no other specific restrictions which cause subprograms to
24344 be incapable of being inlined.
24345
24346 @node  Restrictions on the Pragma INTERFACE
24347 @subsection  Restrictions on Pragma @code{INTERFACE}
24348
24349 @noindent
24350 The following restrictions on pragma @code{INTERFACE}
24351 are enforced by both HP Ada and GNAT:
24352 @itemize @bullet
24353 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
24354 Default is the default on OpenVMS Alpha systems.
24355
24356 @item  Parameter passing: Language specifies default
24357 mechanisms but can be overridden with an @code{EXPORT} pragma.
24358
24359 @itemize @bullet
24360 @item  Ada: Use internal Ada rules.
24361
24362 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
24363 record or task type. Result cannot be a string, an
24364 array, or a record.
24365
24366 @item  Fortran: Parameters cannot have a task type. Result cannot
24367 be a string, an array, or a record.
24368 @end itemize
24369 @end itemize
24370
24371 @noindent
24372 GNAT is entirely upwards compatible with HP Ada, and in addition allows
24373 record parameters for all languages.
24374
24375 @node  Restrictions on the Pragma SYSTEM_NAME
24376 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
24377
24378 @noindent
24379 For HP Ada for OpenVMS Alpha, the enumeration literal
24380 for the type @code{NAME} is @code{OPENVMS_AXP}.
24381 In GNAT, the enumeration
24382 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
24383
24384 @node  Library of Predefined Units
24385 @section  Library of Predefined Units
24386
24387 @noindent
24388 A library of predefined units is provided as part of the
24389 HP Ada and GNAT implementations. HP Ada does not provide
24390 the package @code{MACHINE_CODE} but instead recommends importing
24391 assembler code.
24392
24393 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
24394 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
24395 version.
24396 The HP Ada Predefined Library units are modified to remove post-Ada 83
24397 incompatibilities and to make them interoperable with GNAT
24398 (@pxref{Changes to DECLIB}, for details).
24399 The units are located in the @file{DECLIB} directory.
24400
24401 The GNAT RTL is contained in
24402 the @file{ADALIB} directory, and
24403 the default search path is set up to find @code{DECLIB} units in preference
24404 to @code{ADALIB} units with the same name (@code{TEXT_IO},
24405 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
24406
24407 @menu
24408 * Changes to DECLIB::
24409 @end menu
24410
24411 @node Changes to DECLIB
24412 @subsection Changes to @code{DECLIB}
24413
24414 @noindent
24415 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
24416 compatibility are minor and include the following:
24417
24418 @itemize @bullet
24419 @item  Adjusting the location of pragmas and record representation
24420 clauses to obey Ada 95 (and thus Ada 2005) rules
24421
24422 @item  Adding the proper notation to generic formal parameters
24423 that take unconstrained types in instantiation
24424
24425 @item  Adding pragma @code{ELABORATE_BODY} to package specs
24426 that have package bodies not otherwise allowed
24427
24428 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
24429 ``@code{PROTECTD}''.
24430 Currently these are found only in the @code{STARLET} package spec.
24431
24432 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
24433 where the address size is constrained to 32 bits.
24434 @end itemize
24435
24436 @noindent
24437 None of the above changes is visible to users.
24438
24439 @node Bindings
24440 @section Bindings
24441
24442 @noindent
24443 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
24444 @itemize @bullet
24445
24446 @item  Command Language Interpreter (CLI interface)
24447
24448 @item  DECtalk Run-Time Library (DTK interface)
24449
24450 @item  Librarian utility routines (LBR interface)
24451
24452 @item  General Purpose Run-Time Library (LIB interface)
24453
24454 @item  Math Run-Time Library (MTH interface)
24455
24456 @item  National Character Set Run-Time Library (NCS interface)
24457
24458 @item  Compiled Code Support Run-Time Library (OTS interface)
24459
24460 @item  Parallel Processing Run-Time Library (PPL interface)
24461
24462 @item  Screen Management Run-Time Library (SMG interface)
24463
24464 @item  Sort Run-Time Library (SOR interface)
24465
24466 @item  String Run-Time Library (STR interface)
24467
24468 @item STARLET System Library
24469 @findex Starlet
24470
24471 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
24472
24473 @item  X Windows Toolkit (XT interface)
24474
24475 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
24476 @end itemize
24477
24478 @noindent
24479 GNAT provides implementations of these HP bindings in the @code{DECLIB}
24480 directory, on both the Alpha and I64 OpenVMS platforms.
24481
24482 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
24483 in the
24484 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
24485 A pragma @code{Linker_Options} has been added to packages @code{Xm},
24486 @code{Xt}, and @code{X_Lib}
24487 causing the default X/Motif sharable image libraries to be linked in. This
24488 is done via options files named @file{xm.opt}, @file{xt.opt}, and
24489 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
24490
24491 It may be necessary to edit these options files to update or correct the
24492 library names if, for example, the newer X/Motif bindings from
24493 @file{ADA$EXAMPLES}
24494 had been (previous to installing GNAT) copied and renamed to supersede the
24495 default @file{ADA$PREDEFINED} versions.
24496
24497 @menu
24498 * Shared Libraries and Options Files::
24499 * Interfaces to C::
24500 @end menu
24501
24502 @node Shared Libraries and Options Files
24503 @subsection Shared Libraries and Options Files
24504
24505 @noindent
24506 When using the HP Ada
24507 predefined X and Motif bindings, the linking with their sharable images is
24508 done automatically by @command{GNAT LINK}.
24509 When using other X and Motif bindings, you need
24510 to add the corresponding sharable images to the command line for
24511 @code{GNAT LINK}. When linking with shared libraries, or with
24512 @file{.OPT} files, you must
24513 also add them to the command line for @command{GNAT LINK}.
24514
24515 A shared library to be used with GNAT is built in the same way as other
24516 libraries under VMS. The VMS Link command can be used in standard fashion.
24517
24518 @node Interfaces to C
24519 @subsection Interfaces to C
24520
24521 @noindent
24522 HP Ada
24523 provides the following Ada types and operations:
24524
24525 @itemize @bullet
24526 @item C types package (@code{C_TYPES})
24527
24528 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24529
24530 @item Other_types (@code{SHORT_INT})
24531 @end itemize
24532
24533 @noindent
24534 Interfacing to C with GNAT, you can use the above approach
24535 described for HP Ada or the facilities of Annex B of
24536 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24537 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24538 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
24539
24540 The @option{-gnatF} qualifier forces default and explicit
24541 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24542 to be uppercased for compatibility with the default behavior
24543 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24544
24545 @node Main Program Definition
24546 @section Main Program Definition
24547
24548 @noindent
24549 The following section discusses differences in the
24550 definition of main programs on HP Ada and GNAT.
24551 On HP Ada, main programs are defined to meet the
24552 following conditions:
24553 @itemize @bullet
24554 @item  Procedure with no formal parameters (returns @code{0} upon
24555 normal completion)
24556
24557 @item  Procedure with no formal parameters (returns @code{42} when
24558 an unhandled exception is raised)
24559
24560 @item  Function with no formal parameters whose returned value
24561 is of a discrete type
24562
24563 @item  Procedure with one @code{out} formal of a discrete type for
24564 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
24565
24566 @end itemize
24567
24568 @noindent
24569 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24570 a main function or main procedure returns a discrete
24571 value whose size is less than 64 bits (32 on VAX systems),
24572 the value is zero- or sign-extended as appropriate.
24573 On GNAT, main programs are defined as follows:
24574 @itemize @bullet
24575 @item  Must be a non-generic, parameterless subprogram that
24576 is either a procedure or function returning an Ada
24577 @code{STANDARD.INTEGER} (the predefined type)
24578
24579 @item  Cannot be a generic subprogram or an instantiation of a
24580 generic subprogram
24581 @end itemize
24582
24583 @node Implementation-Defined Attributes
24584 @section Implementation-Defined Attributes
24585
24586 @noindent
24587 GNAT provides all HP Ada implementation-defined
24588 attributes.
24589
24590 @node Compiler and Run-Time Interfacing
24591 @section Compiler and Run-Time Interfacing
24592
24593 @noindent
24594 HP Ada provides the following qualifiers to pass options to the linker
24595 (ACS LINK):
24596 @itemize @bullet
24597 @item  @option{/WAIT} and @option{/SUBMIT}
24598
24599 @item  @option{/COMMAND}
24600
24601 @item  @option{/@r{[}NO@r{]}MAP}
24602
24603 @item  @option{/OUTPUT=@var{file-spec}}
24604
24605 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
24606 @end itemize
24607
24608 @noindent
24609 To pass options to the linker, GNAT provides the following
24610 switches:
24611
24612 @itemize @bullet
24613 @item   @option{/EXECUTABLE=@var{exec-name}}
24614
24615 @item   @option{/VERBOSE}
24616
24617 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
24618 @end itemize
24619
24620 @noindent
24621 For more information on these switches, see
24622 @ref{Switches for gnatlink}.
24623 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
24624 to control optimization. HP Ada also supplies the
24625 following pragmas:
24626 @itemize @bullet
24627 @item  @code{OPTIMIZE}
24628
24629 @item  @code{INLINE}
24630
24631 @item  @code{INLINE_GENERIC}
24632
24633 @item  @code{SUPPRESS_ALL}
24634
24635 @item  @code{PASSIVE}
24636 @end itemize
24637
24638 @noindent
24639 In GNAT, optimization is controlled strictly by command
24640 line parameters, as described in the corresponding section of this guide.
24641 The HP pragmas for control of optimization are
24642 recognized but ignored.
24643
24644 Note that in GNAT, the default is optimization off, whereas in HP Ada
24645 the default is that optimization is turned on.
24646
24647 @node Program Compilation and Library Management
24648 @section Program Compilation and Library Management
24649
24650 @noindent
24651 HP Ada and GNAT provide a comparable set of commands to
24652 build programs. HP Ada also provides a program library,
24653 which is a concept that does not exist on GNAT. Instead,
24654 GNAT provides directories of sources that are compiled as
24655 needed.
24656
24657 The following table summarizes
24658 the HP Ada commands and provides
24659 equivalent GNAT commands. In this table, some GNAT
24660 equivalents reflect the fact that GNAT does not use the
24661 concept of a program library. Instead, it uses a model
24662 in which collections of source and object files are used
24663 in a manner consistent with other languages like C and
24664 Fortran. Therefore, standard system file commands are used
24665 to manipulate these elements. Those GNAT commands are marked with
24666 an asterisk.
24667 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
24668
24669 @need 1500
24670 @multitable @columnfractions .35 .65
24671
24672 @item @emph{HP Ada Command}
24673 @tab @emph{GNAT Equivalent / Description}
24674
24675 @item @command{ADA}
24676 @tab @command{GNAT COMPILE}@*
24677 Invokes the compiler to compile one or more Ada source files.
24678
24679 @item @command{ACS ATTACH}@*
24680 @tab [No equivalent]@*
24681 Switches control of terminal from current process running the program
24682 library manager.
24683
24684 @item @command{ACS CHECK}
24685 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
24686 Forms the execution closure of one
24687 or more compiled units and checks completeness and currency.
24688
24689 @item @command{ACS COMPILE}
24690 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24691 Forms the execution closure of one or
24692 more specified units, checks completeness and currency,
24693 identifies units that have revised source files, compiles same,
24694 and recompiles units that are or will become obsolete.
24695 Also completes incomplete generic instantiations.
24696
24697 @item @command{ACS COPY FOREIGN}
24698 @tab Copy (*)@*
24699 Copies a foreign object file into the program library as a
24700 library unit body.
24701
24702 @item @command{ACS COPY UNIT}
24703 @tab Copy (*)@*
24704 Copies a compiled unit from one program library to another.
24705
24706 @item @command{ACS CREATE LIBRARY}
24707 @tab Create /directory (*)@*
24708 Creates a program library.
24709
24710 @item @command{ACS CREATE SUBLIBRARY}
24711 @tab Create /directory (*)@*
24712 Creates a program sublibrary.
24713
24714 @item @command{ACS DELETE LIBRARY}
24715 @tab @*
24716 Deletes a program library and its contents.
24717
24718 @item @command{ACS DELETE SUBLIBRARY}
24719 @tab @*
24720 Deletes a program sublibrary and its contents.
24721
24722 @item @command{ACS DELETE UNIT}
24723 @tab Delete file (*)@*
24724 On OpenVMS systems, deletes one or more compiled units from
24725 the current program library.
24726
24727 @item @command{ACS DIRECTORY}
24728 @tab Directory (*)@*
24729 On OpenVMS systems, lists units contained in the current
24730 program library.
24731
24732 @item @command{ACS ENTER FOREIGN}
24733 @tab Copy (*)@*
24734 Allows the import of a foreign body as an Ada library
24735 spec and enters a reference to a pointer.
24736
24737 @item @command{ACS ENTER UNIT}
24738 @tab Copy (*)@*
24739 Enters a reference (pointer) from the current program library to
24740 a unit compiled into another program library.
24741
24742 @item @command{ACS EXIT}
24743 @tab [No equivalent]@*
24744 Exits from the program library manager.
24745
24746 @item @command{ACS EXPORT}
24747 @tab Copy (*)@*
24748 Creates an object file that contains system-specific object code
24749 for one or more units. With GNAT, object files can simply be copied
24750 into the desired directory.
24751
24752 @item @command{ACS EXTRACT SOURCE}
24753 @tab Copy (*)@*
24754 Allows access to the copied source file for each Ada compilation unit
24755
24756 @item @command{ACS HELP}
24757 @tab @command{HELP GNAT}@*
24758 Provides online help.
24759
24760 @item @command{ACS LINK}
24761 @tab @command{GNAT LINK}@*
24762 Links an object file containing Ada units into an executable file.
24763
24764 @item @command{ACS LOAD}
24765 @tab Copy (*)@*
24766 Loads (partially compiles) Ada units into the program library.
24767 Allows loading a program from a collection of files into a library
24768 without knowing the relationship among units.
24769
24770 @item @command{ACS MERGE}
24771 @tab Copy (*)@*
24772 Merges into the current program library, one or more units from
24773 another library where they were modified.
24774
24775 @item @command{ACS RECOMPILE}
24776 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24777 Recompiles from   external or copied source files any obsolete
24778 unit in the closure. Also, completes any incomplete generic
24779 instantiations.
24780
24781 @item @command{ACS REENTER}
24782 @tab @command{GNAT MAKE}@*
24783 Reenters current references to units compiled after last entered
24784 with the @command{ACS ENTER UNIT} command.
24785
24786 @item @command{ACS SET LIBRARY}
24787 @tab Set default (*)@*
24788 Defines a program library to be the compilation context as well
24789 as the target library for compiler output and commands in general.
24790
24791 @item @command{ACS SET PRAGMA}
24792 @tab Edit @file{gnat.adc} (*)@*
24793 Redefines specified  values of the library characteristics
24794 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
24795 and @code{Float_Representation}.
24796
24797 @item @command{ACS SET SOURCE}
24798 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
24799 Defines the source file search list for the @command{ACS COMPILE} command.
24800
24801 @item @command{ACS SHOW LIBRARY}
24802 @tab Directory (*)@*
24803 Lists information about one or more program libraries.
24804
24805 @item @command{ACS SHOW PROGRAM}
24806 @tab [No equivalent]@*
24807 Lists information about the execution closure of one or
24808 more units in the program library.
24809
24810 @item @command{ACS SHOW SOURCE}
24811 @tab Show logical @code{ADA_INCLUDE_PATH}@*
24812 Shows the source file search used when compiling units.
24813
24814 @item @command{ACS SHOW VERSION}
24815 @tab Compile with @option{VERBOSE} option
24816 Displays the version number of the compiler and program library
24817 manager used.
24818
24819 @item @command{ACS SPAWN}
24820 @tab [No equivalent]@*
24821 Creates a subprocess of the current process (same as @command{DCL SPAWN}
24822 command).
24823
24824 @item @command{ACS VERIFY}
24825 @tab [No equivalent]@*
24826 Performs a series of consistency checks on a program library to
24827 determine whether the library structure and library files are in
24828 valid form.
24829 @end multitable
24830
24831 @noindent
24832
24833 @node Input-Output
24834 @section Input-Output
24835
24836 @noindent
24837 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
24838 Management Services (RMS) to perform operations on
24839 external files.
24840
24841 @noindent
24842 HP Ada and GNAT predefine an identical set of input-
24843 output packages. To make the use of the
24844 generic @code{TEXT_IO} operations more convenient, HP Ada
24845 provides predefined library packages that instantiate the
24846 integer and floating-point operations for the predefined
24847 integer and floating-point types as shown in the following table.
24848
24849 @multitable @columnfractions .45 .55
24850 @item @emph{Package Name} @tab Instantiation
24851
24852 @item @code{INTEGER_TEXT_IO}
24853 @tab @code{INTEGER_IO(INTEGER)}
24854
24855 @item @code{SHORT_INTEGER_TEXT_IO}
24856 @tab @code{INTEGER_IO(SHORT_INTEGER)}
24857
24858 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
24859 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
24860
24861 @item @code{FLOAT_TEXT_IO}
24862 @tab @code{FLOAT_IO(FLOAT)}
24863
24864 @item @code{LONG_FLOAT_TEXT_IO}
24865 @tab @code{FLOAT_IO(LONG_FLOAT)}
24866 @end multitable
24867
24868 @noindent
24869 The HP Ada predefined packages and their operations
24870 are implemented using OpenVMS Alpha files and input-output
24871 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
24872 Familiarity with the following is recommended:
24873 @itemize @bullet
24874 @item  RMS file organizations and access methods
24875
24876 @item  OpenVMS file specifications and directories
24877
24878 @item  OpenVMS File Definition Language (FDL)
24879 @end itemize
24880
24881 @noindent
24882 GNAT provides I/O facilities that are completely
24883 compatible with HP Ada. The distribution includes the
24884 standard HP Ada versions of all I/O packages, operating
24885 in a manner compatible with HP Ada. In particular, the
24886 following packages are by default the HP Ada (Ada 83)
24887 versions of these packages rather than the renamings
24888 suggested in Annex J of the Ada Reference Manual:
24889 @itemize @bullet
24890 @item  @code{TEXT_IO}
24891
24892 @item  @code{SEQUENTIAL_IO}
24893
24894 @item  @code{DIRECT_IO}
24895 @end itemize
24896
24897 @noindent
24898 The use of the standard child package syntax (for
24899 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
24900 packages.
24901 GNAT provides HP-compatible predefined instantiations
24902 of the @code{TEXT_IO} packages, and also
24903 provides the standard predefined instantiations required
24904 by the @cite{Ada Reference Manual}.
24905
24906 For further information on how GNAT interfaces to the file
24907 system or how I/O is implemented in programs written in
24908 mixed languages, see @ref{Implementation of the Standard I/O,,,
24909 gnat_rm, GNAT Reference Manual}.
24910 This chapter covers the following:
24911 @itemize @bullet
24912 @item  Standard I/O packages
24913
24914 @item  @code{FORM} strings
24915
24916 @item  @code{ADA.DIRECT_IO}
24917
24918 @item  @code{ADA.SEQUENTIAL_IO}
24919
24920 @item  @code{ADA.TEXT_IO}
24921
24922 @item  Stream pointer positioning
24923
24924 @item  Reading and writing non-regular files
24925
24926 @item  @code{GET_IMMEDIATE}
24927
24928 @item  Treating @code{TEXT_IO} files as streams
24929
24930 @item  Shared files
24931
24932 @item  Open modes
24933 @end itemize
24934
24935 @node Implementation Limits
24936 @section Implementation Limits
24937
24938 @noindent
24939 The following table lists implementation limits for HP Ada
24940 and GNAT systems.
24941 @multitable @columnfractions .60 .20 .20
24942 @sp 1
24943 @item  @emph{Compilation Parameter}
24944 @tab   @emph{HP Ada}
24945 @tab   @emph{GNAT}
24946 @sp 1
24947
24948 @item  In a subprogram or entry  declaration, maximum number of
24949 formal parameters that are of an unconstrained record type
24950 @tab   32
24951 @tab   No set limit
24952 @sp 1
24953
24954 @item  Maximum identifier length (number of characters)
24955 @tab   255
24956 @tab   32766
24957 @sp 1
24958
24959 @item  Maximum number of characters in a source line
24960 @tab   255
24961 @tab   32766
24962 @sp 1
24963
24964 @item  Maximum collection size   (number of bytes)
24965 @tab   2**31-1
24966 @tab   2**31-1
24967 @sp 1
24968
24969 @item  Maximum number of discriminants for a record type
24970 @tab   245
24971 @tab   No set limit
24972 @sp 1
24973
24974 @item  Maximum number of formal parameters in an entry or
24975 subprogram declaration
24976 @tab   246
24977 @tab    No set limit
24978 @sp 1
24979
24980 @item  Maximum number of dimensions in an array type
24981 @tab   255
24982 @tab   No set limit
24983 @sp 1
24984
24985 @item  Maximum number of library  units and subunits in a compilation.
24986 @tab   4095
24987 @tab   No set limit
24988 @sp 1
24989
24990 @item  Maximum number of library units and subunits in an execution.
24991 @tab   16383
24992 @tab   No set limit
24993 @sp 1
24994
24995 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
24996 or @code{PSECT_OBJECT}
24997 @tab   32757
24998 @tab   No set limit
24999 @sp 1
25000
25001 @item  Maximum number of enumeration literals in an enumeration type
25002 definition
25003 @tab   65535
25004 @tab   No set limit
25005 @sp 1
25006
25007 @item  Maximum number of lines in a source file
25008 @tab   65534
25009 @tab   No set limit
25010 @sp 1
25011
25012 @item  Maximum number of bits in any object
25013 @tab   2**31-1
25014 @tab   2**31-1
25015 @sp 1
25016
25017 @item  Maximum size of the static portion of a stack frame (approximate)
25018 @tab   2**31-1
25019 @tab   2**31-1
25020 @end multitable
25021
25022 @node Tools and Utilities
25023 @section Tools and Utilities
25024
25025 @noindent
25026 The following table lists some of the OpenVMS development tools
25027 available for HP Ada, and the corresponding tools for
25028 use with @value{EDITION} on Alpha and I64 platforms.
25029 Aside from the debugger, all the OpenVMS tools identified are part
25030 of the DECset package.
25031
25032 @iftex
25033 @c Specify table in TeX since Texinfo does a poor job
25034 @tex
25035 \smallskip
25036 \smallskip
25037 \settabs\+Language-Sensitive Editor\quad
25038    &Product with HP Ada\quad
25039    &\cr
25040 \+\it Tool
25041    &\it Product with HP Ada
25042    & \it Product with GNAT Pro\cr
25043 \smallskip
25044 \+Code Management System
25045    &HP CMS
25046    & HP CMS\cr
25047 \smallskip
25048 \+Language-Sensitive Editor
25049    &HP LSE
25050    & emacs or HP LSE (Alpha)\cr
25051 \+
25052    &
25053    & HP LSE (I64)\cr
25054 \smallskip
25055 \+Debugger
25056    &OpenVMS Debug
25057    & gdb (Alpha),\cr
25058 \+
25059    &
25060    & OpenVMS Debug (I64)\cr
25061 \smallskip
25062 \+Source Code Analyzer /
25063    &HP SCA
25064    & GNAT XREF\cr
25065 \+Cross Referencer
25066    &
25067    &\cr
25068 \smallskip
25069 \+Test Manager
25070    &HP Digital Test
25071    & HP DTM\cr
25072 \+
25073    &Manager (DTM)
25074    &\cr
25075 \smallskip
25076 \+Performance and
25077    & HP PCA
25078    & HP PCA\cr
25079 \+Coverage Analyzer
25080    &
25081    &\cr
25082 \smallskip
25083 \+Module Management
25084    & HP MMS
25085    & Not applicable\cr
25086 \+ System
25087    &
25088    &\cr
25089 \smallskip
25090 \smallskip
25091 @end tex
25092 @end iftex
25093
25094 @ifnottex
25095 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
25096 @c the TeX version above for the printed version
25097 @flushleft
25098 @c @multitable @columnfractions .3 .4 .4
25099 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
25100 @item @i{Tool}
25101 @tab @i{Tool with HP Ada}
25102 @tab @i{Tool with @value{EDITION}}
25103 @item Code Management@*System
25104 @tab HP CMS
25105 @tab HP CMS
25106 @item Language-Sensitive@*Editor
25107 @tab HP LSE
25108 @tab emacs or HP LSE (Alpha)
25109 @item
25110 @tab
25111 @tab HP LSE (I64)
25112 @item Debugger
25113 @tab OpenVMS Debug
25114 @tab gdb (Alpha),
25115 @item
25116 @tab
25117 @tab OpenVMS Debug (I64)
25118 @item Source Code Analyzer /@*Cross Referencer
25119 @tab HP SCA
25120 @tab GNAT XREF
25121 @item Test Manager
25122 @tab HP Digital Test@*Manager (DTM)
25123 @tab HP DTM
25124 @item Performance and@*Coverage Analyzer
25125 @tab HP PCA
25126 @tab HP PCA
25127 @item Module Management@*System
25128 @tab HP MMS
25129 @tab Not applicable
25130 @end multitable
25131 @end flushleft
25132 @end ifnottex
25133
25134 @end ifset
25135
25136 @c **************************************
25137 @node Platform-Specific Information for the Run-Time Libraries
25138 @appendix Platform-Specific Information for the Run-Time Libraries
25139 @cindex Tasking and threads libraries
25140 @cindex Threads libraries and tasking
25141 @cindex Run-time libraries (platform-specific information)
25142
25143 @noindent
25144 The GNAT run-time implementation may vary with respect to both the
25145 underlying threads library and the exception handling scheme.
25146 For threads support, one or more of the following are supplied:
25147 @itemize @bullet
25148 @item @b{native threads library}, a binding to the thread package from
25149 the underlying operating system
25150
25151 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
25152 POSIX thread package
25153 @end itemize
25154
25155 @noindent
25156 For exception handling, either or both of two models are supplied:
25157 @itemize @bullet
25158 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
25159 Most programs should experience a substantial speed improvement by
25160 being compiled with a ZCX run-time.
25161 This is especially true for
25162 tasking applications or applications with many exception handlers.}
25163 @cindex Zero-Cost Exceptions
25164 @cindex ZCX (Zero-Cost Exceptions)
25165 which uses binder-generated tables that
25166 are interrogated at run time to locate a handler
25167
25168 @item @b{setjmp / longjmp} (``SJLJ''),
25169 @cindex setjmp/longjmp Exception Model
25170 @cindex SJLJ (setjmp/longjmp Exception Model)
25171 which uses dynamically-set data to establish
25172 the set of handlers
25173 @end itemize
25174
25175 @noindent
25176 This appendix summarizes which combinations of threads and exception support
25177 are supplied on various GNAT platforms.
25178 It then shows how to select a particular library either
25179 permanently or temporarily,
25180 explains the properties of (and tradeoffs among) the various threads
25181 libraries, and provides some additional
25182 information about several specific platforms.
25183
25184 @menu
25185 * Summary of Run-Time Configurations::
25186 * Specifying a Run-Time Library::
25187 * Choosing the Scheduling Policy::
25188 * Solaris-Specific Considerations::
25189 * Linux-Specific Considerations::
25190 * AIX-Specific Considerations::
25191 * Irix-Specific Considerations::
25192 * RTX-Specific Considerations::
25193 * HP-UX-Specific Considerations::
25194 @end menu
25195
25196 @node Summary of Run-Time Configurations
25197 @section Summary of Run-Time Configurations
25198
25199 @multitable @columnfractions .30 .70
25200 @item @b{alpha-openvms}
25201 @item @code{@ @ }@i{rts-native (default)}
25202 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25203 @item @code{@ @ @ @ }Exceptions @tab ZCX
25204 @*
25205 @item @b{alpha-tru64}
25206 @item @code{@ @ }@i{rts-native (default)}
25207 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25208 @item @code{@ @ @ @ }Exceptions @tab ZCX
25209 @*
25210 @item @code{@ @ }@i{rts-sjlj}
25211 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25212 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25213 @*
25214 @item @b{ia64-hp_linux}
25215 @item @code{@ @ }@i{rts-native (default)}
25216 @item @code{@ @ @ @ }Tasking    @tab pthread library
25217 @item @code{@ @ @ @ }Exceptions @tab ZCX
25218 @*
25219 @item @b{ia64-hpux}
25220 @item @code{@ @ }@i{rts-native (default)}
25221 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25222 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25223 @*
25224 @item @b{ia64-openvms}
25225 @item @code{@ @ }@i{rts-native (default)}
25226 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25227 @item @code{@ @ @ @ }Exceptions @tab ZCX
25228 @*
25229 @item @b{ia64-sgi_linux}
25230 @item @code{@ @ }@i{rts-native (default)}
25231 @item @code{@ @ @ @ }Tasking    @tab pthread library
25232 @item @code{@ @ @ @ }Exceptions @tab ZCX
25233 @*
25234 @item @b{mips-irix}
25235 @item @code{@ @ }@i{rts-native (default)}
25236 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
25237 @item @code{@ @ @ @ }Exceptions @tab ZCX
25238 @*
25239 @item @b{pa-hpux}
25240 @item @code{@ @ }@i{rts-native (default)}
25241 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25242 @item @code{@ @ @ @ }Exceptions @tab ZCX
25243 @*
25244 @item @code{@ @ }@i{rts-sjlj}
25245 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25246 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25247 @*
25248 @item @b{ppc-aix}
25249 @item @code{@ @ }@i{rts-native (default)}
25250 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
25251 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25252 @*
25253 @item @b{ppc-darwin}
25254 @item @code{@ @ }@i{rts-native (default)}
25255 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
25256 @item @code{@ @ @ @ }Exceptions @tab ZCX
25257 @*
25258 @item @b{sparc-solaris}  @tab
25259 @item @code{@ @ }@i{rts-native (default)}
25260 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25261 @item @code{@ @ @ @ }Exceptions @tab ZCX
25262 @*
25263 @item @code{@ @ }@i{rts-pthread}
25264 @item @code{@ @ @ @ }Tasking    @tab pthread library
25265 @item @code{@ @ @ @ }Exceptions @tab ZCX
25266 @*
25267 @item @code{@ @ }@i{rts-sjlj}
25268 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25269 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25270 @*
25271 @item @b{sparc64-solaris}  @tab
25272 @item @code{@ @ }@i{rts-native (default)}
25273 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25274 @item @code{@ @ @ @ }Exceptions @tab ZCX
25275 @*
25276 @item @b{x86-linux}
25277 @item @code{@ @ }@i{rts-native (default)}
25278 @item @code{@ @ @ @ }Tasking    @tab pthread library
25279 @item @code{@ @ @ @ }Exceptions @tab ZCX
25280 @*
25281 @item @code{@ @ }@i{rts-sjlj}
25282 @item @code{@ @ @ @ }Tasking    @tab pthread library
25283 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25284 @*
25285 @item @b{x86-lynx}
25286 @item @code{@ @ }@i{rts-native (default)}
25287 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
25288 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25289 @*
25290 @item @b{x86-solaris}
25291 @item @code{@ @ }@i{rts-native (default)}
25292 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
25293 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25294 @*
25295 @item @b{x86-windows}
25296 @item @code{@ @ }@i{rts-native (default)}
25297 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25298 @item @code{@ @ @ @ }Exceptions @tab ZCX
25299 @*
25300 @item @code{@ @ }@i{rts-sjlj (default)}
25301 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25302 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25303 @*
25304 @item @b{x86-windows-rtx}
25305 @item @code{@ @ }@i{rts-rtx-rtss (default)}
25306 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
25307 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25308 @*
25309 @item @code{@ @ }@i{rts-rtx-w32}
25310 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
25311 @item @code{@ @ @ @ }Exceptions @tab ZCX
25312 @*
25313 @item @b{x86_64-linux}
25314 @item @code{@ @ }@i{rts-native (default)}
25315 @item @code{@ @ @ @ }Tasking    @tab pthread library
25316 @item @code{@ @ @ @ }Exceptions @tab ZCX
25317 @*
25318 @item @code{@ @ }@i{rts-sjlj}
25319 @item @code{@ @ @ @ }Tasking    @tab pthread library
25320 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25321 @*
25322 @end multitable
25323
25324 @node Specifying a Run-Time Library
25325 @section Specifying a Run-Time Library
25326
25327 @noindent
25328 The @file{adainclude} subdirectory containing the sources of the GNAT
25329 run-time library, and the @file{adalib} subdirectory containing the
25330 @file{ALI} files and the static and/or shared GNAT library, are located
25331 in the gcc target-dependent area:
25332
25333 @smallexample
25334 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
25335 @end smallexample
25336
25337 @noindent
25338 As indicated above, on some platforms several run-time libraries are supplied.
25339 These libraries are installed in the target dependent area and
25340 contain a complete source and binary subdirectory. The detailed description
25341 below explains the differences between the different libraries in terms of
25342 their thread support.
25343
25344 The default run-time library (when GNAT is installed) is @emph{rts-native}.
25345 This default run time is selected by the means of soft links.
25346 For example on x86-linux:
25347
25348 @smallexample
25349 @group
25350  $(target-dir)
25351      |
25352      +--- adainclude----------+
25353      |                        |
25354      +--- adalib-----------+  |
25355      |                     |  |
25356      +--- rts-native       |  |
25357      |    |                |  |
25358      |    +--- adainclude <---+
25359      |    |                |
25360      |    +--- adalib <----+
25361      |
25362      +--- rts-sjlj
25363           |
25364           +--- adainclude
25365           |
25366           +--- adalib
25367 @end group
25368 @end smallexample
25369
25370 @noindent
25371 If the @i{rts-sjlj} library is to be selected on a permanent basis,
25372 these soft links can be modified with the following commands:
25373
25374 @smallexample
25375 $ cd $target
25376 $ rm -f adainclude adalib
25377 $ ln -s rts-sjlj/adainclude adainclude
25378 $ ln -s rts-sjlj/adalib adalib
25379 @end smallexample
25380
25381 @noindent
25382 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
25383 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
25384 @file{$target/ada_object_path}.
25385
25386 Selecting another run-time library temporarily can be
25387 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
25388 @cindex @option{--RTS} option
25389
25390 @node Choosing the Scheduling Policy
25391 @section Choosing the Scheduling Policy
25392
25393 @noindent
25394 When using a POSIX threads implementation, you have a choice of several
25395 scheduling policies: @code{SCHED_FIFO},
25396 @cindex @code{SCHED_FIFO} scheduling policy
25397 @code{SCHED_RR}
25398 @cindex @code{SCHED_RR} scheduling policy
25399 and @code{SCHED_OTHER}.
25400 @cindex @code{SCHED_OTHER} scheduling policy
25401 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
25402 or @code{SCHED_RR} requires special (e.g., root) privileges.
25403
25404 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
25405 @code{SCHED_FIFO},
25406 @cindex @code{SCHED_FIFO} scheduling policy
25407 you can use one of the following:
25408
25409 @itemize @bullet
25410 @item
25411 @code{pragma Time_Slice (0.0)}
25412 @cindex pragma Time_Slice
25413 @item
25414 the corresponding binder option @option{-T0}
25415 @cindex @option{-T0} option
25416 @item
25417 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
25418 @cindex pragma Task_Dispatching_Policy
25419 @end itemize
25420
25421 @noindent
25422 To specify @code{SCHED_RR},
25423 @cindex @code{SCHED_RR} scheduling policy
25424 you should use @code{pragma Time_Slice} with a
25425 value greater than @code{0.0}, or else use the corresponding @option{-T}
25426 binder option.
25427
25428 @node Solaris-Specific Considerations
25429 @section Solaris-Specific Considerations
25430 @cindex Solaris Sparc threads libraries
25431
25432 @noindent
25433 This section addresses some topics related to the various threads libraries
25434 on Sparc Solaris.
25435
25436 @menu
25437 * Solaris Threads Issues::
25438 @end menu
25439
25440 @node Solaris Threads Issues
25441 @subsection Solaris Threads Issues
25442
25443 @noindent
25444 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
25445 library based on POSIX threads --- @emph{rts-pthread}.
25446 @cindex rts-pthread threads library
25447 This run-time library has the advantage of being mostly shared across all
25448 POSIX-compliant thread implementations, and it also provides under
25449 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
25450 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
25451 and @code{PTHREAD_PRIO_PROTECT}
25452 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
25453 semantics that can be selected using the predefined pragma
25454 @code{Locking_Policy}
25455 @cindex pragma Locking_Policy (under rts-pthread)
25456 with respectively
25457 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
25458 @cindex @code{Inheritance_Locking} (under rts-pthread)
25459 @cindex @code{Ceiling_Locking} (under rts-pthread)
25460
25461 As explained above, the native run-time library is based on the Solaris thread
25462 library (@code{libthread}) and is the default library.
25463
25464 When the Solaris threads library is used (this is the default), programs
25465 compiled with GNAT can automatically take advantage of
25466 and can thus execute on multiple processors.
25467 The user can alternatively specify a processor on which the program should run
25468 to emulate a single-processor system. The multiprocessor / uniprocessor choice
25469 is made by
25470 setting the environment variable @env{GNAT_PROCESSOR}
25471 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
25472 to one of the following:
25473
25474 @table @code
25475 @item -2
25476 Use the default configuration (run the program on all
25477 available processors) - this is the same as having @code{GNAT_PROCESSOR}
25478 unset
25479
25480 @item -1
25481 Let the run-time implementation choose one processor and run the program on
25482 that processor
25483
25484 @item 0 .. Last_Proc
25485 Run the program on the specified processor.
25486 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
25487 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
25488 @end table
25489
25490 @node Linux-Specific Considerations
25491 @section Linux-Specific Considerations
25492 @cindex Linux threads libraries
25493
25494 @noindent
25495 On GNU/Linux without NPTL support (usually system with GNU C Library
25496 older than 2.3), the signal model is not POSIX compliant, which means
25497 that to send a signal to the process, you need to send the signal to all
25498 threads, e.g.@: by using @code{killpg()}.
25499
25500 @node AIX-Specific Considerations
25501 @section AIX-Specific Considerations
25502 @cindex AIX resolver library
25503
25504 @noindent
25505 On AIX, the resolver library initializes some internal structure on
25506 the first call to @code{get*by*} functions, which are used to implement
25507 @code{GNAT.Sockets.Get_Host_By_Name} and
25508 @code{GNAT.Sockets.Get_Host_By_Address}.
25509 If such initialization occurs within an Ada task, and the stack size for
25510 the task is the default size, a stack overflow may occur.
25511
25512 To avoid this overflow, the user should either ensure that the first call
25513 to @code{GNAT.Sockets.Get_Host_By_Name} or
25514 @code{GNAT.Sockets.Get_Host_By_Addrss}
25515 occurs in the environment task, or use @code{pragma Storage_Size} to
25516 specify a sufficiently large size for the stack of the task that contains
25517 this call.
25518
25519 @node Irix-Specific Considerations
25520 @section Irix-Specific Considerations
25521 @cindex Irix libraries
25522
25523 @noindent
25524 The GCC support libraries coming with the Irix compiler have moved to
25525 their canonical place with respect to the general Irix ABI related
25526 conventions. Running applications built with the default shared GNAT
25527 run-time now requires the LD_LIBRARY_PATH environment variable to
25528 include this location. A possible way to achieve this is to issue the
25529 following command line on a bash prompt:
25530
25531 @smallexample
25532 @group
25533 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
25534 @end group
25535 @end smallexample
25536
25537 @node RTX-Specific Considerations
25538 @section RTX-Specific Considerations
25539 @cindex RTX libraries
25540
25541 @noindent
25542 The Real-time Extension (RTX) to Windows is based on the Windows Win32
25543 API. Applications can be built to work in two different modes:
25544
25545 @itemize @bullet
25546 @item
25547 Windows executables that run in Ring 3 to utilize memory protection
25548 (@emph{rts-rtx-w32}).
25549
25550 @item
25551 Real-time subsystem (RTSS) executables that run in Ring 0, where
25552 performance can be optimized with RTSS applications taking precedent
25553 over all Windows applications (@emph{rts-rtx-rtss}).
25554
25555 @end itemize
25556
25557 @node HP-UX-Specific Considerations
25558 @section HP-UX-Specific Considerations
25559 @cindex HP-UX Scheduling
25560
25561 @noindent
25562 On HP-UX, appropriate privileges are required to change the scheduling
25563 parameters of a task. The calling process must have appropriate
25564 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
25565 successfully change the scheduling parameters.
25566
25567 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
25568 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
25569 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
25570
25571 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
25572 one of the following:
25573
25574 @itemize @bullet
25575 @item
25576 @code{pragma Time_Slice (0.0)}
25577 @cindex pragma Time_Slice
25578 @item
25579 the corresponding binder option @option{-T0}
25580 @cindex @option{-T0} option
25581 @item
25582 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
25583 @cindex pragma Task_Dispatching_Policy
25584 @end itemize
25585
25586 @noindent
25587 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
25588 you should use @code{pragma Time_Slice} with a
25589 value greater than @code{0.0}, or use the corresponding @option{-T}
25590 binder option, or set the @code{pragma Task_Dispatching_Policy
25591 (Round_Robin_Within_Priorities)}.
25592
25593 @c *******************************
25594 @node Example of Binder Output File
25595 @appendix Example of Binder Output File
25596
25597 @noindent
25598 This Appendix displays the source code for @command{gnatbind}'s output
25599 file generated for a simple ``Hello World'' program.
25600 Comments have been added for clarification purposes.
25601
25602 @smallexample @c adanocomment
25603 @iftex
25604 @leftskip=0cm
25605 @end iftex
25606 --  The package is called Ada_Main unless this name is actually used
25607 --  as a unit name in the partition, in which case some other unique
25608 --  name is used.
25609
25610 with System;
25611 package ada_main is
25612
25613    Elab_Final_Code : Integer;
25614    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25615
25616    --  The main program saves the parameters (argument count,
25617    --  argument values, environment pointer) in global variables
25618    --  for later access by other units including
25619    --  Ada.Command_Line.
25620
25621    gnat_argc : Integer;
25622    gnat_argv : System.Address;
25623    gnat_envp : System.Address;
25624
25625    --  The actual variables are stored in a library routine. This
25626    --  is useful for some shared library situations, where there
25627    --  are problems if variables are not in the library.
25628
25629    pragma Import (C, gnat_argc);
25630    pragma Import (C, gnat_argv);
25631    pragma Import (C, gnat_envp);
25632
25633    --  The exit status is similarly an external location
25634
25635    gnat_exit_status : Integer;
25636    pragma Import (C, gnat_exit_status);
25637
25638    GNAT_Version : constant String :=
25639                     "GNAT Version: 6.0.0w (20061115)";
25640    pragma Export (C, GNAT_Version, "__gnat_version");
25641
25642    --  This is the generated adafinal routine that performs
25643    --  finalization at the end of execution. In the case where
25644    --  Ada is the main program, this main program makes a call
25645    --  to adafinal at program termination.
25646
25647    procedure adafinal;
25648    pragma Export (C, adafinal, "adafinal");
25649
25650    --  This is the generated adainit routine that performs
25651    --  initialization at the start of execution. In the case
25652    --  where Ada is the main program, this main program makes
25653    --  a call to adainit at program startup.
25654
25655    procedure adainit;
25656    pragma Export (C, adainit, "adainit");
25657
25658    --  This routine is called at the start of execution. It is
25659    --  a dummy routine that is used by the debugger to breakpoint
25660    --  at the start of execution.
25661
25662    procedure Break_Start;
25663    pragma Import (C, Break_Start, "__gnat_break_start");
25664
25665    --  This is the actual generated main program (it would be
25666    --  suppressed if the no main program switch were used). As
25667    --  required by standard system conventions, this program has
25668    --  the external name main.
25669
25670    function main
25671      (argc : Integer;
25672       argv : System.Address;
25673       envp : System.Address)
25674       return Integer;
25675    pragma Export (C, main, "main");
25676
25677    --  The following set of constants give the version
25678    --  identification values for every unit in the bound
25679    --  partition. This identification is computed from all
25680    --  dependent semantic units, and corresponds to the
25681    --  string that would be returned by use of the
25682    --  Body_Version or Version attributes.
25683
25684    type Version_32 is mod 2 ** 32;
25685    u00001 : constant Version_32 := 16#7880BEB3#;
25686    u00002 : constant Version_32 := 16#0D24CBD0#;
25687    u00003 : constant Version_32 := 16#3283DBEB#;
25688    u00004 : constant Version_32 := 16#2359F9ED#;
25689    u00005 : constant Version_32 := 16#664FB847#;
25690    u00006 : constant Version_32 := 16#68E803DF#;
25691    u00007 : constant Version_32 := 16#5572E604#;
25692    u00008 : constant Version_32 := 16#46B173D8#;
25693    u00009 : constant Version_32 := 16#156A40CF#;
25694    u00010 : constant Version_32 := 16#033DABE0#;
25695    u00011 : constant Version_32 := 16#6AB38FEA#;
25696    u00012 : constant Version_32 := 16#22B6217D#;
25697    u00013 : constant Version_32 := 16#68A22947#;
25698    u00014 : constant Version_32 := 16#18CC4A56#;
25699    u00015 : constant Version_32 := 16#08258E1B#;
25700    u00016 : constant Version_32 := 16#367D5222#;
25701    u00017 : constant Version_32 := 16#20C9ECA4#;
25702    u00018 : constant Version_32 := 16#50D32CB6#;
25703    u00019 : constant Version_32 := 16#39A8BB77#;
25704    u00020 : constant Version_32 := 16#5CF8FA2B#;
25705    u00021 : constant Version_32 := 16#2F1EB794#;
25706    u00022 : constant Version_32 := 16#31AB6444#;
25707    u00023 : constant Version_32 := 16#1574B6E9#;
25708    u00024 : constant Version_32 := 16#5109C189#;
25709    u00025 : constant Version_32 := 16#56D770CD#;
25710    u00026 : constant Version_32 := 16#02F9DE3D#;
25711    u00027 : constant Version_32 := 16#08AB6B2C#;
25712    u00028 : constant Version_32 := 16#3FA37670#;
25713    u00029 : constant Version_32 := 16#476457A0#;
25714    u00030 : constant Version_32 := 16#731E1B6E#;
25715    u00031 : constant Version_32 := 16#23C2E789#;
25716    u00032 : constant Version_32 := 16#0F1BD6A1#;
25717    u00033 : constant Version_32 := 16#7C25DE96#;
25718    u00034 : constant Version_32 := 16#39ADFFA2#;
25719    u00035 : constant Version_32 := 16#571DE3E7#;
25720    u00036 : constant Version_32 := 16#5EB646AB#;
25721    u00037 : constant Version_32 := 16#4249379B#;
25722    u00038 : constant Version_32 := 16#0357E00A#;
25723    u00039 : constant Version_32 := 16#3784FB72#;
25724    u00040 : constant Version_32 := 16#2E723019#;
25725    u00041 : constant Version_32 := 16#623358EA#;
25726    u00042 : constant Version_32 := 16#107F9465#;
25727    u00043 : constant Version_32 := 16#6843F68A#;
25728    u00044 : constant Version_32 := 16#63305874#;
25729    u00045 : constant Version_32 := 16#31E56CE1#;
25730    u00046 : constant Version_32 := 16#02917970#;
25731    u00047 : constant Version_32 := 16#6CCBA70E#;
25732    u00048 : constant Version_32 := 16#41CD4204#;
25733    u00049 : constant Version_32 := 16#572E3F58#;
25734    u00050 : constant Version_32 := 16#20729FF5#;
25735    u00051 : constant Version_32 := 16#1D4F93E8#;
25736    u00052 : constant Version_32 := 16#30B2EC3D#;
25737    u00053 : constant Version_32 := 16#34054F96#;
25738    u00054 : constant Version_32 := 16#5A199860#;
25739    u00055 : constant Version_32 := 16#0E7F912B#;
25740    u00056 : constant Version_32 := 16#5760634A#;
25741    u00057 : constant Version_32 := 16#5D851835#;
25742
25743    --  The following Export pragmas export the version numbers
25744    --  with symbolic names ending in B (for body) or S
25745    --  (for spec) so that they can be located in a link. The
25746    --  information provided here is sufficient to track down
25747    --  the exact versions of units used in a given build.
25748
25749    pragma Export (C, u00001, "helloB");
25750    pragma Export (C, u00002, "system__standard_libraryB");
25751    pragma Export (C, u00003, "system__standard_libraryS");
25752    pragma Export (C, u00004, "adaS");
25753    pragma Export (C, u00005, "ada__text_ioB");
25754    pragma Export (C, u00006, "ada__text_ioS");
25755    pragma Export (C, u00007, "ada__exceptionsB");
25756    pragma Export (C, u00008, "ada__exceptionsS");
25757    pragma Export (C, u00009, "gnatS");
25758    pragma Export (C, u00010, "gnat__heap_sort_aB");
25759    pragma Export (C, u00011, "gnat__heap_sort_aS");
25760    pragma Export (C, u00012, "systemS");
25761    pragma Export (C, u00013, "system__exception_tableB");
25762    pragma Export (C, u00014, "system__exception_tableS");
25763    pragma Export (C, u00015, "gnat__htableB");
25764    pragma Export (C, u00016, "gnat__htableS");
25765    pragma Export (C, u00017, "system__exceptionsS");
25766    pragma Export (C, u00018, "system__machine_state_operationsB");
25767    pragma Export (C, u00019, "system__machine_state_operationsS");
25768    pragma Export (C, u00020, "system__machine_codeS");
25769    pragma Export (C, u00021, "system__storage_elementsB");
25770    pragma Export (C, u00022, "system__storage_elementsS");
25771    pragma Export (C, u00023, "system__secondary_stackB");
25772    pragma Export (C, u00024, "system__secondary_stackS");
25773    pragma Export (C, u00025, "system__parametersB");
25774    pragma Export (C, u00026, "system__parametersS");
25775    pragma Export (C, u00027, "system__soft_linksB");
25776    pragma Export (C, u00028, "system__soft_linksS");
25777    pragma Export (C, u00029, "system__stack_checkingB");
25778    pragma Export (C, u00030, "system__stack_checkingS");
25779    pragma Export (C, u00031, "system__tracebackB");
25780    pragma Export (C, u00032, "system__tracebackS");
25781    pragma Export (C, u00033, "ada__streamsS");
25782    pragma Export (C, u00034, "ada__tagsB");
25783    pragma Export (C, u00035, "ada__tagsS");
25784    pragma Export (C, u00036, "system__string_opsB");
25785    pragma Export (C, u00037, "system__string_opsS");
25786    pragma Export (C, u00038, "interfacesS");
25787    pragma Export (C, u00039, "interfaces__c_streamsB");
25788    pragma Export (C, u00040, "interfaces__c_streamsS");
25789    pragma Export (C, u00041, "system__file_ioB");
25790    pragma Export (C, u00042, "system__file_ioS");
25791    pragma Export (C, u00043, "ada__finalizationB");
25792    pragma Export (C, u00044, "ada__finalizationS");
25793    pragma Export (C, u00045, "system__finalization_rootB");
25794    pragma Export (C, u00046, "system__finalization_rootS");
25795    pragma Export (C, u00047, "system__finalization_implementationB");
25796    pragma Export (C, u00048, "system__finalization_implementationS");
25797    pragma Export (C, u00049, "system__string_ops_concat_3B");
25798    pragma Export (C, u00050, "system__string_ops_concat_3S");
25799    pragma Export (C, u00051, "system__stream_attributesB");
25800    pragma Export (C, u00052, "system__stream_attributesS");
25801    pragma Export (C, u00053, "ada__io_exceptionsS");
25802    pragma Export (C, u00054, "system__unsigned_typesS");
25803    pragma Export (C, u00055, "system__file_control_blockS");
25804    pragma Export (C, u00056, "ada__finalization__list_controllerB");
25805    pragma Export (C, u00057, "ada__finalization__list_controllerS");
25806
25807    -- BEGIN ELABORATION ORDER
25808    -- ada (spec)
25809    -- gnat (spec)
25810    -- gnat.heap_sort_a (spec)
25811    -- gnat.heap_sort_a (body)
25812    -- gnat.htable (spec)
25813    -- gnat.htable (body)
25814    -- interfaces (spec)
25815    -- system (spec)
25816    -- system.machine_code (spec)
25817    -- system.parameters (spec)
25818    -- system.parameters (body)
25819    -- interfaces.c_streams (spec)
25820    -- interfaces.c_streams (body)
25821    -- system.standard_library (spec)
25822    -- ada.exceptions (spec)
25823    -- system.exception_table (spec)
25824    -- system.exception_table (body)
25825    -- ada.io_exceptions (spec)
25826    -- system.exceptions (spec)
25827    -- system.storage_elements (spec)
25828    -- system.storage_elements (body)
25829    -- system.machine_state_operations (spec)
25830    -- system.machine_state_operations (body)
25831    -- system.secondary_stack (spec)
25832    -- system.stack_checking (spec)
25833    -- system.soft_links (spec)
25834    -- system.soft_links (body)
25835    -- system.stack_checking (body)
25836    -- system.secondary_stack (body)
25837    -- system.standard_library (body)
25838    -- system.string_ops (spec)
25839    -- system.string_ops (body)
25840    -- ada.tags (spec)
25841    -- ada.tags (body)
25842    -- ada.streams (spec)
25843    -- system.finalization_root (spec)
25844    -- system.finalization_root (body)
25845    -- system.string_ops_concat_3 (spec)
25846    -- system.string_ops_concat_3 (body)
25847    -- system.traceback (spec)
25848    -- system.traceback (body)
25849    -- ada.exceptions (body)
25850    -- system.unsigned_types (spec)
25851    -- system.stream_attributes (spec)
25852    -- system.stream_attributes (body)
25853    -- system.finalization_implementation (spec)
25854    -- system.finalization_implementation (body)
25855    -- ada.finalization (spec)
25856    -- ada.finalization (body)
25857    -- ada.finalization.list_controller (spec)
25858    -- ada.finalization.list_controller (body)
25859    -- system.file_control_block (spec)
25860    -- system.file_io (spec)
25861    -- system.file_io (body)
25862    -- ada.text_io (spec)
25863    -- ada.text_io (body)
25864    -- hello (body)
25865    -- END ELABORATION ORDER
25866
25867 end ada_main;
25868
25869 --  The following source file name pragmas allow the generated file
25870 --  names to be unique for different main programs. They are needed
25871 --  since the package name will always be Ada_Main.
25872
25873 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25874 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25875
25876 --  Generated package body for Ada_Main starts here
25877
25878 package body ada_main is
25879
25880    --  The actual finalization is performed by calling the
25881    --  library routine in System.Standard_Library.Adafinal
25882
25883    procedure Do_Finalize;
25884    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
25885
25886    -------------
25887    -- adainit --
25888    -------------
25889
25890 @findex adainit
25891    procedure adainit is
25892
25893       --  These booleans are set to True once the associated unit has
25894       --  been elaborated. It is also used to avoid elaborating the
25895       --  same unit twice.
25896
25897       E040 : Boolean;
25898       pragma Import (Ada, E040, "interfaces__c_streams_E");
25899
25900       E008 : Boolean;
25901       pragma Import (Ada, E008, "ada__exceptions_E");
25902
25903       E014 : Boolean;
25904       pragma Import (Ada, E014, "system__exception_table_E");
25905
25906       E053 : Boolean;
25907       pragma Import (Ada, E053, "ada__io_exceptions_E");
25908
25909       E017 : Boolean;
25910       pragma Import (Ada, E017, "system__exceptions_E");
25911
25912       E024 : Boolean;
25913       pragma Import (Ada, E024, "system__secondary_stack_E");
25914
25915       E030 : Boolean;
25916       pragma Import (Ada, E030, "system__stack_checking_E");
25917
25918       E028 : Boolean;
25919       pragma Import (Ada, E028, "system__soft_links_E");
25920
25921       E035 : Boolean;
25922       pragma Import (Ada, E035, "ada__tags_E");
25923
25924       E033 : Boolean;
25925       pragma Import (Ada, E033, "ada__streams_E");
25926
25927       E046 : Boolean;
25928       pragma Import (Ada, E046, "system__finalization_root_E");
25929
25930       E048 : Boolean;
25931       pragma Import (Ada, E048, "system__finalization_implementation_E");
25932
25933       E044 : Boolean;
25934       pragma Import (Ada, E044, "ada__finalization_E");
25935
25936       E057 : Boolean;
25937       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
25938
25939       E055 : Boolean;
25940       pragma Import (Ada, E055, "system__file_control_block_E");
25941
25942       E042 : Boolean;
25943       pragma Import (Ada, E042, "system__file_io_E");
25944
25945       E006 : Boolean;
25946       pragma Import (Ada, E006, "ada__text_io_E");
25947
25948       --  Set_Globals is a library routine that stores away the
25949       --  value of the indicated set of global values in global
25950       --  variables within the library.
25951
25952       procedure Set_Globals
25953         (Main_Priority            : Integer;
25954          Time_Slice_Value         : Integer;
25955          WC_Encoding              : Character;
25956          Locking_Policy           : Character;
25957          Queuing_Policy           : Character;
25958          Task_Dispatching_Policy  : Character;
25959          Adafinal                 : System.Address;
25960          Unreserve_All_Interrupts : Integer;
25961          Exception_Tracebacks     : Integer);
25962 @findex __gnat_set_globals
25963       pragma Import (C, Set_Globals, "__gnat_set_globals");
25964
25965       --  SDP_Table_Build is a library routine used to build the
25966       --  exception tables. See unit Ada.Exceptions in files
25967       --  a-except.ads/adb for full details of how zero cost
25968       --  exception handling works. This procedure, the call to
25969       --  it, and the two following tables are all omitted if the
25970       --  build is in longjmp/setjmp exception mode.
25971
25972 @findex SDP_Table_Build
25973 @findex Zero Cost Exceptions
25974       procedure SDP_Table_Build
25975         (SDP_Addresses   : System.Address;
25976          SDP_Count       : Natural;
25977          Elab_Addresses  : System.Address;
25978          Elab_Addr_Count : Natural);
25979       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
25980
25981       --  Table of Unit_Exception_Table addresses. Used for zero
25982       --  cost exception handling to build the top level table.
25983
25984       ST : aliased constant array (1 .. 23) of System.Address := (
25985         Hello'UET_Address,
25986         Ada.Text_Io'UET_Address,
25987         Ada.Exceptions'UET_Address,
25988         Gnat.Heap_Sort_A'UET_Address,
25989         System.Exception_Table'UET_Address,
25990         System.Machine_State_Operations'UET_Address,
25991         System.Secondary_Stack'UET_Address,
25992         System.Parameters'UET_Address,
25993         System.Soft_Links'UET_Address,
25994         System.Stack_Checking'UET_Address,
25995         System.Traceback'UET_Address,
25996         Ada.Streams'UET_Address,
25997         Ada.Tags'UET_Address,
25998         System.String_Ops'UET_Address,
25999         Interfaces.C_Streams'UET_Address,
26000         System.File_Io'UET_Address,
26001         Ada.Finalization'UET_Address,
26002         System.Finalization_Root'UET_Address,
26003         System.Finalization_Implementation'UET_Address,
26004         System.String_Ops_Concat_3'UET_Address,
26005         System.Stream_Attributes'UET_Address,
26006         System.File_Control_Block'UET_Address,
26007         Ada.Finalization.List_Controller'UET_Address);
26008
26009       --  Table of addresses of elaboration routines. Used for
26010       --  zero cost exception handling to make sure these
26011       --  addresses are included in the top level procedure
26012       --  address table.
26013
26014       EA : aliased constant array (1 .. 23) of System.Address := (
26015         adainit'Code_Address,
26016         Do_Finalize'Code_Address,
26017         Ada.Exceptions'Elab_Spec'Address,
26018         System.Exceptions'Elab_Spec'Address,
26019         Interfaces.C_Streams'Elab_Spec'Address,
26020         System.Exception_Table'Elab_Body'Address,
26021         Ada.Io_Exceptions'Elab_Spec'Address,
26022         System.Stack_Checking'Elab_Spec'Address,
26023         System.Soft_Links'Elab_Body'Address,
26024         System.Secondary_Stack'Elab_Body'Address,
26025         Ada.Tags'Elab_Spec'Address,
26026         Ada.Tags'Elab_Body'Address,
26027         Ada.Streams'Elab_Spec'Address,
26028         System.Finalization_Root'Elab_Spec'Address,
26029         Ada.Exceptions'Elab_Body'Address,
26030         System.Finalization_Implementation'Elab_Spec'Address,
26031         System.Finalization_Implementation'Elab_Body'Address,
26032         Ada.Finalization'Elab_Spec'Address,
26033         Ada.Finalization.List_Controller'Elab_Spec'Address,
26034         System.File_Control_Block'Elab_Spec'Address,
26035         System.File_Io'Elab_Body'Address,
26036         Ada.Text_Io'Elab_Spec'Address,
26037         Ada.Text_Io'Elab_Body'Address);
26038
26039    --  Start of processing for adainit
26040
26041    begin
26042
26043       --  Call SDP_Table_Build to build the top level procedure
26044       --  table for zero cost exception handling (omitted in
26045       --  longjmp/setjmp mode).
26046
26047       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26048
26049       --  Call Set_Globals to record various information for
26050       --  this partition.  The values are derived by the binder
26051       --  from information stored in the ali files by the compiler.
26052
26053 @findex __gnat_set_globals
26054       Set_Globals
26055         (Main_Priority            => -1,
26056          --  Priority of main program, -1 if no pragma Priority used
26057
26058          Time_Slice_Value         => -1,
26059          --  Time slice from Time_Slice pragma, -1 if none used
26060
26061          WC_Encoding              => 'b',
26062          --  Wide_Character encoding used, default is brackets
26063
26064          Locking_Policy           => ' ',
26065          --  Locking_Policy used, default of space means not
26066          --  specified, otherwise it is the first character of
26067          --  the policy name.
26068
26069          Queuing_Policy           => ' ',
26070          --  Queuing_Policy used, default of space means not
26071          --  specified, otherwise it is the first character of
26072          --  the policy name.
26073
26074          Task_Dispatching_Policy  => ' ',
26075          --  Task_Dispatching_Policy used, default of space means
26076          --  not specified, otherwise first character of the
26077          --  policy name.
26078
26079          Adafinal                 => System.Null_Address,
26080          --  Address of Adafinal routine, not used anymore
26081
26082          Unreserve_All_Interrupts => 0,
26083          --  Set true if pragma Unreserve_All_Interrupts was used
26084
26085          Exception_Tracebacks     => 0);
26086          --  Indicates if exception tracebacks are enabled
26087
26088       Elab_Final_Code := 1;
26089
26090       --  Now we have the elaboration calls for all units in the partition.
26091       --  The Elab_Spec and Elab_Body attributes generate references to the
26092       --  implicit elaboration procedures generated by the compiler for
26093       --  each unit that requires elaboration.
26094
26095       if not E040 then
26096          Interfaces.C_Streams'Elab_Spec;
26097       end if;
26098       E040 := True;
26099       if not E008 then
26100          Ada.Exceptions'Elab_Spec;
26101       end if;
26102       if not E014 then
26103          System.Exception_Table'Elab_Body;
26104          E014 := True;
26105       end if;
26106       if not E053 then
26107          Ada.Io_Exceptions'Elab_Spec;
26108          E053 := True;
26109       end if;
26110       if not E017 then
26111          System.Exceptions'Elab_Spec;
26112          E017 := True;
26113       end if;
26114       if not E030 then
26115          System.Stack_Checking'Elab_Spec;
26116       end if;
26117       if not E028 then
26118          System.Soft_Links'Elab_Body;
26119          E028 := True;
26120       end if;
26121       E030 := True;
26122       if not E024 then
26123          System.Secondary_Stack'Elab_Body;
26124          E024 := True;
26125       end if;
26126       if not E035 then
26127          Ada.Tags'Elab_Spec;
26128       end if;
26129       if not E035 then
26130          Ada.Tags'Elab_Body;
26131          E035 := True;
26132       end if;
26133       if not E033 then
26134          Ada.Streams'Elab_Spec;
26135          E033 := True;
26136       end if;
26137       if not E046 then
26138          System.Finalization_Root'Elab_Spec;
26139       end if;
26140       E046 := True;
26141       if not E008 then
26142          Ada.Exceptions'Elab_Body;
26143          E008 := True;
26144       end if;
26145       if not E048 then
26146          System.Finalization_Implementation'Elab_Spec;
26147       end if;
26148       if not E048 then
26149          System.Finalization_Implementation'Elab_Body;
26150          E048 := True;
26151       end if;
26152       if not E044 then
26153          Ada.Finalization'Elab_Spec;
26154       end if;
26155       E044 := True;
26156       if not E057 then
26157          Ada.Finalization.List_Controller'Elab_Spec;
26158       end if;
26159       E057 := True;
26160       if not E055 then
26161          System.File_Control_Block'Elab_Spec;
26162          E055 := True;
26163       end if;
26164       if not E042 then
26165          System.File_Io'Elab_Body;
26166          E042 := True;
26167       end if;
26168       if not E006 then
26169          Ada.Text_Io'Elab_Spec;
26170       end if;
26171       if not E006 then
26172          Ada.Text_Io'Elab_Body;
26173          E006 := True;
26174       end if;
26175
26176       Elab_Final_Code := 0;
26177    end adainit;
26178
26179    --------------
26180    -- adafinal --
26181    --------------
26182
26183 @findex adafinal
26184    procedure adafinal is
26185    begin
26186       Do_Finalize;
26187    end adafinal;
26188
26189    ----------
26190    -- main --
26191    ----------
26192
26193    --  main is actually a function, as in the ANSI C standard,
26194    --  defined to return the exit status. The three parameters
26195    --  are the argument count, argument values and environment
26196    --  pointer.
26197
26198 @findex Main Program
26199    function main
26200      (argc : Integer;
26201       argv : System.Address;
26202       envp : System.Address)
26203       return Integer
26204    is
26205       --  The initialize routine performs low level system
26206       --  initialization using a standard library routine which
26207       --  sets up signal handling and performs any other
26208       --  required setup. The routine can be found in file
26209       --  a-init.c.
26210
26211 @findex __gnat_initialize
26212       procedure initialize;
26213       pragma Import (C, initialize, "__gnat_initialize");
26214
26215       --  The finalize routine performs low level system
26216       --  finalization using a standard library routine. The
26217       --  routine is found in file a-final.c and in the standard
26218       --  distribution is a dummy routine that does nothing, so
26219       --  really this is a hook for special user finalization.
26220
26221 @findex __gnat_finalize
26222       procedure finalize;
26223       pragma Import (C, finalize, "__gnat_finalize");
26224
26225       --  We get to the main program of the partition by using
26226       --  pragma Import because if we try to with the unit and
26227       --  call it Ada style, then not only do we waste time
26228       --  recompiling it, but also, we don't really know the right
26229       --  switches (e.g.@: identifier character set) to be used
26230       --  to compile it.
26231
26232       procedure Ada_Main_Program;
26233       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26234
26235    --  Start of processing for main
26236
26237    begin
26238       --  Save global variables
26239
26240       gnat_argc := argc;
26241       gnat_argv := argv;
26242       gnat_envp := envp;
26243
26244       --  Call low level system initialization
26245
26246       Initialize;
26247
26248       --  Call our generated Ada initialization routine
26249
26250       adainit;
26251
26252       --  This is the point at which we want the debugger to get
26253       --  control
26254
26255       Break_Start;
26256
26257       --  Now we call the main program of the partition
26258
26259       Ada_Main_Program;
26260
26261       --  Perform Ada finalization
26262
26263       adafinal;
26264
26265       --  Perform low level system finalization
26266
26267       Finalize;
26268
26269       --  Return the proper exit status
26270       return (gnat_exit_status);
26271    end;
26272
26273 --  This section is entirely comments, so it has no effect on the
26274 --  compilation of the Ada_Main package. It provides the list of
26275 --  object files and linker options, as well as some standard
26276 --  libraries needed for the link. The gnatlink utility parses
26277 --  this b~hello.adb file to read these comment lines to generate
26278 --  the appropriate command line arguments for the call to the
26279 --  system linker. The BEGIN/END lines are used for sentinels for
26280 --  this parsing operation.
26281
26282 --  The exact file names will of course depend on the environment,
26283 --  host/target and location of files on the host system.
26284
26285 @findex Object file list
26286 -- BEGIN Object file/option list
26287    --   ./hello.o
26288    --   -L./
26289    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26290    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26291 -- END Object file/option list
26292
26293 end ada_main;
26294 @end smallexample
26295
26296 @noindent
26297 The Ada code in the above example is exactly what is generated by the
26298 binder. We have added comments to more clearly indicate the function
26299 of each part of the generated @code{Ada_Main} package.
26300
26301 The code is standard Ada in all respects, and can be processed by any
26302 tools that handle Ada. In particular, it is possible to use the debugger
26303 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26304 suppose that for reasons that you do not understand, your program is crashing
26305 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26306 you can place a breakpoint on the call:
26307
26308 @smallexample @c ada
26309 Ada.Text_Io'Elab_Body;
26310 @end smallexample
26311
26312 @noindent
26313 and trace the elaboration routine for this package to find out where
26314 the problem might be (more usually of course you would be debugging
26315 elaboration code in your own application).
26316
26317 @node Elaboration Order Handling in GNAT
26318 @appendix Elaboration Order Handling in GNAT
26319 @cindex Order of elaboration
26320 @cindex Elaboration control
26321
26322 @menu
26323 * Elaboration Code::
26324 * Checking the Elaboration Order::
26325 * Controlling the Elaboration Order::
26326 * Controlling Elaboration in GNAT - Internal Calls::
26327 * Controlling Elaboration in GNAT - External Calls::
26328 * Default Behavior in GNAT - Ensuring Safety::
26329 * Treatment of Pragma Elaborate::
26330 * Elaboration Issues for Library Tasks::
26331 * Mixing Elaboration Models::
26332 * What to Do If the Default Elaboration Behavior Fails::
26333 * Elaboration for Access-to-Subprogram Values::
26334 * Summary of Procedures for Elaboration Control::
26335 * Other Elaboration Order Considerations::
26336 @end menu
26337
26338 @noindent
26339 This chapter describes the handling of elaboration code in Ada and
26340 in GNAT, and discusses how the order of elaboration of program units can
26341 be controlled in GNAT, either automatically or with explicit programming
26342 features.
26343
26344 @node Elaboration Code
26345 @section Elaboration Code
26346
26347 @noindent
26348 Ada provides rather general mechanisms for executing code at elaboration
26349 time, that is to say before the main program starts executing. Such code arises
26350 in three contexts:
26351
26352 @table @asis
26353 @item Initializers for variables.
26354 Variables declared at the library level, in package specs or bodies, can
26355 require initialization that is performed at elaboration time, as in:
26356 @smallexample @c ada
26357 @cartouche
26358 Sqrt_Half : Float := Sqrt (0.5);
26359 @end cartouche
26360 @end smallexample
26361
26362 @item Package initialization code
26363 Code in a @code{BEGIN-END} section at the outer level of a package body is
26364 executed as part of the package body elaboration code.
26365
26366 @item Library level task allocators
26367 Tasks that are declared using task allocators at the library level
26368 start executing immediately and hence can execute at elaboration time.
26369 @end table
26370
26371 @noindent
26372 Subprogram calls are possible in any of these contexts, which means that
26373 any arbitrary part of the program may be executed as part of the elaboration
26374 code. It is even possible to write a program which does all its work at
26375 elaboration time, with a null main program, although stylistically this
26376 would usually be considered an inappropriate way to structure
26377 a program.
26378
26379 An important concern arises in the context of elaboration code:
26380 we have to be sure that it is executed in an appropriate order. What we
26381 have is a series of elaboration code sections, potentially one section
26382 for each unit in the program. It is important that these execute
26383 in the correct order. Correctness here means that, taking the above
26384 example of the declaration of @code{Sqrt_Half},
26385 if some other piece of
26386 elaboration code references @code{Sqrt_Half},
26387 then it must run after the
26388 section of elaboration code that contains the declaration of
26389 @code{Sqrt_Half}.
26390
26391 There would never be any order of elaboration problem if we made a rule
26392 that whenever you @code{with} a unit, you must elaborate both the spec and body
26393 of that unit before elaborating the unit doing the @code{with}'ing:
26394
26395 @smallexample @c ada
26396 @group
26397 @cartouche
26398 with Unit_1;
26399 package Unit_2 is @dots{}
26400 @end cartouche
26401 @end group
26402 @end smallexample
26403
26404 @noindent
26405 would require that both the body and spec of @code{Unit_1} be elaborated
26406 before the spec of @code{Unit_2}. However, a rule like that would be far too
26407 restrictive. In particular, it would make it impossible to have routines
26408 in separate packages that were mutually recursive.
26409
26410 You might think that a clever enough compiler could look at the actual
26411 elaboration code and determine an appropriate correct order of elaboration,
26412 but in the general case, this is not possible. Consider the following
26413 example.
26414
26415 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
26416 that references
26417 the variable @code{Sqrt_1}, which is declared in the elaboration code
26418 of the body of @code{Unit_1}:
26419
26420 @smallexample @c ada
26421 @cartouche
26422 Sqrt_1 : Float := Sqrt (0.1);
26423 @end cartouche
26424 @end smallexample
26425
26426 @noindent
26427 The elaboration code of the body of @code{Unit_1} also contains:
26428
26429 @smallexample @c ada
26430 @group
26431 @cartouche
26432 if expression_1 = 1 then
26433    Q := Unit_2.Func_2;
26434 end if;
26435 @end cartouche
26436 @end group
26437 @end smallexample
26438
26439 @noindent
26440 @code{Unit_2} is exactly parallel,
26441 it has a procedure @code{Func_2} that references
26442 the variable @code{Sqrt_2}, which is declared in the elaboration code of
26443 the body @code{Unit_2}:
26444
26445 @smallexample @c ada
26446 @cartouche
26447 Sqrt_2 : Float := Sqrt (0.1);
26448 @end cartouche
26449 @end smallexample
26450
26451 @noindent
26452 The elaboration code of the body of @code{Unit_2} also contains:
26453
26454 @smallexample @c ada
26455 @group
26456 @cartouche
26457 if expression_2 = 2 then
26458    Q := Unit_1.Func_1;
26459 end if;
26460 @end cartouche
26461 @end group
26462 @end smallexample
26463
26464 @noindent
26465 Now the question is, which of the following orders of elaboration is
26466 acceptable:
26467
26468 @smallexample
26469 @group
26470 Spec of Unit_1
26471 Spec of Unit_2
26472 Body of Unit_1
26473 Body of Unit_2
26474 @end group
26475 @end smallexample
26476
26477 @noindent
26478 or
26479
26480 @smallexample
26481 @group
26482 Spec of Unit_2
26483 Spec of Unit_1
26484 Body of Unit_2
26485 Body of Unit_1
26486 @end group
26487 @end smallexample
26488
26489 @noindent
26490 If you carefully analyze the flow here, you will see that you cannot tell
26491 at compile time the answer to this question.
26492 If @code{expression_1} is not equal to 1,
26493 and @code{expression_2} is not equal to 2,
26494 then either order is acceptable, because neither of the function calls is
26495 executed. If both tests evaluate to true, then neither order is acceptable
26496 and in fact there is no correct order.
26497
26498 If one of the two expressions is true, and the other is false, then one
26499 of the above orders is correct, and the other is incorrect. For example,
26500 if @code{expression_1} /= 1 and @code{expression_2} = 2,
26501 then the call to @code{Func_1}
26502 will occur, but not the call to @code{Func_2.}
26503 This means that it is essential
26504 to elaborate the body of @code{Unit_1} before
26505 the body of @code{Unit_2}, so the first
26506 order of elaboration is correct and the second is wrong.
26507
26508 By making @code{expression_1} and @code{expression_2}
26509 depend on input data, or perhaps
26510 the time of day, we can make it impossible for the compiler or binder
26511 to figure out which of these expressions will be true, and hence it
26512 is impossible to guarantee a safe order of elaboration at run time.
26513
26514 @node Checking the Elaboration Order
26515 @section Checking the Elaboration Order
26516
26517 @noindent
26518 In some languages that involve the same kind of elaboration problems,
26519 e.g.@: Java and C++, the programmer is expected to worry about these
26520 ordering problems himself, and it is common to
26521 write a program in which an incorrect elaboration order  gives
26522 surprising results, because it references variables before they
26523 are initialized.
26524 Ada is designed to be a safe language, and a programmer-beware approach is
26525 clearly not sufficient. Consequently, the language provides three lines
26526 of defense:
26527
26528 @table @asis
26529 @item Standard rules
26530 Some standard rules restrict the possible choice of elaboration
26531 order. In particular, if you @code{with} a unit, then its spec is always
26532 elaborated before the unit doing the @code{with}. Similarly, a parent
26533 spec is always elaborated before the child spec, and finally
26534 a spec is always elaborated before its corresponding body.
26535
26536 @item Dynamic elaboration checks
26537 @cindex Elaboration checks
26538 @cindex Checks, elaboration
26539 Dynamic checks are made at run time, so that if some entity is accessed
26540 before it is elaborated (typically  by means of a subprogram call)
26541 then the exception (@code{Program_Error}) is raised.
26542
26543 @item Elaboration control
26544 Facilities are provided for the programmer to specify the desired order
26545 of elaboration.
26546 @end table
26547
26548 Let's look at these facilities in more detail. First, the rules for
26549 dynamic checking. One possible rule would be simply to say that the
26550 exception is raised if you access a variable which has not yet been
26551 elaborated. The trouble with this approach is that it could require
26552 expensive checks on every variable reference. Instead Ada has two
26553 rules which are a little more restrictive, but easier to check, and
26554 easier to state:
26555
26556 @table @asis
26557 @item Restrictions on calls
26558 A subprogram can only be called at elaboration time if its body
26559 has been elaborated. The rules for elaboration given above guarantee
26560 that the spec of the subprogram has been elaborated before the
26561 call, but not the body. If this rule is violated, then the
26562 exception @code{Program_Error} is raised.
26563
26564 @item Restrictions on instantiations
26565 A generic unit can only be instantiated if the body of the generic
26566 unit has been elaborated. Again, the rules for elaboration given above
26567 guarantee that the spec of the generic unit has been elaborated
26568 before the instantiation, but not the body. If this rule is
26569 violated, then the exception @code{Program_Error} is raised.
26570 @end table
26571
26572 @noindent
26573 The idea is that if the body has been elaborated, then any variables
26574 it references must have been elaborated; by checking for the body being
26575 elaborated we guarantee that none of its references causes any
26576 trouble. As we noted above, this is a little too restrictive, because a
26577 subprogram that has no non-local references in its body may in fact be safe
26578 to call. However, it really would be unsafe to rely on this, because
26579 it would mean that the caller was aware of details of the implementation
26580 in the body. This goes against the basic tenets of Ada.
26581
26582 A plausible implementation can be described as follows.
26583 A Boolean variable is associated with each subprogram
26584 and each generic unit. This variable is initialized to False, and is set to
26585 True at the point body is elaborated. Every call or instantiation checks the
26586 variable, and raises @code{Program_Error} if the variable is False.
26587
26588 Note that one might think that it would be good enough to have one Boolean
26589 variable for each package, but that would not deal with cases of trying
26590 to call a body in the same package as the call
26591 that has not been elaborated yet.
26592 Of course a compiler may be able to do enough analysis to optimize away
26593 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26594 does such optimizations, but still the easiest conceptual model is to
26595 think of there being one variable per subprogram.
26596
26597 @node Controlling the Elaboration Order
26598 @section Controlling the Elaboration Order
26599
26600 @noindent
26601 In the previous section we discussed the rules in Ada which ensure
26602 that @code{Program_Error} is raised if an incorrect elaboration order is
26603 chosen. This prevents erroneous executions, but we need mechanisms to
26604 specify a correct execution and avoid the exception altogether.
26605 To achieve this, Ada provides a number of features for controlling
26606 the order of elaboration. We discuss these features in this section.
26607
26608 First, there are several ways of indicating to the compiler that a given
26609 unit has no elaboration problems:
26610
26611 @table @asis
26612 @item packages that do not require a body
26613 A library package that does not require a body does not permit
26614 a body (this rule was introduced in Ada 95).
26615 Thus if we have a such a package, as in:
26616
26617 @smallexample @c ada
26618 @group
26619 @cartouche
26620 package Definitions is
26621    generic
26622       type m is new integer;
26623    package Subp is
26624       type a is array (1 .. 10) of m;
26625       type b is array (1 .. 20) of m;
26626    end Subp;
26627 end Definitions;
26628 @end cartouche
26629 @end group
26630 @end smallexample
26631
26632 @noindent
26633 A package that @code{with}'s @code{Definitions} may safely instantiate
26634 @code{Definitions.Subp} because the compiler can determine that there
26635 definitely is no package body to worry about in this case
26636
26637 @item pragma Pure
26638 @cindex pragma Pure
26639 @findex Pure
26640 Places sufficient restrictions on a unit to guarantee that
26641 no call to any subprogram in the unit can result in an
26642 elaboration problem. This means that the compiler does not need
26643 to worry about the point of elaboration of such units, and in
26644 particular, does not need to check any calls to any subprograms
26645 in this unit.
26646
26647 @item pragma Preelaborate
26648 @findex Preelaborate
26649 @cindex pragma Preelaborate
26650 This pragma places slightly less stringent restrictions on a unit than
26651 does pragma Pure,
26652 but these restrictions are still sufficient to ensure that there
26653 are no elaboration problems with any calls to the unit.
26654
26655 @item pragma Elaborate_Body
26656 @findex Elaborate_Body
26657 @cindex pragma Elaborate_Body
26658 This pragma requires that the body of a unit be elaborated immediately
26659 after its spec. Suppose a unit @code{A} has such a pragma,
26660 and unit @code{B} does
26661 a @code{with} of unit @code{A}. Recall that the standard rules require
26662 the spec of unit @code{A}
26663 to be elaborated before the @code{with}'ing unit; given the pragma in
26664 @code{A}, we also know that the body of @code{A}
26665 will be elaborated before @code{B}, so
26666 that calls to @code{A} are safe and do not need a check.
26667 @end table
26668
26669 @noindent
26670 Note that,
26671 unlike pragma @code{Pure} and pragma @code{Preelaborate},
26672 the use of
26673 @code{Elaborate_Body} does not guarantee that the program is
26674 free of elaboration problems, because it may not be possible
26675 to satisfy the requested elaboration order.
26676 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
26677 If a programmer
26678 marks @code{Unit_1} as @code{Elaborate_Body},
26679 and not @code{Unit_2,} then the order of
26680 elaboration will be:
26681
26682 @smallexample
26683 @group
26684 Spec of Unit_2
26685 Spec of Unit_1
26686 Body of Unit_1
26687 Body of Unit_2
26688 @end group
26689 @end smallexample
26690
26691 @noindent
26692 Now that means that the call to @code{Func_1} in @code{Unit_2}
26693 need not be checked,
26694 it must be safe. But the call to @code{Func_2} in
26695 @code{Unit_1} may still fail if
26696 @code{Expression_1} is equal to 1,
26697 and the programmer must still take
26698 responsibility for this not being the case.
26699
26700 If all units carry a pragma @code{Elaborate_Body}, then all problems are
26701 eliminated, except for calls entirely within a body, which are
26702 in any case fully under programmer control. However, using the pragma
26703 everywhere is not always possible.
26704 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
26705 we marked both of them as having pragma @code{Elaborate_Body}, then
26706 clearly there would be no possible elaboration order.
26707
26708 The above pragmas allow a server to guarantee safe use by clients, and
26709 clearly this is the preferable approach. Consequently a good rule
26710 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
26711 and if this is not possible,
26712 mark them as @code{Elaborate_Body} if possible.
26713 As we have seen, there are situations where neither of these
26714 three pragmas can be used.
26715 So we also provide methods for clients to control the
26716 order of elaboration of the servers on which they depend:
26717
26718 @table @asis
26719 @item pragma Elaborate (unit)
26720 @findex Elaborate
26721 @cindex pragma Elaborate
26722 This pragma is placed in the context clause, after a @code{with} clause,
26723 and it requires that the body of the named unit be elaborated before
26724 the unit in which the pragma occurs. The idea is to use this pragma
26725 if the current unit calls at elaboration time, directly or indirectly,
26726 some subprogram in the named unit.
26727
26728 @item pragma Elaborate_All (unit)
26729 @findex Elaborate_All
26730 @cindex pragma Elaborate_All
26731 This is a stronger version of the Elaborate pragma. Consider the
26732 following example:
26733
26734 @smallexample
26735 Unit A @code{with}'s unit B and calls B.Func in elab code
26736 Unit B @code{with}'s unit C, and B.Func calls C.Func
26737 @end smallexample
26738
26739 @noindent
26740 Now if we put a pragma @code{Elaborate (B)}
26741 in unit @code{A}, this ensures that the
26742 body of @code{B} is elaborated before the call, but not the
26743 body of @code{C}, so
26744 the call to @code{C.Func} could still cause @code{Program_Error} to
26745 be raised.
26746
26747 The effect of a pragma @code{Elaborate_All} is stronger, it requires
26748 not only that the body of the named unit be elaborated before the
26749 unit doing the @code{with}, but also the bodies of all units that the
26750 named unit uses, following @code{with} links transitively. For example,
26751 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
26752 then it requires
26753 not only that the body of @code{B} be elaborated before @code{A},
26754 but also the
26755 body of @code{C}, because @code{B} @code{with}'s @code{C}.
26756 @end table
26757
26758 @noindent
26759 We are now in a position to give a usage rule in Ada for avoiding
26760 elaboration problems, at least if dynamic dispatching and access to
26761 subprogram values are not used. We will handle these cases separately
26762 later.
26763
26764 The rule is simple. If a unit has elaboration code that can directly or
26765 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
26766 a generic package in a @code{with}'ed unit,
26767 then if the @code{with}'ed unit does not have
26768 pragma @code{Pure} or @code{Preelaborate}, then the client should have
26769 a pragma @code{Elaborate_All}
26770 for the @code{with}'ed unit. By following this rule a client is
26771 assured that calls can be made without risk of an exception.
26772
26773 For generic subprogram instantiations, the rule can be relaxed to
26774 require only a pragma @code{Elaborate} since elaborating the body
26775 of a subprogram cannot cause any transitive elaboration (we are
26776 not calling the subprogram in this case, just elaborating its
26777 declaration).
26778
26779 If this rule is not followed, then a program may be in one of four
26780 states:
26781
26782 @table @asis
26783 @item No order exists
26784 No order of elaboration exists which follows the rules, taking into
26785 account any @code{Elaborate}, @code{Elaborate_All},
26786 or @code{Elaborate_Body} pragmas. In
26787 this case, an Ada compiler must diagnose the situation at bind
26788 time, and refuse to build an executable program.
26789
26790 @item One or more orders exist, all incorrect
26791 One or more acceptable elaboration orders exist, and all of them
26792 generate an elaboration order problem. In this case, the binder
26793 can build an executable program, but @code{Program_Error} will be raised
26794 when the program is run.
26795
26796 @item Several orders exist, some right, some incorrect
26797 One or more acceptable elaboration orders exists, and some of them
26798 work, and some do not. The programmer has not controlled
26799 the order of elaboration, so the binder may or may not pick one of
26800 the correct orders, and the program may or may not raise an
26801 exception when it is run. This is the worst case, because it means
26802 that the program may fail when moved to another compiler, or even
26803 another version of the same compiler.
26804
26805 @item One or more orders exists, all correct
26806 One ore more acceptable elaboration orders exist, and all of them
26807 work. In this case the program runs successfully. This state of
26808 affairs can be guaranteed by following the rule we gave above, but
26809 may be true even if the rule is not followed.
26810 @end table
26811
26812 @noindent
26813 Note that one additional advantage of following our rules on the use
26814 of @code{Elaborate} and @code{Elaborate_All}
26815 is that the program continues to stay in the ideal (all orders OK) state
26816 even if maintenance
26817 changes some bodies of some units. Conversely, if a program that does
26818 not follow this rule happens to be safe at some point, this state of affairs
26819 may deteriorate silently as a result of maintenance changes.
26820
26821 You may have noticed that the above discussion did not mention
26822 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
26823 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
26824 code in the body makes calls to some other unit, so it is still necessary
26825 to use @code{Elaborate_All} on such units.
26826
26827 @node Controlling Elaboration in GNAT - Internal Calls
26828 @section Controlling Elaboration in GNAT - Internal Calls
26829
26830 @noindent
26831 In the case of internal calls, i.e., calls within a single package, the
26832 programmer has full control over the order of elaboration, and it is up
26833 to the programmer to elaborate declarations in an appropriate order. For
26834 example writing:
26835
26836 @smallexample @c ada
26837 @group
26838 @cartouche
26839 function One return Float;
26840
26841 Q : Float := One;
26842
26843 function One return Float is
26844 begin
26845      return 1.0;
26846 end One;
26847 @end cartouche
26848 @end group
26849 @end smallexample
26850
26851 @noindent
26852 will obviously raise @code{Program_Error} at run time, because function
26853 One will be called before its body is elaborated. In this case GNAT will
26854 generate a warning that the call will raise @code{Program_Error}:
26855
26856 @smallexample
26857 @group
26858 @cartouche
26859  1. procedure y is
26860  2.    function One return Float;
26861  3.
26862  4.    Q : Float := One;
26863                     |
26864     >>> warning: cannot call "One" before body is elaborated
26865     >>> warning: Program_Error will be raised at run time
26866
26867  5.
26868  6.    function One return Float is
26869  7.    begin
26870  8.         return 1.0;
26871  9.    end One;
26872 10.
26873 11. begin
26874 12.    null;
26875 13. end;
26876 @end cartouche
26877 @end group
26878 @end smallexample
26879
26880 @noindent
26881 Note that in this particular case, it is likely that the call is safe, because
26882 the function @code{One} does not access any global variables.
26883 Nevertheless in Ada, we do not want the validity of the check to depend on
26884 the contents of the body (think about the separate compilation case), so this
26885 is still wrong, as we discussed in the previous sections.
26886
26887 The error is easily corrected by rearranging the declarations so that the
26888 body of @code{One} appears before the declaration containing the call
26889 (note that in Ada 95 and Ada 2005,
26890 declarations can appear in any order, so there is no restriction that
26891 would prevent this reordering, and if we write:
26892
26893 @smallexample @c ada
26894 @group
26895 @cartouche
26896 function One return Float;
26897
26898 function One return Float is
26899 begin
26900      return 1.0;
26901 end One;
26902
26903 Q : Float := One;
26904 @end cartouche
26905 @end group
26906 @end smallexample
26907
26908 @noindent
26909 then all is well, no warning is generated, and no
26910 @code{Program_Error} exception
26911 will be raised.
26912 Things are more complicated when a chain of subprograms is executed:
26913
26914 @smallexample @c ada
26915 @group
26916 @cartouche
26917 function A return Integer;
26918 function B return Integer;
26919 function C return Integer;
26920
26921 function B return Integer is begin return A; end;
26922 function C return Integer is begin return B; end;
26923
26924 X : Integer := C;
26925
26926 function A return Integer is begin return 1; end;
26927 @end cartouche
26928 @end group
26929 @end smallexample
26930
26931 @noindent
26932 Now the call to @code{C}
26933 at elaboration time in the declaration of @code{X} is correct, because
26934 the body of @code{C} is already elaborated,
26935 and the call to @code{B} within the body of
26936 @code{C} is correct, but the call
26937 to @code{A} within the body of @code{B} is incorrect, because the body
26938 of @code{A} has not been elaborated, so @code{Program_Error}
26939 will be raised on the call to @code{A}.
26940 In this case GNAT will generate a
26941 warning that @code{Program_Error} may be
26942 raised at the point of the call. Let's look at the warning:
26943
26944 @smallexample
26945 @group
26946 @cartouche
26947  1. procedure x is
26948  2.    function A return Integer;
26949  3.    function B return Integer;
26950  4.    function C return Integer;
26951  5.
26952  6.    function B return Integer is begin return A; end;
26953                                                     |
26954     >>> warning: call to "A" before body is elaborated may
26955                  raise Program_Error
26956     >>> warning: "B" called at line 7
26957     >>> warning: "C" called at line 9
26958
26959  7.    function C return Integer is begin return B; end;
26960  8.
26961  9.    X : Integer := C;
26962 10.
26963 11.    function A return Integer is begin return 1; end;
26964 12.
26965 13. begin
26966 14.    null;
26967 15. end;
26968 @end cartouche
26969 @end group
26970 @end smallexample
26971
26972 @noindent
26973 Note that the message here says ``may raise'', instead of the direct case,
26974 where the message says ``will be raised''. That's because whether
26975 @code{A} is
26976 actually called depends in general on run-time flow of control.
26977 For example, if the body of @code{B} said
26978
26979 @smallexample @c ada
26980 @group
26981 @cartouche
26982 function B return Integer is
26983 begin
26984    if some-condition-depending-on-input-data then
26985       return A;
26986    else
26987       return 1;
26988    end if;
26989 end B;
26990 @end cartouche
26991 @end group
26992 @end smallexample
26993
26994 @noindent
26995 then we could not know until run time whether the incorrect call to A would
26996 actually occur, so @code{Program_Error} might
26997 or might not be raised. It is possible for a compiler to
26998 do a better job of analyzing bodies, to
26999 determine whether or not @code{Program_Error}
27000 might be raised, but it certainly
27001 couldn't do a perfect job (that would require solving the halting problem
27002 and is provably impossible), and because this is a warning anyway, it does
27003 not seem worth the effort to do the analysis. Cases in which it
27004 would be relevant are rare.
27005
27006 In practice, warnings of either of the forms given
27007 above will usually correspond to
27008 real errors, and should be examined carefully and eliminated.
27009 In the rare case where a warning is bogus, it can be suppressed by any of
27010 the following methods:
27011
27012 @itemize @bullet
27013 @item
27014 Compile with the @option{-gnatws} switch set
27015
27016 @item
27017 Suppress @code{Elaboration_Check} for the called subprogram
27018
27019 @item
27020 Use pragma @code{Warnings_Off} to turn warnings off for the call
27021 @end itemize
27022
27023 @noindent
27024 For the internal elaboration check case,
27025 GNAT by default generates the
27026 necessary run-time checks to ensure
27027 that @code{Program_Error} is raised if any
27028 call fails an elaboration check. Of course this can only happen if a
27029 warning has been issued as described above. The use of pragma
27030 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27031 some of these checks, meaning that it may be possible (but is not
27032 guaranteed) for a program to be able to call a subprogram whose body
27033 is not yet elaborated, without raising a @code{Program_Error} exception.
27034
27035 @node Controlling Elaboration in GNAT - External Calls
27036 @section Controlling Elaboration in GNAT - External Calls
27037
27038 @noindent
27039 The previous section discussed the case in which the execution of a
27040 particular thread of elaboration code occurred entirely within a
27041 single unit. This is the easy case to handle, because a programmer
27042 has direct and total control over the order of elaboration, and
27043 furthermore, checks need only be generated in cases which are rare
27044 and which the compiler can easily detect.
27045 The situation is more complex when separate compilation is taken into account.
27046 Consider the following:
27047
27048 @smallexample @c ada
27049 @cartouche
27050 @group
27051 package Math is
27052    function Sqrt (Arg : Float) return Float;
27053 end Math;
27054
27055 package body Math is
27056    function Sqrt (Arg : Float) return Float is
27057    begin
27058          @dots{}
27059    end Sqrt;
27060 end Math;
27061 @end group
27062 @group
27063 with Math;
27064 package Stuff is
27065    X : Float := Math.Sqrt (0.5);
27066 end Stuff;
27067
27068 with Stuff;
27069 procedure Main is
27070 begin
27071    @dots{}
27072 end Main;
27073 @end group
27074 @end cartouche
27075 @end smallexample
27076
27077 @noindent
27078 where @code{Main} is the main program. When this program is executed, the
27079 elaboration code must first be executed, and one of the jobs of the
27080 binder is to determine the order in which the units of a program are
27081 to be elaborated. In this case we have four units: the spec and body
27082 of @code{Math},
27083 the spec of @code{Stuff} and the body of @code{Main}).
27084 In what order should the four separate sections of elaboration code
27085 be executed?
27086
27087 There are some restrictions in the order of elaboration that the binder
27088 can choose. In particular, if unit U has a @code{with}
27089 for a package @code{X}, then you
27090 are assured that the spec of @code{X}
27091 is elaborated before U , but you are
27092 not assured that the body of @code{X}
27093 is elaborated before U.
27094 This means that in the above case, the binder is allowed to choose the
27095 order:
27096
27097 @smallexample
27098 spec of Math
27099 spec of Stuff
27100 body of Math
27101 body of Main
27102 @end smallexample
27103
27104 @noindent
27105 but that's not good, because now the call to @code{Math.Sqrt}
27106 that happens during
27107 the elaboration of the @code{Stuff}
27108 spec happens before the body of @code{Math.Sqrt} is
27109 elaborated, and hence causes @code{Program_Error} exception to be raised.
27110 At first glance, one might say that the binder is misbehaving, because
27111 obviously you want to elaborate the body of something you @code{with}
27112 first, but
27113 that is not a general rule that can be followed in all cases. Consider
27114
27115 @smallexample @c ada
27116 @group
27117 @cartouche
27118 package X is @dots{}
27119
27120 package Y is @dots{}
27121
27122 with X;
27123 package body Y is @dots{}
27124
27125 with Y;
27126 package body X is @dots{}
27127 @end cartouche
27128 @end group
27129 @end smallexample
27130
27131 @noindent
27132 This is a common arrangement, and, apart from the order of elaboration
27133 problems that might arise in connection with elaboration code, this works fine.
27134 A rule that says that you must first elaborate the body of anything you
27135 @code{with} cannot work in this case:
27136 the body of @code{X} @code{with}'s @code{Y},
27137 which means you would have to
27138 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
27139 which means
27140 you have to elaborate the body of @code{X} first, but @dots{} and we have a
27141 loop that cannot be broken.
27142
27143 It is true that the binder can in many cases guess an order of elaboration
27144 that is unlikely to cause a @code{Program_Error}
27145 exception to be raised, and it tries to do so (in the
27146 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27147 by default
27148 elaborate the body of @code{Math} right after its spec, so all will be well).
27149
27150 However, a program that blindly relies on the binder to be helpful can
27151 get into trouble, as we discussed in the previous sections, so
27152 GNAT
27153 provides a number of facilities for assisting the programmer in
27154 developing programs that are robust with respect to elaboration order.
27155
27156 @node Default Behavior in GNAT - Ensuring Safety
27157 @section Default Behavior in GNAT - Ensuring Safety
27158
27159 @noindent
27160 The default behavior in GNAT ensures elaboration safety. In its
27161 default mode GNAT implements the
27162 rule we previously described as the right approach. Let's restate it:
27163
27164 @itemize
27165 @item
27166 @emph{If a unit has elaboration code that can directly or indirectly make a
27167 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
27168 package in a @code{with}'ed unit, then if the @code{with}'ed unit
27169 does not have pragma @code{Pure} or
27170 @code{Preelaborate}, then the client should have an
27171 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
27172
27173 @emph{In the case of instantiating a generic subprogram, it is always
27174 sufficient to have only an @code{Elaborate} pragma for the
27175 @code{with}'ed unit.}
27176 @end itemize
27177
27178 @noindent
27179 By following this rule a client is assured that calls and instantiations
27180 can be made without risk of an exception.
27181
27182 In this mode GNAT traces all calls that are potentially made from
27183 elaboration code, and puts in any missing implicit @code{Elaborate}
27184 and @code{Elaborate_All} pragmas.
27185 The advantage of this approach is that no elaboration problems
27186 are possible if the binder can find an elaboration order that is
27187 consistent with these implicit @code{Elaborate} and
27188 @code{Elaborate_All} pragmas. The
27189 disadvantage of this approach is that no such order may exist.
27190
27191 If the binder does not generate any diagnostics, then it means that it has
27192 found an elaboration order that is guaranteed to be safe. However, the binder
27193 may still be relying on implicitly generated @code{Elaborate} and
27194 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27195 guaranteed.
27196
27197 If it is important to guarantee portability, then the compilations should
27198 use the
27199 @option{-gnatwl}
27200 (warn on elaboration problems) switch. This will cause warning messages
27201 to be generated indicating the missing @code{Elaborate} and
27202 @code{Elaborate_All} pragmas.
27203 Consider the following source program:
27204
27205 @smallexample @c ada
27206 @group
27207 @cartouche
27208 with k;
27209 package j is
27210   m : integer := k.r;
27211 end;
27212 @end cartouche
27213 @end group
27214 @end smallexample
27215
27216 @noindent
27217 where it is clear that there
27218 should be a pragma @code{Elaborate_All}
27219 for unit @code{k}. An implicit pragma will be generated, and it is
27220 likely that the binder will be able to honor it. However, if you want
27221 to port this program to some other Ada compiler than GNAT.
27222 it is safer to include the pragma explicitly in the source. If this
27223 unit is compiled with the
27224 @option{-gnatwl}
27225 switch, then the compiler outputs a warning:
27226
27227 @smallexample
27228 @group
27229 @cartouche
27230 1. with k;
27231 2. package j is
27232 3.   m : integer := k.r;
27233                      |
27234    >>> warning: call to "r" may raise Program_Error
27235    >>> warning: missing pragma Elaborate_All for "k"
27236
27237 4. end;
27238 @end cartouche
27239 @end group
27240 @end smallexample
27241
27242 @noindent
27243 and these warnings can be used as a guide for supplying manually
27244 the missing pragmas. It is usually a bad idea to use this warning
27245 option during development. That's because it will warn you when
27246 you need to put in a pragma, but cannot warn you when it is time
27247 to take it out. So the use of pragma @code{Elaborate_All} may lead to
27248 unnecessary dependencies and even false circularities.
27249
27250 This default mode is more restrictive than the Ada Reference
27251 Manual, and it is possible to construct programs which will compile
27252 using the dynamic model described there, but will run into a
27253 circularity using the safer static model we have described.
27254
27255 Of course any Ada compiler must be able to operate in a mode
27256 consistent with the requirements of the Ada Reference Manual,
27257 and in particular must have the capability of implementing the
27258 standard dynamic model of elaboration with run-time checks.
27259
27260 In GNAT, this standard mode can be achieved either by the use of
27261 the @option{-gnatE} switch on the compiler (@command{gcc} or
27262 @command{gnatmake}) command, or by the use of the configuration pragma:
27263
27264 @smallexample @c ada
27265 pragma Elaboration_Checks (DYNAMIC);
27266 @end smallexample
27267
27268 @noindent
27269 Either approach will cause the unit affected to be compiled using the
27270 standard dynamic run-time elaboration checks described in the Ada
27271 Reference Manual. The static model is generally preferable, since it
27272 is clearly safer to rely on compile and link time checks rather than
27273 run-time checks. However, in the case of legacy code, it may be
27274 difficult to meet the requirements of the static model. This
27275 issue is further discussed in
27276 @ref{What to Do If the Default Elaboration Behavior Fails}.
27277
27278 Note that the static model provides a strict subset of the allowed
27279 behavior and programs of the Ada Reference Manual, so if you do
27280 adhere to the static model and no circularities exist,
27281 then you are assured that your program will
27282 work using the dynamic model, providing that you remove any
27283 pragma Elaborate statements from the source.
27284
27285 @node Treatment of Pragma Elaborate
27286 @section Treatment of Pragma Elaborate
27287 @cindex Pragma Elaborate
27288
27289 @noindent
27290 The use of @code{pragma Elaborate}
27291 should generally be avoided in Ada 95 and Ada 2005 programs,
27292 since there is no guarantee that transitive calls
27293 will be properly handled. Indeed at one point, this pragma was placed
27294 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27295
27296 Now that's a bit restrictive. In practice, the case in which
27297 @code{pragma Elaborate} is useful is when the caller knows that there
27298 are no transitive calls, or that the called unit contains all necessary
27299 transitive @code{pragma Elaborate} statements, and legacy code often
27300 contains such uses.
27301
27302 Strictly speaking the static mode in GNAT should ignore such pragmas,
27303 since there is no assurance at compile time that the necessary safety
27304 conditions are met. In practice, this would cause GNAT to be incompatible
27305 with correctly written Ada 83 code that had all necessary
27306 @code{pragma Elaborate} statements in place. Consequently, we made the
27307 decision that GNAT in its default mode will believe that if it encounters
27308 a @code{pragma Elaborate} then the programmer knows what they are doing,
27309 and it will trust that no elaboration errors can occur.
27310
27311 The result of this decision is two-fold. First to be safe using the
27312 static mode, you should remove all @code{pragma Elaborate} statements.
27313 Second, when fixing circularities in existing code, you can selectively
27314 use @code{pragma Elaborate} statements to convince the static mode of
27315 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
27316 statement.
27317
27318 When using the static mode with @option{-gnatwl}, any use of
27319 @code{pragma Elaborate} will generate a warning about possible
27320 problems.
27321
27322 @node Elaboration Issues for Library Tasks
27323 @section Elaboration Issues for Library Tasks
27324 @cindex Library tasks, elaboration issues
27325 @cindex Elaboration of library tasks
27326
27327 @noindent
27328 In this section we examine special elaboration issues that arise for
27329 programs that declare library level tasks.
27330
27331 Generally the model of execution of an Ada program is that all units are
27332 elaborated, and then execution of the program starts. However, the
27333 declaration of library tasks definitely does not fit this model. The
27334 reason for this is that library tasks start as soon as they are declared
27335 (more precisely, as soon as the statement part of the enclosing package
27336 body is reached), that is to say before elaboration
27337 of the program is complete. This means that if such a task calls a
27338 subprogram, or an entry in another task, the callee may or may not be
27339 elaborated yet, and in the standard
27340 Reference Manual model of dynamic elaboration checks, you can even
27341 get timing dependent Program_Error exceptions, since there can be
27342 a race between the elaboration code and the task code.
27343
27344 The static model of elaboration in GNAT seeks to avoid all such
27345 dynamic behavior, by being conservative, and the conservative
27346 approach in this particular case is to assume that all the code
27347 in a task body is potentially executed at elaboration time if
27348 a task is declared at the library level.
27349
27350 This can definitely result in unexpected circularities. Consider
27351 the following example
27352
27353 @smallexample @c ada
27354 package Decls is
27355   task Lib_Task is
27356      entry Start;
27357   end Lib_Task;
27358
27359   type My_Int is new Integer;
27360
27361   function Ident (M : My_Int) return My_Int;
27362 end Decls;
27363
27364 with Utils;
27365 package body Decls is
27366   task body Lib_Task is
27367   begin
27368      accept Start;
27369      Utils.Put_Val (2);
27370   end Lib_Task;
27371
27372   function Ident (M : My_Int) return My_Int is
27373   begin
27374      return M;
27375   end Ident;
27376 end Decls;
27377
27378 with Decls;
27379 package Utils is
27380   procedure Put_Val (Arg : Decls.My_Int);
27381 end Utils;
27382
27383 with Text_IO;
27384 package body Utils is
27385   procedure Put_Val (Arg : Decls.My_Int) is
27386   begin
27387      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27388   end Put_Val;
27389 end Utils;
27390
27391 with Decls;
27392 procedure Main is
27393 begin
27394    Decls.Lib_Task.Start;
27395 end;
27396 @end smallexample
27397
27398 @noindent
27399 If the above example is compiled in the default static elaboration
27400 mode, then a circularity occurs. The circularity comes from the call
27401 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
27402 this call occurs in elaboration code, we need an implicit pragma
27403 @code{Elaborate_All} for @code{Utils}. This means that not only must
27404 the spec and body of @code{Utils} be elaborated before the body
27405 of @code{Decls}, but also the spec and body of any unit that is
27406 @code{with'ed} by the body of @code{Utils} must also be elaborated before
27407 the body of @code{Decls}. This is the transitive implication of
27408 pragma @code{Elaborate_All} and it makes sense, because in general
27409 the body of @code{Put_Val} might have a call to something in a
27410 @code{with'ed} unit.
27411
27412 In this case, the body of Utils (actually its spec) @code{with's}
27413 @code{Decls}. Unfortunately this means that the body of @code{Decls}
27414 must be elaborated before itself, in case there is a call from the
27415 body of @code{Utils}.
27416
27417 Here is the exact chain of events we are worrying about:
27418
27419 @enumerate
27420 @item
27421 In the body of @code{Decls} a call is made from within the body of a library
27422 task to a subprogram in the package @code{Utils}. Since this call may
27423 occur at elaboration time (given that the task is activated at elaboration
27424 time), we have to assume the worst, i.e., that the
27425 call does happen at elaboration time.
27426
27427 @item
27428 This means that the body and spec of @code{Util} must be elaborated before
27429 the body of @code{Decls} so that this call does not cause an access before
27430 elaboration.
27431
27432 @item
27433 Within the body of @code{Util}, specifically within the body of
27434 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
27435 by this package.
27436
27437 @item
27438 One such @code{with}'ed package is package @code{Decls}, so there
27439 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
27440 In fact there is such a call in this example, but we would have to
27441 assume that there was such a call even if it were not there, since
27442 we are not supposed to write the body of @code{Decls} knowing what
27443 is in the body of @code{Utils}; certainly in the case of the
27444 static elaboration model, the compiler does not know what is in
27445 other bodies and must assume the worst.
27446
27447 @item
27448 This means that the spec and body of @code{Decls} must also be
27449 elaborated before we elaborate the unit containing the call, but
27450 that unit is @code{Decls}! This means that the body of @code{Decls}
27451 must be elaborated before itself, and that's a circularity.
27452 @end enumerate
27453
27454 @noindent
27455 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
27456 the body of @code{Decls} you will get a true Ada Reference Manual
27457 circularity that makes the program illegal.
27458
27459 In practice, we have found that problems with the static model of
27460 elaboration in existing code often arise from library tasks, so
27461 we must address this particular situation.
27462
27463 Note that if we compile and run the program above, using the dynamic model of
27464 elaboration (that is to say use the @option{-gnatE} switch),
27465 then it compiles, binds,
27466 links, and runs, printing the expected result of 2. Therefore in some sense
27467 the circularity here is only apparent, and we need to capture
27468 the properties of this program that  distinguish it from other library-level
27469 tasks that have real elaboration problems.
27470
27471 We have four possible answers to this question:
27472
27473 @itemize @bullet
27474
27475 @item
27476 Use the dynamic model of elaboration.
27477
27478 If we use the @option{-gnatE} switch, then as noted above, the program works.
27479 Why is this? If we examine the task body, it is apparent that the task cannot
27480 proceed past the
27481 @code{accept} statement until after elaboration has been completed, because
27482 the corresponding entry call comes from the main program, not earlier.
27483 This is why the dynamic model works here. But that's really giving
27484 up on a precise analysis, and we prefer to take this approach only if we cannot
27485 solve the
27486 problem in any other manner. So let us examine two ways to reorganize
27487 the program to avoid the potential elaboration problem.
27488
27489 @item
27490 Split library tasks into separate packages.
27491
27492 Write separate packages, so that library tasks are isolated from
27493 other declarations as much as possible. Let us look at a variation on
27494 the above program.
27495
27496 @smallexample @c ada
27497 package Decls1 is
27498   task Lib_Task is
27499      entry Start;
27500   end Lib_Task;
27501 end Decls1;
27502
27503 with Utils;
27504 package body Decls1 is
27505   task body Lib_Task is
27506   begin
27507      accept Start;
27508      Utils.Put_Val (2);
27509   end Lib_Task;
27510 end Decls1;
27511
27512 package Decls2 is
27513   type My_Int is new Integer;
27514   function Ident (M : My_Int) return My_Int;
27515 end Decls2;
27516
27517 with Utils;
27518 package body Decls2 is
27519   function Ident (M : My_Int) return My_Int is
27520   begin
27521      return M;
27522   end Ident;
27523 end Decls2;
27524
27525 with Decls2;
27526 package Utils is
27527   procedure Put_Val (Arg : Decls2.My_Int);
27528 end Utils;
27529
27530 with Text_IO;
27531 package body Utils is
27532   procedure Put_Val (Arg : Decls2.My_Int) is
27533   begin
27534      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
27535   end Put_Val;
27536 end Utils;
27537
27538 with Decls1;
27539 procedure Main is
27540 begin
27541    Decls1.Lib_Task.Start;
27542 end;
27543 @end smallexample
27544
27545 @noindent
27546 All we have done is to split @code{Decls} into two packages, one
27547 containing the library task, and one containing everything else. Now
27548 there is no cycle, and the program compiles, binds, links and executes
27549 using the default static model of elaboration.
27550
27551 @item
27552 Declare separate task types.
27553
27554 A significant part of the problem arises because of the use of the
27555 single task declaration form. This means that the elaboration of
27556 the task type, and the elaboration of the task itself (i.e.@: the
27557 creation of the task) happen at the same time. A good rule
27558 of style in Ada is to always create explicit task types. By
27559 following the additional step of placing task objects in separate
27560 packages from the task type declaration, many elaboration problems
27561 are avoided. Here is another modified example of the example program:
27562
27563 @smallexample @c ada
27564 package Decls is
27565   task type Lib_Task_Type is
27566      entry Start;
27567   end Lib_Task_Type;
27568
27569   type My_Int is new Integer;
27570
27571   function Ident (M : My_Int) return My_Int;
27572 end Decls;
27573
27574 with Utils;
27575 package body Decls is
27576   task body Lib_Task_Type is
27577   begin
27578      accept Start;
27579      Utils.Put_Val (2);
27580   end Lib_Task_Type;
27581
27582   function Ident (M : My_Int) return My_Int is
27583   begin
27584      return M;
27585   end Ident;
27586 end Decls;
27587
27588 with Decls;
27589 package Utils is
27590   procedure Put_Val (Arg : Decls.My_Int);
27591 end Utils;
27592
27593 with Text_IO;
27594 package body Utils is
27595   procedure Put_Val (Arg : Decls.My_Int) is
27596   begin
27597      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27598   end Put_Val;
27599 end Utils;
27600
27601 with Decls;
27602 package Declst is
27603    Lib_Task : Decls.Lib_Task_Type;
27604 end Declst;
27605
27606 with Declst;
27607 procedure Main is
27608 begin
27609    Declst.Lib_Task.Start;
27610 end;
27611 @end smallexample
27612
27613 @noindent
27614 What we have done here is to replace the @code{task} declaration in
27615 package @code{Decls} with a @code{task type} declaration. Then we
27616 introduce a separate package @code{Declst} to contain the actual
27617 task object. This separates the elaboration issues for
27618 the @code{task type}
27619 declaration, which causes no trouble, from the elaboration issues
27620 of the task object, which is also unproblematic, since it is now independent
27621 of the elaboration of  @code{Utils}.
27622 This separation of concerns also corresponds to
27623 a generally sound engineering principle of separating declarations
27624 from instances. This version of the program also compiles, binds, links,
27625 and executes, generating the expected output.
27626
27627 @item
27628 Use No_Entry_Calls_In_Elaboration_Code restriction.
27629 @cindex No_Entry_Calls_In_Elaboration_Code
27630
27631 The previous two approaches described how a program can be restructured
27632 to avoid the special problems caused by library task bodies. in practice,
27633 however, such restructuring may be difficult to apply to existing legacy code,
27634 so we must consider solutions that do not require massive rewriting.
27635
27636 Let us consider more carefully why our original sample program works
27637 under the dynamic model of elaboration. The reason is that the code
27638 in the task body blocks immediately on the @code{accept}
27639 statement. Now of course there is nothing to prohibit elaboration
27640 code from making entry calls (for example from another library level task),
27641 so we cannot tell in isolation that
27642 the task will not execute the accept statement  during elaboration.
27643
27644 However, in practice it is very unusual to see elaboration code
27645 make any entry calls, and the pattern of tasks starting
27646 at elaboration time and then immediately blocking on @code{accept} or
27647 @code{select} statements is very common. What this means is that
27648 the compiler is being too pessimistic when it analyzes the
27649 whole package body as though it might be executed at elaboration
27650 time.
27651
27652 If we know that the elaboration code contains no entry calls, (a very safe
27653 assumption most of the time, that could almost be made the default
27654 behavior), then we can compile all units of the program under control
27655 of the following configuration pragma:
27656
27657 @smallexample
27658 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
27659 @end smallexample
27660
27661 @noindent
27662 This pragma can be placed in the @file{gnat.adc} file in the usual
27663 manner. If we take our original unmodified program and compile it
27664 in the presence of a @file{gnat.adc} containing the above pragma,
27665 then once again, we can compile, bind, link, and execute, obtaining
27666 the expected result. In the presence of this pragma, the compiler does
27667 not trace calls in a task body, that appear after the first @code{accept}
27668 or @code{select} statement, and therefore does not report a potential
27669 circularity in the original program.
27670
27671 The compiler will check to the extent it can that the above
27672 restriction is not violated, but it is not always possible to do a
27673 complete check at compile time, so it is important to use this
27674 pragma only if the stated restriction is in fact met, that is to say
27675 no task receives an entry call before elaboration of all units is completed.
27676
27677 @end itemize
27678
27679 @node Mixing Elaboration Models
27680 @section Mixing Elaboration Models
27681 @noindent
27682 So far, we have assumed that the entire program is either compiled
27683 using the dynamic model or static model, ensuring consistency. It
27684 is possible to mix the two models, but rules have to be followed
27685 if this mixing is done to ensure that elaboration checks are not
27686 omitted.
27687
27688 The basic rule is that @emph{a unit compiled with the static model cannot
27689 be @code{with'ed} by a unit compiled with the dynamic model}. The
27690 reason for this is that in the static model, a unit assumes that
27691 its clients guarantee to use (the equivalent of) pragma
27692 @code{Elaborate_All} so that no elaboration checks are required
27693 in inner subprograms, and this assumption is violated if the
27694 client is compiled with dynamic checks.
27695
27696 The precise rule is as follows. A unit that is compiled with dynamic
27697 checks can only @code{with} a unit that meets at least one of the
27698 following criteria:
27699
27700 @itemize @bullet
27701
27702 @item
27703 The @code{with'ed} unit is itself compiled with dynamic elaboration
27704 checks (that is with the @option{-gnatE} switch.
27705
27706 @item
27707 The @code{with'ed} unit is an internal GNAT implementation unit from
27708 the System, Interfaces, Ada, or GNAT hierarchies.
27709
27710 @item
27711 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
27712
27713 @item
27714 The @code{with'ing} unit (that is the client) has an explicit pragma
27715 @code{Elaborate_All} for the @code{with'ed} unit.
27716
27717 @end itemize
27718
27719 @noindent
27720 If this rule is violated, that is if a unit with dynamic elaboration
27721 checks @code{with's} a unit that does not meet one of the above four
27722 criteria, then the binder (@code{gnatbind}) will issue a warning
27723 similar to that in the following example:
27724
27725 @smallexample
27726 warning: "x.ads" has dynamic elaboration checks and with's
27727 warning:   "y.ads" which has static elaboration checks
27728 @end smallexample
27729
27730 @noindent
27731 These warnings indicate that the rule has been violated, and that as a result
27732 elaboration checks may be missed in the resulting executable file.
27733 This warning may be suppressed using the @option{-ws} binder switch
27734 in the usual manner.
27735
27736 One useful application of this mixing rule is in the case of a subsystem
27737 which does not itself @code{with} units from the remainder of the
27738 application. In this case, the entire subsystem can be compiled with
27739 dynamic checks to resolve a circularity in the subsystem, while
27740 allowing the main application that uses this subsystem to be compiled
27741 using the more reliable default static model.
27742
27743 @node What to Do If the Default Elaboration Behavior Fails
27744 @section What to Do If the Default Elaboration Behavior Fails
27745
27746 @noindent
27747 If the binder cannot find an acceptable order, it outputs detailed
27748 diagnostics. For example:
27749 @smallexample
27750 @group
27751 @iftex
27752 @leftskip=0cm
27753 @end iftex
27754 error: elaboration circularity detected
27755 info:   "proc (body)" must be elaborated before "pack (body)"
27756 info:     reason: Elaborate_All probably needed in unit "pack (body)"
27757 info:     recompile "pack (body)" with -gnatwl
27758 info:                             for full details
27759 info:       "proc (body)"
27760 info:         is needed by its spec:
27761 info:       "proc (spec)"
27762 info:         which is withed by:
27763 info:       "pack (body)"
27764 info:  "pack (body)" must be elaborated before "proc (body)"
27765 info:     reason: pragma Elaborate in unit "proc (body)"
27766 @end group
27767
27768 @end smallexample
27769
27770 @noindent
27771 In this case we have a cycle that the binder cannot break. On the one
27772 hand, there is an explicit pragma Elaborate in @code{proc} for
27773 @code{pack}. This means that the body of @code{pack} must be elaborated
27774 before the body of @code{proc}. On the other hand, there is elaboration
27775 code in @code{pack} that calls a subprogram in @code{proc}. This means
27776 that for maximum safety, there should really be a pragma
27777 Elaborate_All in @code{pack} for @code{proc} which would require that
27778 the body of @code{proc} be elaborated before the body of
27779 @code{pack}. Clearly both requirements cannot be satisfied.
27780 Faced with a circularity of this kind, you have three different options.
27781
27782 @table @asis
27783 @item Fix the program
27784 The most desirable option from the point of view of long-term maintenance
27785 is to rearrange the program so that the elaboration problems are avoided.
27786 One useful technique is to place the elaboration code into separate
27787 child packages. Another is to move some of the initialization code to
27788 explicitly called subprograms, where the program controls the order
27789 of initialization explicitly. Although this is the most desirable option,
27790 it may be impractical and involve too much modification, especially in
27791 the case of complex legacy code.
27792
27793 @item Perform dynamic checks
27794 If the compilations are done using the
27795 @option{-gnatE}
27796 (dynamic elaboration check) switch, then GNAT behaves in a quite different
27797 manner. Dynamic checks are generated for all calls that could possibly result
27798 in raising an exception. With this switch, the compiler does not generate
27799 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
27800 exactly as specified in the @cite{Ada Reference Manual}.
27801 The binder will generate
27802 an executable program that may or may not raise @code{Program_Error}, and then
27803 it is the programmer's job to ensure that it does not raise an exception. Note
27804 that it is important to compile all units with the switch, it cannot be used
27805 selectively.
27806
27807 @item Suppress checks
27808 The drawback of dynamic checks is that they generate a
27809 significant overhead at run time, both in space and time. If you
27810 are absolutely sure that your program cannot raise any elaboration
27811 exceptions, and you still want to use the dynamic elaboration model,
27812 then you can use the configuration pragma
27813 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
27814 example this pragma could be placed in the @file{gnat.adc} file.
27815
27816 @item Suppress checks selectively
27817 When you know that certain calls or instantiations in elaboration code cannot
27818 possibly lead to an elaboration error, and the binder nevertheless complains
27819 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
27820 elaboration circularities, it is possible to remove those warnings locally and
27821 obtain a program that will bind. Clearly this can be unsafe, and it is the
27822 responsibility of the programmer to make sure that the resulting program has no
27823 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
27824 used with different granularity to suppress warnings and break elaboration
27825 circularities:
27826
27827 @itemize @bullet
27828 @item
27829 Place the pragma that names the called subprogram in the declarative part
27830 that contains the call.
27831
27832 @item
27833 Place the pragma in the declarative part, without naming an entity. This
27834 disables warnings on all calls in the corresponding  declarative region.
27835
27836 @item
27837 Place the pragma in the package spec that declares the called subprogram,
27838 and name the subprogram. This disables warnings on all elaboration calls to
27839 that subprogram.
27840
27841 @item
27842 Place the pragma in the package spec that declares the called subprogram,
27843 without naming any entity. This disables warnings on all elaboration calls to
27844 all subprograms declared in this spec.
27845
27846 @item Use Pragma Elaborate
27847 As previously described in section @xref{Treatment of Pragma Elaborate},
27848 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
27849 that no elaboration checks are required on calls to the designated unit.
27850 There may be cases in which the caller knows that no transitive calls
27851 can occur, so that a @code{pragma Elaborate} will be sufficient in a
27852 case where @code{pragma Elaborate_All} would cause a circularity.
27853 @end itemize
27854
27855 @noindent
27856 These five cases are listed in order of decreasing safety, and therefore
27857 require increasing programmer care in their application. Consider the
27858 following program:
27859
27860 @smallexample @c adanocomment
27861 package Pack1 is
27862   function F1 return Integer;
27863   X1 : Integer;
27864 end Pack1;
27865
27866 package Pack2 is
27867   function F2 return Integer;
27868   function Pure (x : integer) return integer;
27869   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
27870   --  pragma Suppress (Elaboration_Check);              -- (4)
27871 end Pack2;
27872
27873 with Pack2;
27874 package body Pack1 is
27875   function F1 return Integer is
27876   begin
27877     return 100;
27878   end F1;
27879   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
27880 begin
27881   declare
27882     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
27883     --  pragma Suppress(Elaboration_Check);             -- (2)
27884   begin
27885     X1 := Pack2.F2 + 1;                --  Elab. call (2)
27886   end;
27887 end Pack1;
27888
27889 with Pack1;
27890 package body Pack2 is
27891   function F2 return Integer is
27892   begin
27893      return Pack1.F1;
27894   end F2;
27895   function Pure (x : integer) return integer is
27896   begin
27897      return x ** 3 - 3 * x;
27898   end;
27899 end Pack2;
27900
27901 with Pack1, Ada.Text_IO;
27902 procedure Proc3 is
27903 begin
27904   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
27905 end Proc3;
27906 @end smallexample
27907 In the absence of any pragmas, an attempt to bind this program produces
27908 the following diagnostics:
27909 @smallexample
27910 @group
27911 @iftex
27912 @leftskip=.5cm
27913 @end iftex
27914 error: elaboration circularity detected
27915 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
27916 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
27917 info:       recompile "pack1 (body)" with -gnatwl for full details
27918 info:          "pack1 (body)"
27919 info:             must be elaborated along with its spec:
27920 info:          "pack1 (spec)"
27921 info:             which is withed by:
27922 info:          "pack2 (body)"
27923 info:             which must be elaborated along with its spec:
27924 info:          "pack2 (spec)"
27925 info:             which is withed by:
27926 info:          "pack1 (body)"
27927 @end group
27928 @end smallexample
27929 The sources of the circularity are the two calls to @code{Pack2.Pure} and
27930 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
27931 F2 is safe, even though F2 calls F1, because the call appears after the
27932 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
27933 remove the warning on the call. It is also possible to use pragma (2)
27934 because there are no other potentially unsafe calls in the block.
27935
27936 @noindent
27937 The call to @code{Pure} is safe because this function does not depend on the
27938 state of @code{Pack2}. Therefore any call to this function is safe, and it
27939 is correct to place pragma (3) in the corresponding package spec.
27940
27941 @noindent
27942 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
27943 warnings on all calls to functions declared therein. Note that this is not
27944 necessarily safe, and requires more detailed examination of the subprogram
27945 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
27946 be already elaborated.
27947 @end table
27948
27949 @noindent
27950 It is hard to generalize on which of these four approaches should be
27951 taken. Obviously if it is possible to fix the program so that the default
27952 treatment works, this is preferable, but this may not always be practical.
27953 It is certainly simple enough to use
27954 @option{-gnatE}
27955 but the danger in this case is that, even if the GNAT binder
27956 finds a correct elaboration order, it may not always do so,
27957 and certainly a binder from another Ada compiler might not. A
27958 combination of testing and analysis (for which the warnings generated
27959 with the
27960 @option{-gnatwl}
27961 switch can be useful) must be used to ensure that the program is free
27962 of errors. One switch that is useful in this testing is the
27963 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
27964 switch for
27965 @code{gnatbind}.
27966 Normally the binder tries to find an order that has the best chance
27967 of avoiding elaboration problems. However, if this switch is used, the binder
27968 plays a devil's advocate role, and tries to choose the order that
27969 has the best chance of failing. If your program works even with this
27970 switch, then it has a better chance of being error free, but this is still
27971 not a guarantee.
27972
27973 For an example of this approach in action, consider the C-tests (executable
27974 tests) from the ACVC suite. If these are compiled and run with the default
27975 treatment, then all but one of them succeed without generating any error
27976 diagnostics from the binder. However, there is one test that fails, and
27977 this is not surprising, because the whole point of this test is to ensure
27978 that the compiler can handle cases where it is impossible to determine
27979 a correct order statically, and it checks that an exception is indeed
27980 raised at run time.
27981
27982 This one test must be compiled and run using the
27983 @option{-gnatE}
27984 switch, and then it passes. Alternatively, the entire suite can
27985 be run using this switch. It is never wrong to run with the dynamic
27986 elaboration switch if your code is correct, and we assume that the
27987 C-tests are indeed correct (it is less efficient, but efficiency is
27988 not a factor in running the ACVC tests.)
27989
27990 @node Elaboration for Access-to-Subprogram Values
27991 @section Elaboration for Access-to-Subprogram Values
27992 @cindex Access-to-subprogram
27993
27994 @noindent
27995 Access-to-subprogram types (introduced in Ada 95) complicate
27996 the handling of elaboration. The trouble is that it becomes
27997 impossible to tell at compile time which procedure
27998 is being called. This means that it is not possible for the binder
27999 to analyze the elaboration requirements in this case.
28000
28001 If at the point at which the access value is created
28002 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28003 the body of the subprogram is
28004 known to have been elaborated, then the access value is safe, and its use
28005 does not require a check. This may be achieved by appropriate arrangement
28006 of the order of declarations if the subprogram is in the current unit,
28007 or, if the subprogram is in another unit, by using pragma
28008 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28009 on the referenced unit.
28010
28011 If the referenced body is not known to have been elaborated at the point
28012 the access value is created, then any use of the access value must do a
28013 dynamic check, and this dynamic check will fail and raise a
28014 @code{Program_Error} exception if the body has not been elaborated yet.
28015 GNAT will generate the necessary checks, and in addition, if the
28016 @option{-gnatwl}
28017 switch is set, will generate warnings that such checks are required.
28018
28019 The use of dynamic dispatching for tagged types similarly generates
28020 a requirement for dynamic checks, and premature calls to any primitive
28021 operation of a tagged type before the body of the operation has been
28022 elaborated, will result in the raising of @code{Program_Error}.
28023
28024 @node Summary of Procedures for Elaboration Control
28025 @section Summary of Procedures for Elaboration Control
28026 @cindex Elaboration control
28027
28028 @noindent
28029 First, compile your program with the default options, using none of
28030 the special elaboration control switches. If the binder successfully
28031 binds your program, then you can be confident that, apart from issues
28032 raised by the use of access-to-subprogram types and dynamic dispatching,
28033 the program is free of elaboration errors. If it is important that the
28034 program be portable, then use the
28035 @option{-gnatwl}
28036 switch to generate warnings about missing @code{Elaborate} or
28037 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28038
28039 If the program fails to bind using the default static elaboration
28040 handling, then you can fix the program to eliminate the binder
28041 message, or recompile the entire program with the
28042 @option{-gnatE} switch to generate dynamic elaboration checks,
28043 and, if you are sure there really are no elaboration problems,
28044 use a global pragma @code{Suppress (Elaboration_Check)}.
28045
28046 @node Other Elaboration Order Considerations
28047 @section Other Elaboration Order Considerations
28048 @noindent
28049 This section has been entirely concerned with the issue of finding a valid
28050 elaboration order, as defined by the Ada Reference Manual. In a case
28051 where several elaboration orders are valid, the task is to find one
28052 of the possible valid elaboration orders (and the static model in GNAT
28053 will ensure that this is achieved).
28054
28055 The purpose of the elaboration rules in the Ada Reference Manual is to
28056 make sure that no entity is accessed before it has been elaborated. For
28057 a subprogram, this means that the spec and body must have been elaborated
28058 before the subprogram is called. For an object, this means that the object
28059 must have been elaborated before its value is read or written. A violation
28060 of either of these two requirements is an access before elaboration order,
28061 and this section has been all about avoiding such errors.
28062
28063 In the case where more than one order of elaboration is possible, in the
28064 sense that access before elaboration errors are avoided, then any one of
28065 the orders is ``correct'' in the sense that it meets the requirements of
28066 the Ada Reference Manual, and no such error occurs.
28067
28068 However, it may be the case for a given program, that there are
28069 constraints on the order of elaboration that come not from consideration
28070 of avoiding elaboration errors, but rather from extra-lingual logic
28071 requirements. Consider this example:
28072
28073 @smallexample @c ada
28074 with Init_Constants;
28075 package Constants is
28076    X : Integer := 0;
28077    Y : Integer := 0;
28078 end Constants;
28079
28080 package Init_Constants is
28081    procedure P; -- require a body
28082 end Init_Constants;
28083
28084 with Constants;
28085 package body Init_Constants is
28086    procedure P is begin null; end;
28087 begin
28088    Constants.X := 3;
28089    Constants.Y := 4;
28090 end Init_Constants;
28091
28092 with Constants;
28093 package Calc is
28094    Z : Integer := Constants.X + Constants.Y;
28095 end Calc;
28096
28097 with Calc;
28098 with Text_IO; use Text_IO;
28099 procedure Main is
28100 begin
28101    Put_Line (Calc.Z'Img);
28102 end Main;
28103 @end smallexample
28104
28105 @noindent
28106 In this example, there is more than one valid order of elaboration. For
28107 example both the following are correct orders:
28108
28109 @smallexample
28110 Init_Constants spec
28111 Constants spec
28112 Calc spec
28113 Init_Constants body
28114 Main body
28115
28116   and
28117
28118 Init_Constants spec
28119 Init_Constants body
28120 Constants spec
28121 Calc spec
28122 Main body
28123 @end smallexample
28124
28125 @noindent
28126 There is no language rule to prefer one or the other, both are correct
28127 from an order of elaboration point of view. But the programmatic effects
28128 of the two orders are very different. In the first, the elaboration routine
28129 of @code{Calc} initializes @code{Z} to zero, and then the main program
28130 runs with this value of zero. But in the second order, the elaboration
28131 routine of @code{Calc} runs after the body of Init_Constants has set
28132 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
28133 runs.
28134
28135 One could perhaps by applying pretty clever non-artificial intelligence
28136 to the situation guess that it is more likely that the second order of
28137 elaboration is the one desired, but there is no formal linguistic reason
28138 to prefer one over the other. In fact in this particular case, GNAT will
28139 prefer the second order, because of the rule that bodies are elaborated
28140 as soon as possible, but it's just luck that this is what was wanted
28141 (if indeed the second order was preferred).
28142
28143 If the program cares about the order of elaboration routines in a case like
28144 this, it is important to specify the order required. In this particular
28145 case, that could have been achieved by adding to the spec of Calc:
28146
28147 @smallexample @c ada
28148 pragma Elaborate_All (Constants);
28149 @end smallexample
28150
28151 @noindent
28152 which requires that the body (if any) and spec of @code{Constants},
28153 as well as the body and spec of any unit @code{with}'ed by
28154 @code{Constants} be elaborated before @code{Calc} is elaborated.
28155
28156 Clearly no automatic method can always guess which alternative you require,
28157 and if you are working with legacy code that had constraints of this kind
28158 which were not properly specified by adding @code{Elaborate} or
28159 @code{Elaborate_All} pragmas, then indeed it is possible that two different
28160 compilers can choose different orders.
28161
28162 However, GNAT does attempt to diagnose the common situation where there
28163 are uninitialized variables in the visible part of a package spec, and the
28164 corresponding package body has an elaboration block that directly or
28165 indirectly initialized one or more of these variables. This is the situation
28166 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28167 a warning that suggests this addition if it detects this situation.
28168
28169 The @code{gnatbind}
28170 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
28171 out problems. This switch causes bodies to be elaborated as late as possible
28172 instead of as early as possible. In the example above, it would have forced
28173 the choice of the first elaboration order. If you get different results
28174 when using this switch, and particularly if one set of results is right,
28175 and one is wrong as far as you are concerned, it shows that you have some
28176 missing @code{Elaborate} pragmas. For the example above, we have the
28177 following output:
28178
28179 @smallexample
28180 gnatmake -f -q main
28181 main
28182  7
28183 gnatmake -f -q main -bargs -p
28184 main
28185  0
28186 @end smallexample
28187
28188 @noindent
28189 It is of course quite unlikely that both these results are correct, so
28190 it is up to you in a case like this to investigate the source of the
28191 difference, by looking at the two elaboration orders that are chosen,
28192 and figuring out which is correct, and then adding the necessary
28193 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
28194
28195
28196
28197 @c *******************************
28198 @node Conditional Compilation
28199 @appendix Conditional Compilation
28200 @c *******************************
28201 @cindex Conditional compilation
28202
28203 @noindent
28204 It is often necessary to arrange for a single source program
28205 to serve multiple purposes, where it is compiled in different
28206 ways to achieve these different goals. Some examples of the
28207 need for this feature are
28208
28209 @itemize @bullet
28210 @item  Adapting a program to a different hardware environment
28211 @item  Adapting a program to a different target architecture
28212 @item  Turning debugging features on and off
28213 @item  Arranging for a program to compile with different compilers
28214 @end itemize
28215
28216 @noindent
28217 In C, or C++, the typical approach would be to use the preprocessor
28218 that is defined as part of the language. The Ada language does not
28219 contain such a feature. This is not an oversight, but rather a very
28220 deliberate design decision, based on the experience that overuse of
28221 the preprocessing features in C and C++ can result in programs that
28222 are extremely difficult to maintain. For example, if we have ten
28223 switches that can be on or off, this means that there are a thousand
28224 separate programs, any one of which might not even be syntactically
28225 correct, and even if syntactically correct, the resulting program
28226 might not work correctly. Testing all combinations can quickly become
28227 impossible.
28228
28229 Nevertheless, the need to tailor programs certainly exists, and in
28230 this Appendix we will discuss how this can
28231 be achieved using Ada in general, and GNAT in particular.
28232
28233 @menu
28234 * Use of Boolean Constants::
28235 * Debugging - A Special Case::
28236 * Conditionalizing Declarations::
28237 * Use of Alternative Implementations::
28238 * Preprocessing::
28239 @end menu
28240
28241 @node Use of Boolean Constants
28242 @section Use of Boolean Constants
28243
28244 @noindent
28245 In the case where the difference is simply which code
28246 sequence is executed, the cleanest solution is to use Boolean
28247 constants to control which code is executed.
28248
28249 @smallexample @c ada
28250 @group
28251 FP_Initialize_Required : constant Boolean := True;
28252 @dots{}
28253 if FP_Initialize_Required then
28254 @dots{}
28255 end if;
28256 @end group
28257 @end smallexample
28258
28259 @noindent
28260 Not only will the code inside the @code{if} statement not be executed if
28261 the constant Boolean is @code{False}, but it will also be completely
28262 deleted from the program.
28263 However, the code is only deleted after the @code{if} statement
28264 has been checked for syntactic and semantic correctness.
28265 (In contrast, with preprocessors the code is deleted before the
28266 compiler ever gets to see it, so it is not checked until the switch
28267 is turned on.)
28268 @cindex Preprocessors (contrasted with conditional compilation)
28269
28270 Typically the Boolean constants will be in a separate package,
28271 something like:
28272
28273 @smallexample @c ada
28274 @group
28275 package Config is
28276    FP_Initialize_Required : constant Boolean := True;
28277    Reset_Available        : constant Boolean := False;
28278    @dots{}
28279 end Config;
28280 @end group
28281 @end smallexample
28282
28283 @noindent
28284 The @code{Config} package exists in multiple forms for the various targets,
28285 with an appropriate script selecting the version of @code{Config} needed.
28286 Then any other unit requiring conditional compilation can do a @code{with}
28287 of @code{Config} to make the constants visible.
28288
28289
28290 @node Debugging - A Special Case
28291 @section Debugging - A Special Case
28292
28293 @noindent
28294 A common use of conditional code is to execute statements (for example
28295 dynamic checks, or output of intermediate results) under control of a
28296 debug switch, so that the debugging behavior can be turned on and off.
28297 This can be done using a Boolean constant to control whether the code
28298 is active:
28299
28300 @smallexample @c ada
28301 @group
28302 if Debugging then
28303    Put_Line ("got to the first stage!");
28304 end if;
28305 @end group
28306 @end smallexample
28307
28308 @noindent
28309 or
28310
28311 @smallexample @c ada
28312 @group
28313 if Debugging and then Temperature > 999.0 then
28314    raise Temperature_Crazy;
28315 end if;
28316 @end group
28317 @end smallexample
28318
28319 @noindent
28320 Since this is a common case, there are special features to deal with
28321 this in a convenient manner. For the case of tests, Ada 2005 has added
28322 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
28323 @cindex pragma @code{Assert}
28324 on the @code{Assert} pragma that has always been available in GNAT, so this
28325 feature may be used with GNAT even if you are not using Ada 2005 features.
28326 The use of pragma @code{Assert} is described in
28327 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
28328 example, the last test could be written:
28329
28330 @smallexample @c ada
28331 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
28332 @end smallexample
28333
28334 @noindent
28335 or simply
28336
28337 @smallexample @c ada
28338 pragma Assert (Temperature <= 999.0);
28339 @end smallexample
28340
28341 @noindent
28342 In both cases, if assertions are active and the temperature is excessive,
28343 the exception @code{Assert_Failure} will be raised, with the given string in
28344 the first case or a string indicating the location of the pragma in the second
28345 case used as the exception message.
28346
28347 You can turn assertions on and off by using the @code{Assertion_Policy}
28348 pragma.
28349 @cindex pragma @code{Assertion_Policy}
28350 This is an Ada 2005 pragma which is implemented in all modes by
28351 GNAT, but only in the latest versions of GNAT which include Ada 2005
28352 capability. Alternatively, you can use the @option{-gnata} switch
28353 @cindex @option{-gnata} switch
28354 to enable assertions from the command line (this is recognized by all versions
28355 of GNAT).
28356
28357 For the example above with the @code{Put_Line}, the GNAT-specific pragma
28358 @code{Debug} can be used:
28359 @cindex pragma @code{Debug}
28360
28361 @smallexample @c ada
28362 pragma Debug (Put_Line ("got to the first stage!"));
28363 @end smallexample
28364
28365 @noindent
28366 If debug pragmas are enabled, the argument, which must be of the form of
28367 a procedure call, is executed (in this case, @code{Put_Line} will be called).
28368 Only one call can be present, but of course a special debugging procedure
28369 containing any code you like can be included in the program and then
28370 called in a pragma @code{Debug} argument as needed.
28371
28372 One advantage of pragma @code{Debug} over the @code{if Debugging then}
28373 construct is that pragma @code{Debug} can appear in declarative contexts,
28374 such as at the very beginning of a procedure, before local declarations have
28375 been elaborated.
28376
28377 Debug pragmas are enabled using either the @option{-gnata} switch that also
28378 controls assertions, or with a separate Debug_Policy pragma.
28379 @cindex pragma @code{Debug_Policy}
28380 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
28381 in Ada 95 and Ada 83 programs as well), and is analogous to
28382 pragma @code{Assertion_Policy} to control assertions.
28383
28384 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
28385 and thus they can appear in @file{gnat.adc} if you are not using a
28386 project file, or in the file designated to contain configuration pragmas
28387 in a project file.
28388 They then apply to all subsequent compilations. In practice the use of
28389 the @option{-gnata} switch is often the most convenient method of controlling
28390 the status of these pragmas.
28391
28392 Note that a pragma is not a statement, so in contexts where a statement
28393 sequence is required, you can't just write a pragma on its own. You have
28394 to add a @code{null} statement.
28395
28396 @smallexample @c ada
28397 @group
28398 if @dots{} then
28399    @dots{} -- some statements
28400 else
28401    pragma Assert (Num_Cases < 10);
28402    null;
28403 end if;
28404 @end group
28405 @end smallexample
28406
28407
28408 @node Conditionalizing Declarations
28409 @section Conditionalizing Declarations
28410
28411 @noindent
28412 In some cases, it may be necessary to conditionalize declarations to meet
28413 different requirements. For example we might want a bit string whose length
28414 is set to meet some hardware message requirement.
28415
28416 In some cases, it may be possible to do this using declare blocks controlled
28417 by conditional constants:
28418
28419 @smallexample @c ada
28420 @group
28421 if Small_Machine then
28422    declare
28423       X : Bit_String (1 .. 10);
28424    begin
28425       @dots{}
28426    end;
28427 else
28428    declare
28429       X : Large_Bit_String (1 .. 1000);
28430    begin
28431       @dots{}
28432    end;
28433 end if;
28434 @end group
28435 @end smallexample
28436
28437 @noindent
28438 Note that in this approach, both declarations are analyzed by the
28439 compiler so this can only be used where both declarations are legal,
28440 even though one of them will not be used.
28441
28442 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
28443 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
28444 that are parameterized by these constants. For example
28445
28446 @smallexample @c ada
28447 @group
28448 for Rec use
28449   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
28450 end record;
28451 @end group
28452 @end smallexample
28453
28454 @noindent
28455 If @code{Bits_Per_Word} is set to 32, this generates either
28456
28457 @smallexample @c ada
28458 @group
28459 for Rec use
28460   Field1 at 0 range 0 .. 32;
28461 end record;
28462 @end group
28463 @end smallexample
28464
28465 @noindent
28466 for the big endian case, or
28467
28468 @smallexample @c ada
28469 @group
28470 for Rec use record
28471   Field1 at 0 range 10 .. 32;
28472 end record;
28473 @end group
28474 @end smallexample
28475
28476 @noindent
28477 for the little endian case. Since a powerful subset of Ada expression
28478 notation is usable for creating static constants, clever use of this
28479 feature can often solve quite difficult problems in conditionalizing
28480 compilation (note incidentally that in Ada 95, the little endian
28481 constant was introduced as @code{System.Default_Bit_Order}, so you do not
28482 need to define this one yourself).
28483
28484
28485 @node Use of Alternative Implementations
28486 @section Use of Alternative Implementations
28487
28488 @noindent
28489 In some cases, none of the approaches described above are adequate. This
28490 can occur for example if the set of declarations required is radically
28491 different for two different configurations.
28492
28493 In this situation, the official Ada way of dealing with conditionalizing
28494 such code is to write separate units for the different cases. As long as
28495 this does not result in excessive duplication of code, this can be done
28496 without creating maintenance problems. The approach is to share common
28497 code as far as possible, and then isolate the code and declarations
28498 that are different. Subunits are often a convenient method for breaking
28499 out a piece of a unit that is to be conditionalized, with separate files
28500 for different versions of the subunit for different targets, where the
28501 build script selects the right one to give to the compiler.
28502 @cindex Subunits (and conditional compilation)
28503
28504 As an example, consider a situation where a new feature in Ada 2005
28505 allows something to be done in a really nice way. But your code must be able
28506 to compile with an Ada 95 compiler. Conceptually you want to say:
28507
28508 @smallexample @c ada
28509 @group
28510 if Ada_2005 then
28511    @dots{} neat Ada 2005 code
28512 else
28513    @dots{} not quite as neat Ada 95 code
28514 end if;
28515 @end group
28516 @end smallexample
28517
28518 @noindent
28519 where @code{Ada_2005} is a Boolean constant.
28520
28521 But this won't work when @code{Ada_2005} is set to @code{False},
28522 since the @code{then} clause will be illegal for an Ada 95 compiler.
28523 (Recall that although such unreachable code would eventually be deleted
28524 by the compiler, it still needs to be legal.  If it uses features
28525 introduced in Ada 2005, it will be illegal in Ada 95.)
28526
28527 So instead we write
28528
28529 @smallexample @c ada
28530 procedure Insert is separate;
28531 @end smallexample
28532
28533 @noindent
28534 Then we have two files for the subunit @code{Insert}, with the two sets of
28535 code.
28536 If the package containing this is called @code{File_Queries}, then we might
28537 have two files
28538
28539 @itemize @bullet
28540 @item    @file{file_queries-insert-2005.adb}
28541 @item    @file{file_queries-insert-95.adb}
28542 @end itemize
28543
28544 @noindent
28545 and the build script renames the appropriate file to
28546
28547 @smallexample
28548 file_queries-insert.adb
28549 @end smallexample
28550
28551 @noindent
28552 and then carries out the compilation.
28553
28554 This can also be done with project files' naming schemes. For example:
28555
28556 @smallexample @c project
28557 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
28558 @end smallexample
28559
28560 @noindent
28561 Note also that with project files it is desirable to use a different extension
28562 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
28563 conflict may arise through another commonly used feature: to declare as part
28564 of the project a set of directories containing all the sources obeying the
28565 default naming scheme.
28566
28567 The use of alternative units is certainly feasible in all situations,
28568 and for example the Ada part of the GNAT run-time is conditionalized
28569 based on the target architecture using this approach. As a specific example,
28570 consider the implementation of the AST feature in VMS. There is one
28571 spec:
28572
28573 @smallexample
28574 s-asthan.ads
28575 @end smallexample
28576
28577 @noindent
28578 which is the same for all architectures, and three bodies:
28579
28580 @table @file
28581 @item    s-asthan.adb
28582 used for all non-VMS operating systems
28583 @item    s-asthan-vms-alpha.adb
28584 used for VMS on the Alpha
28585 @item    s-asthan-vms-ia64.adb
28586 used for VMS on the ia64
28587 @end table
28588
28589 @noindent
28590 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28591 this operating system feature is not available, and the two remaining
28592 versions interface with the corresponding versions of VMS to provide
28593 VMS-compatible AST handling. The GNAT build script knows the architecture
28594 and operating system, and automatically selects the right version,
28595 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28596
28597 Another style for arranging alternative implementations is through Ada's
28598 access-to-subprogram facility.
28599 In case some functionality is to be conditionally included,
28600 you can declare an access-to-procedure variable @code{Ref} that is initialized
28601 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28602 when appropriate.
28603 In some library package, set @code{Ref} to @code{Proc'Access} for some
28604 procedure @code{Proc} that performs the relevant processing.
28605 The initialization only occurs if the library package is included in the
28606 program.
28607 The same idea can also be implemented using tagged types and dispatching
28608 calls.
28609
28610
28611 @node Preprocessing
28612 @section Preprocessing
28613 @cindex Preprocessing
28614
28615 @noindent
28616 Although it is quite possible to conditionalize code without the use of
28617 C-style preprocessing, as described earlier in this section, it is
28618 nevertheless convenient in some cases to use the C approach. Moreover,
28619 older Ada compilers have often provided some preprocessing capability,
28620 so legacy code may depend on this approach, even though it is not
28621 standard.
28622
28623 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28624 extent on the various preprocessors that have been used
28625 with legacy code on other compilers, to enable easier transition).
28626
28627 The preprocessor may be used in two separate modes. It can be used quite
28628 separately from the compiler, to generate a separate output source file
28629 that is then fed to the compiler as a separate step. This is the
28630 @code{gnatprep} utility, whose use is fully described in
28631 @ref{Preprocessing Using gnatprep}.
28632 @cindex @code{gnatprep}
28633
28634 The preprocessing language allows such constructs as
28635
28636 @smallexample
28637 @group
28638 #if DEBUG or PRIORITY > 4 then
28639    bunch of declarations
28640 #else
28641    completely different bunch of declarations
28642 #end if;
28643 @end group
28644 @end smallexample
28645
28646 @noindent
28647 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28648 defined either on the command line or in a separate file.
28649
28650 The other way of running the preprocessor is even closer to the C style and
28651 often more convenient. In this approach the preprocessing is integrated into
28652 the compilation process. The compiler is fed the preprocessor input which
28653 includes @code{#if} lines etc, and then the compiler carries out the
28654 preprocessing internally and processes the resulting output.
28655 For more details on this approach, see @ref{Integrated Preprocessing}.
28656
28657
28658 @c *******************************
28659 @node Inline Assembler
28660 @appendix Inline Assembler
28661 @c *******************************
28662
28663 @noindent
28664 If you need to write low-level software that interacts directly
28665 with the hardware, Ada provides two ways to incorporate assembly
28666 language code into your program.  First, you can import and invoke
28667 external routines written in assembly language, an Ada feature fully
28668 supported by GNAT@.  However, for small sections of code it may be simpler
28669 or more efficient to include assembly language statements directly
28670 in your Ada source program, using the facilities of the implementation-defined
28671 package @code{System.Machine_Code}, which incorporates the gcc
28672 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28673 including the following:
28674
28675 @itemize @bullet
28676 @item No need to use non-Ada tools
28677 @item Consistent interface over different targets
28678 @item Automatic usage of the proper calling conventions
28679 @item Access to Ada constants and variables
28680 @item Definition of intrinsic routines
28681 @item Possibility of inlining a subprogram comprising assembler code
28682 @item Code optimizer can take Inline Assembler code into account
28683 @end itemize
28684
28685 This chapter presents a series of examples to show you how to use
28686 the Inline Assembler.  Although it focuses on the Intel x86,
28687 the general approach applies also to other processors.
28688 It is assumed that you are familiar with Ada
28689 and with assembly language programming.
28690
28691 @menu
28692 * Basic Assembler Syntax::
28693 * A Simple Example of Inline Assembler::
28694 * Output Variables in Inline Assembler::
28695 * Input Variables in Inline Assembler::
28696 * Inlining Inline Assembler Code::
28697 * Other Asm Functionality::
28698 @end menu
28699
28700 @c ---------------------------------------------------------------------------
28701 @node Basic Assembler Syntax
28702 @section Basic Assembler Syntax
28703
28704 @noindent
28705 The assembler used by GNAT and gcc is based not on the Intel assembly
28706 language, but rather on a language that descends from the AT&T Unix
28707 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28708 The following table summarizes the main features of @emph{as} syntax
28709 and points out the differences from the Intel conventions.
28710 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28711 pre-processor) documentation for further information.
28712
28713 @table @asis
28714 @item Register names
28715 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28716 @*
28717 Intel: No extra punctuation; for example @code{eax}
28718
28719 @item Immediate operand
28720 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28721 @*
28722 Intel: No extra punctuation; for example @code{4}
28723
28724 @item Address
28725 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28726 @*
28727 Intel: No extra punctuation; for example @code{loc}
28728
28729 @item Memory contents
28730 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28731 @*
28732 Intel: Square brackets; for example @code{[loc]}
28733
28734 @item Register contents
28735 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28736 @*
28737 Intel: Square brackets; for example @code{[eax]}
28738
28739 @item Hexadecimal numbers
28740 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28741 @*
28742 Intel: Trailing ``h''; for example @code{A0h}
28743
28744 @item Operand size
28745 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28746 a 16-bit word
28747 @*
28748 Intel: Implicit, deduced by assembler; for example @code{mov}
28749
28750 @item Instruction repetition
28751 gcc / @emph{as}: Split into two lines; for example
28752 @*
28753 @code{rep}
28754 @*
28755 @code{stosl}
28756 @*
28757 Intel: Keep on one line; for example @code{rep stosl}
28758
28759 @item Order of operands
28760 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28761 @*
28762 Intel: Destination first; for example @code{mov eax, 4}
28763 @end table
28764
28765 @c ---------------------------------------------------------------------------
28766 @node A Simple Example of Inline Assembler
28767 @section A Simple Example of Inline Assembler
28768
28769 @noindent
28770 The following example will generate a single assembly language statement,
28771 @code{nop}, which does nothing.  Despite its lack of run-time effect,
28772 the example will be useful in illustrating the basics of
28773 the Inline Assembler facility.
28774
28775 @smallexample @c ada
28776 @group
28777 with System.Machine_Code; use System.Machine_Code;
28778 procedure Nothing is
28779 begin
28780    Asm ("nop");
28781 end Nothing;
28782 @end group
28783 @end smallexample
28784
28785 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28786 here it takes one parameter, a @emph{template string} that must be a static
28787 expression and that will form the generated instruction.
28788 @code{Asm} may be regarded as a compile-time procedure that parses
28789 the template string and additional parameters (none here),
28790 from which it generates a sequence of assembly language instructions.
28791
28792 The examples in this chapter will illustrate several of the forms
28793 for invoking @code{Asm}; a complete specification of the syntax
28794 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
28795 Manual}.
28796
28797 Under the standard GNAT conventions, the @code{Nothing} procedure
28798 should be in a file named @file{nothing.adb}.
28799 You can build the executable in the usual way:
28800 @smallexample
28801 gnatmake nothing
28802 @end smallexample
28803 However, the interesting aspect of this example is not its run-time behavior
28804 but rather the generated assembly code.
28805 To see this output, invoke the compiler as follows:
28806 @smallexample
28807    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28808 @end smallexample
28809 where the options are:
28810
28811 @table @code
28812 @item -c
28813 compile only (no bind or link)
28814 @item -S
28815 generate assembler listing
28816 @item -fomit-frame-pointer
28817 do not set up separate stack frames
28818 @item -gnatp
28819 do not add runtime checks
28820 @end table
28821
28822 This gives a human-readable assembler version of the code. The resulting
28823 file will have the same name as the Ada source file, but with a @code{.s}
28824 extension. In our example, the file @file{nothing.s} has the following
28825 contents:
28826
28827 @smallexample
28828 @group
28829 .file "nothing.adb"
28830 gcc2_compiled.:
28831 ___gnu_compiled_ada:
28832 .text
28833    .align 4
28834 .globl __ada_nothing
28835 __ada_nothing:
28836 #APP
28837    nop
28838 #NO_APP
28839    jmp L1
28840    .align 2,0x90
28841 L1:
28842    ret
28843 @end group
28844 @end smallexample
28845
28846 The assembly code you included is clearly indicated by
28847 the compiler, between the @code{#APP} and @code{#NO_APP}
28848 delimiters. The character before the 'APP' and 'NOAPP'
28849 can differ on different targets. For example, GNU/Linux uses '#APP' while
28850 on NT you will see '/APP'.
28851
28852 If you make a mistake in your assembler code (such as using the
28853 wrong size modifier, or using a wrong operand for the instruction) GNAT
28854 will report this error in a temporary file, which will be deleted when
28855 the compilation is finished.  Generating an assembler file will help
28856 in such cases, since you can assemble this file separately using the
28857 @emph{as} assembler that comes with gcc.
28858
28859 Assembling the file using the command
28860
28861 @smallexample
28862 as @file{nothing.s}
28863 @end smallexample
28864 @noindent
28865 will give you error messages whose lines correspond to the assembler
28866 input file, so you can easily find and correct any mistakes you made.
28867 If there are no errors, @emph{as} will generate an object file
28868 @file{nothing.out}.
28869
28870 @c ---------------------------------------------------------------------------
28871 @node Output Variables in Inline Assembler
28872 @section Output Variables in Inline Assembler
28873
28874 @noindent
28875 The examples in this section, showing how to access the processor flags,
28876 illustrate how to specify the destination operands for assembly language
28877 statements.
28878
28879 @smallexample @c ada
28880 @group
28881 with Interfaces; use Interfaces;
28882 with Ada.Text_IO; use Ada.Text_IO;
28883 with System.Machine_Code; use System.Machine_Code;
28884 procedure Get_Flags is
28885    Flags : Unsigned_32;
28886    use ASCII;
28887 begin
28888    Asm ("pushfl"          & LF & HT & -- push flags on stack
28889         "popl %%eax"      & LF & HT & -- load eax with flags
28890         "movl %%eax, %0",             -- store flags in variable
28891         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28892    Put_Line ("Flags register:" & Flags'Img);
28893 end Get_Flags;
28894 @end group
28895 @end smallexample
28896
28897 In order to have a nicely aligned assembly listing, we have separated
28898 multiple assembler statements in the Asm template string with linefeed
28899 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28900 The resulting section of the assembly output file is:
28901
28902 @smallexample
28903 @group
28904 #APP
28905    pushfl
28906    popl %eax
28907    movl %eax, -40(%ebp)
28908 #NO_APP
28909 @end group
28910 @end smallexample
28911
28912 It would have been legal to write the Asm invocation as:
28913
28914 @smallexample
28915 Asm ("pushfl popl %%eax movl %%eax, %0")
28916 @end smallexample
28917
28918 but in the generated assembler file, this would come out as:
28919
28920 @smallexample
28921 #APP
28922    pushfl popl %eax movl %eax, -40(%ebp)
28923 #NO_APP
28924 @end smallexample
28925
28926 which is not so convenient for the human reader.
28927
28928 We use Ada comments
28929 at the end of each line to explain what the assembler instructions
28930 actually do.  This is a useful convention.
28931
28932 When writing Inline Assembler instructions, you need to precede each register
28933 and variable name with a percent sign.  Since the assembler already requires
28934 a percent sign at the beginning of a register name, you need two consecutive
28935 percent signs for such names in the Asm template string, thus @code{%%eax}.
28936 In the generated assembly code, one of the percent signs will be stripped off.
28937
28938 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28939 variables: operands you later define using @code{Input} or @code{Output}
28940 parameters to @code{Asm}.
28941 An output variable is illustrated in
28942 the third statement in the Asm template string:
28943 @smallexample
28944 movl %%eax, %0
28945 @end smallexample
28946 The intent is to store the contents of the eax register in a variable that can
28947 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28948 necessarily work, since the compiler might optimize by using a register
28949 to hold Flags, and the expansion of the @code{movl} instruction would not be
28950 aware of this optimization.  The solution is not to store the result directly
28951 but rather to advise the compiler to choose the correct operand form;
28952 that is the purpose of the @code{%0} output variable.
28953
28954 Information about the output variable is supplied in the @code{Outputs}
28955 parameter to @code{Asm}:
28956 @smallexample
28957 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28958 @end smallexample
28959
28960 The output is defined by the @code{Asm_Output} attribute of the target type;
28961 the general format is
28962 @smallexample
28963 Type'Asm_Output (constraint_string, variable_name)
28964 @end smallexample
28965
28966 The constraint string directs the compiler how
28967 to store/access the associated variable.  In the example
28968 @smallexample
28969 Unsigned_32'Asm_Output ("=m", Flags);
28970 @end smallexample
28971 the @code{"m"} (memory) constraint tells the compiler that the variable
28972 @code{Flags} should be stored in a memory variable, thus preventing
28973 the optimizer from keeping it in a register.  In contrast,
28974 @smallexample
28975 Unsigned_32'Asm_Output ("=r", Flags);
28976 @end smallexample
28977 uses the @code{"r"} (register) constraint, telling the compiler to
28978 store the variable in a register.
28979
28980 If the constraint is preceded by the equal character (@strong{=}), it tells
28981 the compiler that the variable will be used to store data into it.
28982
28983 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28984 allowing the optimizer to choose whatever it deems best.
28985
28986 There are a fairly large number of constraints, but the ones that are
28987 most useful (for the Intel x86 processor) are the following:
28988
28989 @table @code
28990 @item =
28991 output constraint
28992 @item g
28993 global (i.e.@: can be stored anywhere)
28994 @item m
28995 in memory
28996 @item I
28997 a constant
28998 @item a
28999 use eax
29000 @item b
29001 use ebx
29002 @item c
29003 use ecx
29004 @item d
29005 use edx
29006 @item S
29007 use esi
29008 @item D
29009 use edi
29010 @item r
29011 use one of eax, ebx, ecx or edx
29012 @item q
29013 use one of eax, ebx, ecx, edx, esi or edi
29014 @end table
29015
29016 The full set of constraints is described in the gcc and @emph{as}
29017 documentation; note that it is possible to combine certain constraints
29018 in one constraint string.
29019
29020 You specify the association of an output variable with an assembler operand
29021 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29022 integer.  Thus in
29023 @smallexample @c ada
29024 @group
29025 Asm ("pushfl"          & LF & HT & -- push flags on stack
29026      "popl %%eax"      & LF & HT & -- load eax with flags
29027      "movl %%eax, %0",             -- store flags in variable
29028      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29029 @end group
29030 @end smallexample
29031 @noindent
29032 @code{%0} will be replaced in the expanded code by the appropriate operand,
29033 whatever
29034 the compiler decided for the @code{Flags} variable.
29035
29036 In general, you may have any number of output variables:
29037 @itemize @bullet
29038 @item
29039 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29040 @item
29041 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29042 of @code{Asm_Output} attributes
29043 @end itemize
29044
29045 For example:
29046 @smallexample @c ada
29047 @group
29048 Asm ("movl %%eax, %0" & LF & HT &
29049      "movl %%ebx, %1" & LF & HT &
29050      "movl %%ecx, %2",
29051      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29052                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29053                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29054 @end group
29055 @end smallexample
29056 @noindent
29057 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29058 in the Ada program.
29059
29060 As a variation on the @code{Get_Flags} example, we can use the constraints
29061 string to direct the compiler to store the eax register into the @code{Flags}
29062 variable, instead of including the store instruction explicitly in the
29063 @code{Asm} template string:
29064
29065 @smallexample @c ada
29066 @group
29067 with Interfaces; use Interfaces;
29068 with Ada.Text_IO; use Ada.Text_IO;
29069 with System.Machine_Code; use System.Machine_Code;
29070 procedure Get_Flags_2 is
29071    Flags : Unsigned_32;
29072    use ASCII;
29073 begin
29074    Asm ("pushfl"      & LF & HT & -- push flags on stack
29075         "popl %%eax",             -- save flags in eax
29076         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29077    Put_Line ("Flags register:" & Flags'Img);
29078 end Get_Flags_2;
29079 @end group
29080 @end smallexample
29081
29082 @noindent
29083 The @code{"a"} constraint tells the compiler that the @code{Flags}
29084 variable will come from the eax register. Here is the resulting code:
29085
29086 @smallexample
29087 @group
29088 #APP
29089    pushfl
29090    popl %eax
29091 #NO_APP
29092    movl %eax,-40(%ebp)
29093 @end group
29094 @end smallexample
29095
29096 @noindent
29097 The compiler generated the store of eax into Flags after
29098 expanding the assembler code.
29099
29100 Actually, there was no need to pop the flags into the eax register;
29101 more simply, we could just pop the flags directly into the program variable:
29102
29103 @smallexample @c ada
29104 @group
29105 with Interfaces; use Interfaces;
29106 with Ada.Text_IO; use Ada.Text_IO;
29107 with System.Machine_Code; use System.Machine_Code;
29108 procedure Get_Flags_3 is
29109    Flags : Unsigned_32;
29110    use ASCII;
29111 begin
29112    Asm ("pushfl"  & LF & HT & -- push flags on stack
29113         "pop %0",             -- save flags in Flags
29114         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29115    Put_Line ("Flags register:" & Flags'Img);
29116 end Get_Flags_3;
29117 @end group
29118 @end smallexample
29119
29120 @c ---------------------------------------------------------------------------
29121 @node Input Variables in Inline Assembler
29122 @section Input Variables in Inline Assembler
29123
29124 @noindent
29125 The example in this section illustrates how to specify the source operands
29126 for assembly language statements.
29127 The program simply increments its input value by 1:
29128
29129 @smallexample @c ada
29130 @group
29131 with Interfaces; use Interfaces;
29132 with Ada.Text_IO; use Ada.Text_IO;
29133 with System.Machine_Code; use System.Machine_Code;
29134 procedure Increment is
29135
29136    function Incr (Value : Unsigned_32) return Unsigned_32 is
29137       Result : Unsigned_32;
29138    begin
29139       Asm ("incl %0",
29140            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29141            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29142       return Result;
29143    end Incr;
29144
29145    Value : Unsigned_32;
29146
29147 begin
29148    Value := 5;
29149    Put_Line ("Value before is" & Value'Img);
29150    Value := Incr (Value);
29151    Put_Line ("Value after is" & Value'Img);
29152 end Increment;
29153 @end group
29154 @end smallexample
29155
29156 The @code{Outputs} parameter to @code{Asm} specifies
29157 that the result will be in the eax register and that it is to be stored
29158 in the @code{Result} variable.
29159
29160 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29161 but with an @code{Asm_Input} attribute.
29162 The @code{"="} constraint, indicating an output value, is not present.
29163
29164 You can have multiple input variables, in the same way that you can have more
29165 than one output variable.
29166
29167 The parameter count (%0, %1) etc, now starts at the first input
29168 statement, and continues with the output statements.
29169 When both parameters use the same variable, the
29170 compiler will treat them as the same %n operand, which is the case here.
29171
29172 Just as the @code{Outputs} parameter causes the register to be stored into the
29173 target variable after execution of the assembler statements, so does the
29174 @code{Inputs} parameter cause its variable to be loaded into the register
29175 before execution of the assembler statements.
29176
29177 Thus the effect of the @code{Asm} invocation is:
29178 @enumerate
29179 @item load the 32-bit value of @code{Value} into eax
29180 @item execute the @code{incl %eax} instruction
29181 @item store the contents of eax into the @code{Result} variable
29182 @end enumerate
29183
29184 The resulting assembler file (with @option{-O2} optimization) contains:
29185 @smallexample
29186 @group
29187 _increment__incr.1:
29188    subl $4,%esp
29189    movl 8(%esp),%eax
29190 #APP
29191    incl %eax
29192 #NO_APP
29193    movl %eax,%edx
29194    movl %ecx,(%esp)
29195    addl $4,%esp
29196    ret
29197 @end group
29198 @end smallexample
29199
29200 @c ---------------------------------------------------------------------------
29201 @node Inlining Inline Assembler Code
29202 @section Inlining Inline Assembler Code
29203
29204 @noindent
29205 For a short subprogram such as the @code{Incr} function in the previous
29206 section, the overhead of the call and return (creating / deleting the stack
29207 frame) can be significant, compared to the amount of code in the subprogram
29208 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29209 which directs the compiler to expand invocations of the subprogram at the
29210 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29211 Here is the resulting program:
29212
29213 @smallexample @c ada
29214 @group
29215 with Interfaces; use Interfaces;
29216 with Ada.Text_IO; use Ada.Text_IO;
29217 with System.Machine_Code; use System.Machine_Code;
29218 procedure Increment_2 is
29219
29220    function Incr (Value : Unsigned_32) return Unsigned_32 is
29221       Result : Unsigned_32;
29222    begin
29223       Asm ("incl %0",
29224            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29225            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29226       return Result;
29227    end Incr;
29228    pragma Inline (Increment);
29229
29230    Value : Unsigned_32;
29231
29232 begin
29233    Value := 5;
29234    Put_Line ("Value before is" & Value'Img);
29235    Value := Increment (Value);
29236    Put_Line ("Value after is" & Value'Img);
29237 end Increment_2;
29238 @end group
29239 @end smallexample
29240
29241 Compile the program with both optimization (@option{-O2}) and inlining
29242 (@option{-gnatn}) enabled.
29243
29244 The @code{Incr} function is still compiled as usual, but at the
29245 point in @code{Increment} where our function used to be called:
29246
29247 @smallexample
29248 @group
29249 pushl %edi
29250 call _increment__incr.1
29251 @end group
29252 @end smallexample
29253
29254 @noindent
29255 the code for the function body directly appears:
29256
29257 @smallexample
29258 @group
29259 movl %esi,%eax
29260 #APP
29261    incl %eax
29262 #NO_APP
29263    movl %eax,%edx
29264 @end group
29265 @end smallexample
29266
29267 @noindent
29268 thus saving the overhead of stack frame setup and an out-of-line call.
29269
29270 @c ---------------------------------------------------------------------------
29271 @node Other Asm Functionality
29272 @section Other @code{Asm} Functionality
29273
29274 @noindent
29275 This section describes two important parameters to the @code{Asm}
29276 procedure: @code{Clobber}, which identifies register usage;
29277 and @code{Volatile}, which inhibits unwanted optimizations.
29278
29279 @menu
29280 * The Clobber Parameter::
29281 * The Volatile Parameter::
29282 @end menu
29283
29284 @c ---------------------------------------------------------------------------
29285 @node The Clobber Parameter
29286 @subsection The @code{Clobber} Parameter
29287
29288 @noindent
29289 One of the dangers of intermixing assembly language and a compiled language
29290 such as Ada is that the compiler needs to be aware of which registers are
29291 being used by the assembly code.  In some cases, such as the earlier examples,
29292 the constraint string is sufficient to indicate register usage (e.g.,
29293 @code{"a"} for
29294 the eax register).  But more generally, the compiler needs an explicit
29295 identification of the registers that are used by the Inline Assembly
29296 statements.
29297
29298 Using a register that the compiler doesn't know about
29299 could be a side effect of an instruction (like @code{mull}
29300 storing its result in both eax and edx).
29301 It can also arise from explicit register usage in your
29302 assembly code; for example:
29303 @smallexample
29304 @group
29305 Asm ("movl %0, %%ebx" & LF & HT &
29306      "movl %%ebx, %1",
29307      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29308      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
29309 @end group
29310 @end smallexample
29311 @noindent
29312 where the compiler (since it does not analyze the @code{Asm} template string)
29313 does not know you are using the ebx register.
29314
29315 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29316 to identify the registers that will be used by your assembly code:
29317
29318 @smallexample
29319 @group
29320 Asm ("movl %0, %%ebx" & LF & HT &
29321      "movl %%ebx, %1",
29322      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29323      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29324      Clobber => "ebx");
29325 @end group
29326 @end smallexample
29327
29328 The Clobber parameter is a static string expression specifying the
29329 register(s) you are using.  Note that register names are @emph{not} prefixed
29330 by a percent sign. Also, if more than one register is used then their names
29331 are separated by commas; e.g., @code{"eax, ebx"}
29332
29333 The @code{Clobber} parameter has several additional uses:
29334 @enumerate
29335 @item Use ``register'' name @code{cc} to indicate that flags might have changed
29336 @item Use ``register'' name @code{memory} if you changed a memory location
29337 @end enumerate
29338
29339 @c ---------------------------------------------------------------------------
29340 @node The Volatile Parameter
29341 @subsection The @code{Volatile} Parameter
29342 @cindex Volatile parameter
29343
29344 @noindent
29345 Compiler optimizations in the presence of Inline Assembler may sometimes have
29346 unwanted effects.  For example, when an @code{Asm} invocation with an input
29347 variable is inside a loop, the compiler might move the loading of the input
29348 variable outside the loop, regarding it as a one-time initialization.
29349
29350 If this effect is not desired, you can disable such optimizations by setting
29351 the @code{Volatile} parameter to @code{True}; for example:
29352
29353 @smallexample @c ada
29354 @group
29355 Asm ("movl %0, %%ebx" & LF & HT &
29356      "movl %%ebx, %1",
29357      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29358      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29359      Clobber  => "ebx",
29360      Volatile => True);
29361 @end group
29362 @end smallexample
29363
29364 By default, @code{Volatile} is set to @code{False} unless there is no
29365 @code{Outputs} parameter.
29366
29367 Although setting @code{Volatile} to @code{True} prevents unwanted
29368 optimizations, it will also disable other optimizations that might be
29369 important for efficiency. In general, you should set @code{Volatile}
29370 to @code{True} only if the compiler's optimizations have created
29371 problems.
29372 @c END OF INLINE ASSEMBLER CHAPTER
29373 @c ===============================
29374
29375 @c ***********************************
29376 @c * Compatibility and Porting Guide *
29377 @c ***********************************
29378 @node Compatibility and Porting Guide
29379 @appendix Compatibility and Porting Guide
29380
29381 @noindent
29382 This chapter describes the compatibility issues that may arise between
29383 GNAT and other Ada compilation systems (including those for Ada 83),
29384 and shows how GNAT can expedite porting
29385 applications developed in other Ada environments.
29386
29387 @menu
29388 * Compatibility with Ada 83::
29389 * Compatibility between Ada 95 and Ada 2005::
29390 * Implementation-dependent characteristics::
29391 * Compatibility with Other Ada Systems::
29392 * Representation Clauses::
29393 @ifclear vms
29394 @c Brief section is only in non-VMS version
29395 @c Full chapter is in VMS version
29396 * Compatibility with HP Ada 83::
29397 @end ifclear
29398 @ifset vms
29399 * Transitioning to 64-Bit GNAT for OpenVMS::
29400 @end ifset
29401 @end menu
29402
29403 @node Compatibility with Ada 83
29404 @section Compatibility with Ada 83
29405 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
29406
29407 @noindent
29408 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
29409 particular, the design intention was that the difficulties associated
29410 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
29411 that occur when moving from one Ada 83 system to another.
29412
29413 However, there are a number of points at which there are minor
29414 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
29415 full details of these issues,
29416 and should be consulted for a complete treatment.
29417 In practice the
29418 following subsections treat the most likely issues to be encountered.
29419
29420 @menu
29421 * Legal Ada 83 programs that are illegal in Ada 95::
29422 * More deterministic semantics::
29423 * Changed semantics::
29424 * Other language compatibility issues::
29425 @end menu
29426
29427 @node Legal Ada 83 programs that are illegal in Ada 95
29428 @subsection Legal Ada 83 programs that are illegal in Ada 95
29429
29430 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
29431 Ada 95 and thus also in Ada 2005:
29432
29433 @table @emph
29434 @item Character literals
29435 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
29436 @code{Wide_Character} as a new predefined character type, some uses of
29437 character literals that were legal in Ada 83 are illegal in Ada 95.
29438 For example:
29439 @smallexample @c ada
29440    for Char in 'A' .. 'Z' loop @dots{} end loop;
29441 @end smallexample
29442
29443 @noindent
29444 The problem is that @code{'A'} and @code{'Z'} could be from either
29445 @code{Character} or @code{Wide_Character}.  The simplest correction
29446 is to make the type explicit; e.g.:
29447 @smallexample @c ada
29448    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
29449 @end smallexample
29450
29451 @item New reserved words
29452 The identifiers @code{abstract}, @code{aliased}, @code{protected},
29453 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
29454 Existing Ada 83 code using any of these identifiers must be edited to
29455 use some alternative name.
29456
29457 @item Freezing rules
29458 The rules in Ada 95 are slightly different with regard to the point at
29459 which entities are frozen, and representation pragmas and clauses are
29460 not permitted past the freeze point.  This shows up most typically in
29461 the form of an error message complaining that a representation item
29462 appears too late, and the appropriate corrective action is to move
29463 the item nearer to the declaration of the entity to which it refers.
29464
29465 A particular case is that representation pragmas
29466 @ifset vms
29467 (including the
29468 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
29469 @end ifset
29470 cannot be applied to a subprogram body.  If necessary, a separate subprogram
29471 declaration must be introduced to which the pragma can be applied.
29472
29473 @item Optional bodies for library packages
29474 In Ada 83, a package that did not require a package body was nevertheless
29475 allowed to have one.  This lead to certain surprises in compiling large
29476 systems (situations in which the body could be unexpectedly ignored by the
29477 binder).  In Ada 95, if a package does not require a body then it is not
29478 permitted to have a body.  To fix this problem, simply remove a redundant
29479 body if it is empty, or, if it is non-empty, introduce a dummy declaration
29480 into the spec that makes the body required.  One approach is to add a private
29481 part to the package declaration (if necessary), and define a parameterless
29482 procedure called @code{Requires_Body}, which must then be given a dummy
29483 procedure body in the package body, which then becomes required.
29484 Another approach (assuming that this does not introduce elaboration
29485 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
29486 since one effect of this pragma is to require the presence of a package body.
29487
29488 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
29489 In Ada 95, the exception @code{Numeric_Error} is a renaming of
29490 @code{Constraint_Error}.
29491 This means that it is illegal to have separate exception handlers for
29492 the two exceptions.  The fix is simply to remove the handler for the
29493 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
29494 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
29495
29496 @item Indefinite subtypes in generics
29497 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
29498 as the actual for a generic formal private type, but then the instantiation
29499 would be illegal if there were any instances of declarations of variables
29500 of this type in the generic body.  In Ada 95, to avoid this clear violation
29501 of the methodological principle known as the ``contract model'',
29502 the generic declaration explicitly indicates whether
29503 or not such instantiations are permitted.  If a generic formal parameter
29504 has explicit unknown discriminants, indicated by using @code{(<>)} after the
29505 type name, then it can be instantiated with indefinite types, but no
29506 stand-alone variables can be declared of this type.  Any attempt to declare
29507 such a variable will result in an illegality at the time the generic is
29508 declared.  If the @code{(<>)} notation is not used, then it is illegal
29509 to instantiate the generic with an indefinite type.
29510 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
29511 It will show up as a compile time error, and
29512 the fix is usually simply to add the @code{(<>)} to the generic declaration.
29513 @end table
29514
29515 @node More deterministic semantics
29516 @subsection More deterministic semantics
29517
29518 @table @emph
29519 @item Conversions
29520 Conversions from real types to integer types round away from 0.  In Ada 83
29521 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
29522 implementation freedom was intended to support unbiased rounding in
29523 statistical applications, but in practice it interfered with portability.
29524 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
29525 is required.  Numeric code may be affected by this change in semantics.
29526 Note, though, that this issue is no worse than already existed in Ada 83
29527 when porting code from one vendor to another.
29528
29529 @item Tasking
29530 The Real-Time Annex introduces a set of policies that define the behavior of
29531 features that were implementation dependent in Ada 83, such as the order in
29532 which open select branches are executed.
29533 @end table
29534
29535 @node Changed semantics
29536 @subsection Changed semantics
29537
29538 @noindent
29539 The worst kind of incompatibility is one where a program that is legal in
29540 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
29541 possible in Ada 83.  Fortunately this is extremely rare, but the one
29542 situation that you should be alert to is the change in the predefined type
29543 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
29544
29545 @table @emph
29546 @item Range of type @code{Character}
29547 The range of @code{Standard.Character} is now the full 256 characters
29548 of Latin-1, whereas in most Ada 83 implementations it was restricted
29549 to 128 characters. Although some of the effects of
29550 this change will be manifest in compile-time rejection of legal
29551 Ada 83 programs it is possible for a working Ada 83 program to have
29552 a different effect in Ada 95, one that was not permitted in Ada 83.
29553 As an example, the expression
29554 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
29555 delivers @code{255} as its value.
29556 In general, you should look at the logic of any
29557 character-processing Ada 83 program and see whether it needs to be adapted
29558 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
29559 character handling package that may be relevant if code needs to be adapted
29560 to account for the additional Latin-1 elements.
29561 The desirable fix is to
29562 modify the program to accommodate the full character set, but in some cases
29563 it may be convenient to define a subtype or derived type of Character that
29564 covers only the restricted range.
29565 @cindex Latin-1
29566 @end table
29567
29568 @node Other language compatibility issues
29569 @subsection Other language compatibility issues
29570
29571 @table @emph
29572 @item @option{-gnat83} switch
29573 All implementations of GNAT provide a switch that causes GNAT to operate
29574 in Ada 83 mode.  In this mode, some but not all compatibility problems
29575 of the type described above are handled automatically.  For example, the
29576 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
29577 as identifiers as in Ada 83.
29578 However,
29579 in practice, it is usually advisable to make the necessary modifications
29580 to the program to remove the need for using this switch.
29581 See @ref{Compiling Different Versions of Ada}.
29582
29583 @item Support for removed Ada 83 pragmas and attributes
29584 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
29585 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
29586 compilers are allowed, but not required, to implement these missing
29587 elements.  In contrast with some other compilers, GNAT implements all
29588 such pragmas and attributes, eliminating this compatibility concern.  These
29589 include @code{pragma Interface} and the floating point type attributes
29590 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29591 @end table
29592
29593
29594 @node Compatibility between Ada 95 and Ada 2005
29595 @section Compatibility between Ada 95 and Ada 2005
29596 @cindex Compatibility between Ada 95 and Ada 2005
29597
29598 @noindent
29599 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29600 a number of incompatibilities. Several are enumerated below;
29601 for a complete description please see the
29602 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29603 @cite{Rationale for Ada 2005}.
29604
29605 @table @emph
29606 @item New reserved words.
29607 The words @code{interface}, @code{overriding} and @code{synchronized} are
29608 reserved in Ada 2005.
29609 A pre-Ada 2005 program that uses any of these as an identifier will be
29610 illegal.
29611
29612 @item New declarations in predefined packages.
29613 A number of packages in the predefined environment contain new declarations:
29614 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29615 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29616 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29617 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29618 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29619 If an Ada 95 program does a @code{with} and @code{use} of any of these
29620 packages, the new declarations may cause name clashes.
29621
29622 @item Access parameters.
29623 A nondispatching subprogram with an access parameter cannot be renamed
29624 as a dispatching operation.  This was permitted in Ada 95.
29625
29626 @item Access types, discriminants, and constraints.
29627 Rule changes in this area have led to some incompatibilities; for example,
29628 constrained subtypes of some access types are not permitted in Ada 2005.
29629
29630 @item Aggregates for limited types.
29631 The allowance of aggregates for limited types in Ada 2005 raises the
29632 possibility of ambiguities in legal Ada 95 programs, since additional types
29633 now need to be considered in expression resolution.
29634
29635 @item Fixed-point multiplication and division.
29636 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29637 were legal in Ada 95 and invoked the predefined versions of these operations,
29638 are now ambiguous.
29639 The ambiguity may be resolved either by applying a type conversion to the
29640 expression, or by explicitly invoking the operation from package
29641 @code{Standard}.
29642
29643 @item Return-by-reference types.
29644 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
29645 can declare a function returning a value from an anonymous access type.
29646 @end table
29647
29648
29649 @node Implementation-dependent characteristics
29650 @section Implementation-dependent characteristics
29651 @noindent
29652 Although the Ada language defines the semantics of each construct as
29653 precisely as practical, in some situations (for example for reasons of
29654 efficiency, or where the effect is heavily dependent on the host or target
29655 platform) the implementation is allowed some freedom.  In porting Ada 83
29656 code to GNAT, you need to be aware of whether / how the existing code
29657 exercised such implementation dependencies.  Such characteristics fall into
29658 several categories, and GNAT offers specific support in assisting the
29659 transition from certain Ada 83 compilers.
29660
29661 @menu
29662 * Implementation-defined pragmas::
29663 * Implementation-defined attributes::
29664 * Libraries::
29665 * Elaboration order::
29666 * Target-specific aspects::
29667 @end menu
29668
29669 @node Implementation-defined pragmas
29670 @subsection Implementation-defined pragmas
29671
29672 @noindent
29673 Ada compilers are allowed to supplement the language-defined pragmas, and
29674 these are a potential source of non-portability.  All GNAT-defined pragmas
29675 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
29676 Reference Manual}, and these include several that are specifically
29677 intended to correspond to other vendors' Ada 83 pragmas.
29678 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29679 For compatibility with HP Ada 83, GNAT supplies the pragmas
29680 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29681 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29682 and @code{Volatile}.
29683 Other relevant pragmas include @code{External} and @code{Link_With}.
29684 Some vendor-specific
29685 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29686 recognized, thus
29687 avoiding compiler rejection of units that contain such pragmas; they are not
29688 relevant in a GNAT context and hence are not otherwise implemented.
29689
29690 @node Implementation-defined attributes
29691 @subsection Implementation-defined attributes
29692
29693 Analogous to pragmas, the set of attributes may be extended by an
29694 implementation.  All GNAT-defined attributes are described in
29695 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
29696 Manual}, and these include several that are specifically intended
29697 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
29698 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
29699 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29700 @code{Type_Class}.
29701
29702 @node Libraries
29703 @subsection Libraries
29704 @noindent
29705 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
29706 code uses vendor-specific libraries then there are several ways to manage
29707 this in Ada 95 or Ada 2005:
29708 @enumerate
29709 @item
29710 If the source code for the libraries (specs and bodies) are
29711 available, then the libraries can be migrated in the same way as the
29712 application.
29713 @item
29714 If the source code for the specs but not the bodies are
29715 available, then you can reimplement the bodies.
29716 @item
29717 Some features introduced by Ada 95 obviate the need for library support.  For
29718 example most Ada 83 vendors supplied a package for unsigned integers.  The
29719 Ada 95 modular type feature is the preferred way to handle this need, so
29720 instead of migrating or reimplementing the unsigned integer package it may
29721 be preferable to retrofit the application using modular types.
29722 @end enumerate
29723
29724 @node Elaboration order
29725 @subsection Elaboration order
29726 @noindent
29727 The implementation can choose any elaboration order consistent with the unit
29728 dependency relationship.  This freedom means that some orders can result in
29729 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29730 to invoke a subprogram its body has been elaborated, or to instantiate a
29731 generic before the generic body has been elaborated.  By default GNAT
29732 attempts to choose a safe order (one that will not encounter access before
29733 elaboration problems) by implicitly inserting @code{Elaborate} or
29734 @code{Elaborate_All} pragmas where
29735 needed.  However, this can lead to the creation of elaboration circularities
29736 and a resulting rejection of the program by gnatbind.  This issue is
29737 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29738 In brief, there are several
29739 ways to deal with this situation:
29740
29741 @itemize @bullet
29742 @item
29743 Modify the program to eliminate the circularities, e.g.@: by moving
29744 elaboration-time code into explicitly-invoked procedures
29745 @item
29746 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29747 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29748 @code{Elaborate_All}
29749 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29750 (by selectively suppressing elaboration checks via pragma
29751 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29752 @end itemize
29753
29754 @node Target-specific aspects
29755 @subsection Target-specific aspects
29756 @noindent
29757 Low-level applications need to deal with machine addresses, data
29758 representations, interfacing with assembler code, and similar issues.  If
29759 such an Ada 83 application is being ported to different target hardware (for
29760 example where the byte endianness has changed) then you will need to
29761 carefully examine the program logic; the porting effort will heavily depend
29762 on the robustness of the original design.  Moreover, Ada 95 (and thus
29763 Ada 2005) are sometimes
29764 incompatible with typical Ada 83 compiler practices regarding implicit
29765 packing, the meaning of the Size attribute, and the size of access values.
29766 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29767
29768 @node Compatibility with Other Ada Systems
29769 @section Compatibility with Other Ada Systems
29770
29771 @noindent
29772 If programs avoid the use of implementation dependent and
29773 implementation defined features, as documented in the @cite{Ada
29774 Reference Manual}, there should be a high degree of portability between
29775 GNAT and other Ada systems.  The following are specific items which
29776 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29777 compilers, but do not affect porting code to GNAT@.
29778 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29779 the following issues may or may not arise for Ada 2005 programs
29780 when other compilers appear.)
29781
29782 @table @emph
29783 @item Ada 83 Pragmas and Attributes
29784 Ada 95 compilers are allowed, but not required, to implement the missing
29785 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29786 GNAT implements all such pragmas and attributes, eliminating this as
29787 a compatibility concern, but some other Ada 95 compilers reject these
29788 pragmas and attributes.
29789
29790 @item Specialized Needs Annexes
29791 GNAT implements the full set of special needs annexes.  At the
29792 current time, it is the only Ada 95 compiler to do so.  This means that
29793 programs making use of these features may not be portable to other Ada
29794 95 compilation systems.
29795
29796 @item Representation Clauses
29797 Some other Ada 95 compilers implement only the minimal set of
29798 representation clauses required by the Ada 95 reference manual.  GNAT goes
29799 far beyond this minimal set, as described in the next section.
29800 @end table
29801
29802 @node Representation Clauses
29803 @section Representation Clauses
29804
29805 @noindent
29806 The Ada 83 reference manual was quite vague in describing both the minimal
29807 required implementation of representation clauses, and also their precise
29808 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
29809 minimal set of capabilities required is still quite limited.
29810
29811 GNAT implements the full required set of capabilities in
29812 Ada 95 and Ada 2005, but also goes much further, and in particular
29813 an effort has been made to be compatible with existing Ada 83 usage to the
29814 greatest extent possible.
29815
29816 A few cases exist in which Ada 83 compiler behavior is incompatible with
29817 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
29818 intentional or accidental dependence on specific implementation dependent
29819 characteristics of these Ada 83 compilers.  The following is a list of
29820 the cases most likely to arise in existing Ada 83 code.
29821
29822 @table @emph
29823 @item Implicit Packing
29824 Some Ada 83 compilers allowed a Size specification to cause implicit
29825 packing of an array or record.  This could cause expensive implicit
29826 conversions for change of representation in the presence of derived
29827 types, and the Ada design intends to avoid this possibility.
29828 Subsequent AI's were issued to make it clear that such implicit
29829 change of representation in response to a Size clause is inadvisable,
29830 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29831 Reference Manuals as implementation advice that is followed by GNAT@.
29832 The problem will show up as an error
29833 message rejecting the size clause.  The fix is simply to provide
29834 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29835 a Component_Size clause.
29836
29837 @item Meaning of Size Attribute
29838 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29839 the minimal number of bits required to hold values of the type.  For example,
29840 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29841 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
29842 some 32 in this situation.  This problem will usually show up as a compile
29843 time error, but not always.  It is a good idea to check all uses of the
29844 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
29845 Object_Size can provide a useful way of duplicating the behavior of
29846 some Ada 83 compiler systems.
29847
29848 @item Size of Access Types
29849 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29850 and that therefore it will be the same size as a System.Address value.  This
29851 assumption is true for GNAT in most cases with one exception.  For the case of
29852 a pointer to an unconstrained array type (where the bounds may vary from one
29853 value of the access type to another), the default is to use a ``fat pointer'',
29854 which is represented as two separate pointers, one to the bounds, and one to
29855 the array.  This representation has a number of advantages, including improved
29856 efficiency.  However, it may cause some difficulties in porting existing Ada 83
29857 code which makes the assumption that, for example, pointers fit in 32 bits on
29858 a machine with 32-bit addressing.
29859
29860 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29861 access types in this case (where the designated type is an unconstrained array
29862 type).  These thin pointers are indeed the same size as a System.Address value.
29863 To specify a thin pointer, use a size clause for the type, for example:
29864
29865 @smallexample @c ada
29866 type X is access all String;
29867 for X'Size use Standard'Address_Size;
29868 @end smallexample
29869
29870 @noindent
29871 which will cause the type X to be represented using a single pointer.
29872 When using this representation, the bounds are right behind the array.
29873 This representation is slightly less efficient, and does not allow quite
29874 such flexibility in the use of foreign pointers or in using the
29875 Unrestricted_Access attribute to create pointers to non-aliased objects.
29876 But for any standard portable use of the access type it will work in
29877 a functionally correct manner and allow porting of existing code.
29878 Note that another way of forcing a thin pointer representation
29879 is to use a component size clause for the element size in an array,
29880 or a record representation clause for an access field in a record.
29881 @end table
29882
29883 @ifclear vms
29884 @c This brief section is only in the non-VMS version
29885 @c The complete chapter on HP Ada is in the VMS version
29886 @node Compatibility with HP Ada 83
29887 @section Compatibility with HP Ada 83
29888
29889 @noindent
29890 The VMS version of GNAT fully implements all the pragmas and attributes
29891 provided by HP Ada 83, as well as providing the standard HP Ada 83
29892 libraries, including Starlet.  In addition, data layouts and parameter
29893 passing conventions are highly compatible.  This means that porting
29894 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29895 most other porting efforts.  The following are some of the most
29896 significant differences between GNAT and HP Ada 83.
29897
29898 @table @emph
29899 @item Default floating-point representation
29900 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29901 it is VMS format.  GNAT does implement the necessary pragmas
29902 (Long_Float, Float_Representation) for changing this default.
29903
29904 @item System
29905 The package System in GNAT exactly corresponds to the definition in the
29906 Ada 95 reference manual, which means that it excludes many of the
29907 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
29908 that contains the additional definitions, and a special pragma,
29909 Extend_System allows this package to be treated transparently as an
29910 extension of package System.
29911
29912 @item To_Address
29913 The definitions provided by Aux_DEC are exactly compatible with those
29914 in the HP Ada 83 version of System, with one exception.
29915 HP Ada provides the following declarations:
29916
29917 @smallexample @c ada
29918 TO_ADDRESS (INTEGER)
29919 TO_ADDRESS (UNSIGNED_LONGWORD)
29920 TO_ADDRESS (@i{universal_integer})
29921 @end smallexample
29922
29923 @noindent
29924 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29925 an extension to Ada 83 not strictly compatible with the reference manual.
29926 In GNAT, we are constrained to be exactly compatible with the standard,
29927 and this means we cannot provide this capability.  In HP Ada 83, the
29928 point of this definition is to deal with a call like:
29929
29930 @smallexample @c ada
29931 TO_ADDRESS (16#12777#);
29932 @end smallexample
29933
29934 @noindent
29935 Normally, according to the Ada 83 standard, one would expect this to be
29936 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29937 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
29938 definition using @i{universal_integer} takes precedence.
29939
29940 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29941 is not possible to be 100% compatible.  Since there are many programs using
29942 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29943 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29944 declarations provided in the GNAT version of AUX_Dec are:
29945
29946 @smallexample @c ada
29947 function To_Address (X : Integer) return Address;
29948 pragma Pure_Function (To_Address);
29949
29950 function To_Address_Long (X : Unsigned_Longword)
29951  return Address;
29952 pragma Pure_Function (To_Address_Long);
29953 @end smallexample
29954
29955 @noindent
29956 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29957 change the name to TO_ADDRESS_LONG@.
29958
29959 @item Task_Id values
29960 The Task_Id values assigned will be different in the two systems, and GNAT
29961 does not provide a specified value for the Task_Id of the environment task,
29962 which in GNAT is treated like any other declared task.
29963 @end table
29964
29965 @noindent
29966 For full details on these and other less significant compatibility issues,
29967 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29968 Overview and Comparison on HP Platforms}.
29969
29970 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29971 attributes are recognized, although only a subset of them can sensibly
29972 be implemented.  The description of pragmas in @ref{Implementation
29973 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
29974 indicates whether or not they are applicable to non-VMS systems.
29975 @end ifclear
29976
29977 @ifset vms
29978 @node Transitioning to 64-Bit GNAT for OpenVMS
29979 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29980
29981 @noindent
29982 This section is meant to assist users of pre-2006 @value{EDITION}
29983 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29984 the version of the GNAT technology supplied in 2006 and later for
29985 OpenVMS on both Alpha and I64.
29986
29987 @menu
29988 * Introduction to transitioning::
29989 * Migration of 32 bit code::
29990 * Taking advantage of 64 bit addressing::
29991 * Technical details::
29992 @end menu
29993
29994 @node Introduction to transitioning
29995 @subsection Introduction
29996
29997 @noindent
29998 64-bit @value{EDITION} for Open VMS has been designed to meet
29999 three main goals:
30000
30001 @enumerate
30002 @item
30003 Providing a full conforming implementation of Ada 95 and Ada 2005
30004
30005 @item
30006 Allowing maximum backward compatibility, thus easing migration of existing
30007 Ada source code
30008
30009 @item
30010 Supplying a path for exploiting the full 64-bit address range
30011 @end enumerate
30012
30013 @noindent
30014 Ada's strong typing semantics has made it
30015 impractical to have different 32-bit and 64-bit modes. As soon as
30016 one object could possibly be outside the 32-bit address space, this
30017 would make it necessary for the @code{System.Address} type to be 64 bits.
30018 In particular, this would cause inconsistencies if 32-bit code is
30019 called from 64-bit code that raises an exception.
30020
30021 This issue has been resolved by always using 64-bit addressing
30022 at the system level, but allowing for automatic conversions between
30023 32-bit and 64-bit addresses where required. Thus users who
30024 do not currently require 64-bit addressing capabilities, can
30025 recompile their code with only minimal changes (and indeed
30026 if the code is written in portable Ada, with no assumptions about
30027 the size of the @code{Address} type, then no changes at all are necessary).
30028 At the same time,
30029 this approach provides a simple, gradual upgrade path to future
30030 use of larger memories than available for 32-bit systems.
30031 Also, newly written applications or libraries will by default
30032 be fully compatible with future systems exploiting 64-bit
30033 addressing capabilities.
30034
30035 @ref{Migration of 32 bit code}, will focus on porting applications
30036 that do not require more than 2 GB of
30037 addressable memory. This code will be referred to as
30038 @emph{32-bit code}.
30039 For applications intending to exploit the full 64-bit address space,
30040 @ref{Taking advantage of 64 bit addressing},
30041 will consider further changes that may be required.
30042 Such code will be referred to below as @emph{64-bit code}.
30043
30044 @node Migration of 32 bit code
30045 @subsection Migration of 32-bit code
30046
30047 @menu
30048 * Address types::
30049 * Access types::
30050 * Unchecked conversions::
30051 * Predefined constants::
30052 * Interfacing with C::
30053 * Experience with source compatibility::
30054 @end menu
30055
30056 @node Address types
30057 @subsubsection Address types
30058
30059 @noindent
30060 To solve the problem of mixing 64-bit and 32-bit addressing,
30061 while maintaining maximum backward compatibility, the following
30062 approach has been taken:
30063
30064 @itemize @bullet
30065 @item
30066 @code{System.Address} always has a size of 64 bits
30067
30068 @item
30069 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30070 @end itemize
30071
30072 @noindent
30073 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30074 a @code{Short_Address}
30075 may be used where an @code{Address} is required, and vice versa, without
30076 needing explicit type conversions.
30077 By virtue of the Open VMS parameter passing conventions,
30078 even imported
30079 and exported subprograms that have 32-bit address parameters are
30080 compatible with those that have 64-bit address parameters.
30081 (See @ref{Making code 64 bit clean} for details.)
30082
30083 The areas that may need attention are those where record types have
30084 been defined that contain components of the type @code{System.Address}, and
30085 where objects of this type are passed to code expecting a record layout with
30086 32-bit addresses.
30087
30088 Different compilers on different platforms cannot be
30089 expected to represent the same type in the same way,
30090 since alignment constraints
30091 and other system-dependent properties affect the compiler's decision.
30092 For that reason, Ada code
30093 generally uses representation clauses to specify the expected
30094 layout where required.
30095
30096 If such a representation clause uses 32 bits for a component having
30097 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30098 will detect that error and produce a specific diagnostic message.
30099 The developer should then determine whether the representation
30100 should be 64 bits or not and make either of two changes:
30101 change the size to 64 bits and leave the type as @code{System.Address}, or
30102 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30103 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30104 required in any code setting or accessing the field; the compiler will
30105 automatically perform any needed conversions between address
30106 formats.
30107
30108 @node Access types
30109 @subsubsection Access types
30110
30111 @noindent
30112 By default, objects designated by access values are always
30113 allocated in the 32-bit
30114 address space. Thus legacy code will never contain
30115 any objects that are not addressable with 32-bit addresses, and
30116 the compiler will never raise exceptions as result of mixing
30117 32-bit and 64-bit addresses.
30118
30119 However, the access values themselves are represented in 64 bits, for optimum
30120 performance and future compatibility with 64-bit code. As was
30121 the case with @code{System.Address}, the compiler will give an error message
30122 if an object or record component has a representation clause that
30123 requires the access value to fit in 32 bits. In such a situation,
30124 an explicit size clause for the access type, specifying 32 bits,
30125 will have the desired effect.
30126
30127 General access types (declared with @code{access all}) can never be
30128 32 bits, as values of such types must be able to refer to any object
30129 of the  designated type,
30130 including objects residing outside the 32-bit address range.
30131 Existing Ada 83 code will not contain such type definitions,
30132 however, since general access types were introduced in Ada 95.
30133
30134 @node Unchecked conversions
30135 @subsubsection Unchecked conversions
30136
30137 @noindent
30138 In the case of an @code{Unchecked_Conversion} where the source type is a
30139 64-bit access type or the type @code{System.Address}, and the target
30140 type is a 32-bit type, the compiler will generate a warning.
30141 Even though the generated code will still perform the required
30142 conversions, it is highly recommended in these cases to use
30143 respectively a 32-bit access type or @code{System.Short_Address}
30144 as the source type.
30145
30146 @node Predefined constants
30147 @subsubsection Predefined constants
30148
30149 @noindent
30150 The following table shows the correspondence between pre-2006 versions of
30151 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
30152 (``New''):
30153
30154 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
30155 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
30156 @item   @code{System.Word_Size}          @tab 32      @tab 64
30157 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
30158 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
30159 @item   @code{System.Address_Size}       @tab 32      @tab 64
30160 @end multitable
30161
30162 @noindent
30163 If you need to refer to the specific
30164 memory size of a 32-bit implementation, instead of the
30165 actual memory size, use @code{System.Short_Memory_Size}
30166 rather than @code{System.Memory_Size}.
30167 Similarly, references to @code{System.Address_Size} may need
30168 to be replaced by @code{System.Short_Address'Size}.
30169 The program @command{gnatfind} may be useful for locating
30170 references to the above constants, so that you can verify that they
30171 are still correct.
30172
30173 @node Interfacing with C
30174 @subsubsection Interfacing with C
30175
30176 @noindent
30177 In order to minimize the impact of the transition to 64-bit addresses on
30178 legacy programs, some fundamental types in the @code{Interfaces.C}
30179 package hierarchy continue to be represented in 32 bits.
30180 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
30181 This eases integration with the default HP C layout choices, for example
30182 as found in the system routines in @code{DECC$SHR.EXE}.
30183 Because of this implementation choice, the type fully compatible with
30184 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
30185 Depending on the context the compiler will issue a
30186 warning or an error when type @code{Address} is used, alerting the user to a
30187 potential problem. Otherwise 32-bit programs that use
30188 @code{Interfaces.C} should normally not require code modifications
30189
30190 The other issue arising with C interfacing concerns pragma @code{Convention}.
30191 For VMS 64-bit systems, there is an issue of the appropriate default size
30192 of C convention pointers in the absence of an explicit size clause. The HP
30193 C compiler can choose either 32 or 64 bits depending on compiler options.
30194 GNAT chooses 32-bits rather than 64-bits in the default case where no size
30195 clause is given. This proves a better choice for porting 32-bit legacy
30196 applications. In order to have a 64-bit representation, it is necessary to
30197 specify a size representation clause. For example:
30198
30199 @smallexample @c ada
30200 type int_star is access Interfaces.C.int;
30201 pragma Convention(C, int_star);
30202 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
30203 @end smallexample
30204
30205 @node Experience with source compatibility
30206 @subsubsection Experience with source compatibility
30207
30208 @noindent
30209 The Security Server and STARLET on I64 provide an interesting ``test case''
30210 for source compatibility issues, since it is in such system code
30211 where assumptions about @code{Address} size might be expected to occur.
30212 Indeed, there were a small number of occasions in the Security Server
30213 file @file{jibdef.ads}
30214 where a representation clause for a record type specified
30215 32 bits for a component of type @code{Address}.
30216 All of these errors were detected by the compiler.
30217 The repair was obvious and immediate; to simply replace @code{Address} by
30218 @code{Short_Address}.
30219
30220 In the case of STARLET, there were several record types that should
30221 have had representation clauses but did not.  In these record types
30222 there was an implicit assumption that an @code{Address} value occupied
30223 32 bits.
30224 These compiled without error, but their usage resulted in run-time error
30225 returns from STARLET system calls.
30226 Future GNAT technology enhancements may include a tool that detects and flags
30227 these sorts of potential source code porting problems.
30228
30229 @c ****************************************
30230 @node Taking advantage of 64 bit addressing
30231 @subsection Taking advantage of 64-bit addressing
30232
30233 @menu
30234 * Making code 64 bit clean::
30235 * Allocating memory from the 64 bit storage pool::
30236 * Restrictions on use of 64 bit objects::
30237 * Using 64 bit storage pools by default::
30238 * General access types::
30239 * STARLET and other predefined libraries::
30240 @end menu
30241
30242 @node Making code 64 bit clean
30243 @subsubsection Making code 64-bit clean
30244
30245 @noindent
30246 In order to prevent problems that may occur when (parts of) a
30247 system start using memory outside the 32-bit address range,
30248 we recommend some additional guidelines:
30249
30250 @itemize @bullet
30251 @item
30252 For imported subprograms that take parameters of the
30253 type @code{System.Address}, ensure that these subprograms can
30254 indeed handle 64-bit addresses. If not, or when in doubt,
30255 change the subprogram declaration to specify
30256 @code{System.Short_Address} instead.
30257
30258 @item
30259 Resolve all warnings related to size mismatches in
30260 unchecked conversions. Failing to do so causes
30261 erroneous execution if the source object is outside
30262 the 32-bit address space.
30263
30264 @item
30265 (optional) Explicitly use the 32-bit storage pool
30266 for access types used in a 32-bit context, or use
30267 generic access types where possible
30268 (@pxref{Restrictions on use of 64 bit objects}).
30269 @end itemize
30270
30271 @noindent
30272 If these rules are followed, the compiler will automatically insert
30273 any necessary checks to ensure that no addresses or access values
30274 passed to 32-bit code ever refer to objects outside the 32-bit
30275 address range.
30276 Any attempt to do this will raise @code{Constraint_Error}.
30277
30278 @node Allocating memory from the 64 bit storage pool
30279 @subsubsection Allocating memory from the 64-bit storage pool
30280
30281 @noindent
30282 For any access type @code{T} that potentially requires memory allocations
30283 beyond the 32-bit address space,
30284 use the following representation clause:
30285
30286 @smallexample @c ada
30287    for T'Storage_Pool use System.Pool_64;
30288 @end smallexample
30289
30290 @node Restrictions on use of 64 bit objects
30291 @subsubsection Restrictions on use of 64-bit objects
30292
30293 @noindent
30294 Taking the address of an object allocated from a 64-bit storage pool,
30295 and then passing this address to a subprogram expecting
30296 @code{System.Short_Address},
30297 or assigning it to a variable of type @code{Short_Address}, will cause
30298 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
30299 (@pxref{Making code 64 bit clean}), or checks are suppressed,
30300 no exception is raised and execution
30301 will become erroneous.
30302
30303 @node Using 64 bit storage pools by default
30304 @subsubsection Using 64-bit storage pools by default
30305
30306 @noindent
30307 In some cases it may be desirable to have the compiler allocate
30308 from 64-bit storage pools by default. This may be the case for
30309 libraries that are 64-bit clean, but may be used in both 32-bit
30310 and 64-bit contexts. For these cases the following configuration
30311 pragma may be specified:
30312
30313 @smallexample @c ada
30314   pragma Pool_64_Default;
30315 @end smallexample
30316
30317 @noindent
30318 Any code compiled in the context of this pragma will by default
30319 use the @code{System.Pool_64} storage pool. This default may be overridden
30320 for a specific access type @code{T} by the representation clause:
30321
30322 @smallexample @c ada
30323    for T'Storage_Pool use System.Pool_32;
30324 @end smallexample
30325
30326 @noindent
30327 Any object whose address may be passed to a subprogram with a
30328 @code{Short_Address} argument, or assigned to a variable of type
30329 @code{Short_Address}, needs to be allocated from this pool.
30330
30331 @node General access types
30332 @subsubsection General access types
30333
30334 @noindent
30335 Objects designated by access values from a
30336 general access type (declared with @code{access all}) are never allocated
30337 from a 64-bit storage pool. Code that uses general access types will
30338 accept objects allocated in either 32-bit or 64-bit address spaces,
30339 but never allocate objects outside the 32-bit address space.
30340 Using general access types ensures maximum compatibility with both
30341 32-bit and 64-bit code.
30342
30343 @node STARLET and other predefined libraries
30344 @subsubsection STARLET and other predefined libraries
30345
30346 @noindent
30347 All code that comes as part of GNAT is 64-bit clean, but the
30348 restrictions given in @ref{Restrictions on use of 64 bit objects},
30349 still apply. Look at the package
30350 specs to see in which contexts objects allocated
30351 in 64-bit address space are acceptable.
30352
30353 @node Technical details
30354 @subsection Technical details
30355
30356 @noindent
30357 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
30358 Ada standard with respect to the type of @code{System.Address}. Previous
30359 versions of GNAT Pro have defined this type as private and implemented it as a
30360 modular type.
30361
30362 In order to allow defining @code{System.Short_Address} as a proper subtype,
30363 and to match the implicit sign extension in parameter passing,
30364 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
30365 visible (i.e., non-private) integer type.
30366 Standard operations on the type, such as the binary operators ``+'', ``-'',
30367 etc., that take @code{Address} operands and return an @code{Address} result,
30368 have been hidden by declaring these
30369 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
30370 ambiguities that would otherwise result from overloading.
30371 (Note that, although @code{Address} is a visible integer type,
30372 good programming practice dictates against exploiting the type's
30373 integer properties such as literals, since this will compromise
30374 code portability.)
30375
30376 Defining @code{Address} as a visible integer type helps achieve
30377 maximum compatibility for existing Ada code,
30378 without sacrificing the capabilities of the 64-bit architecture.
30379 @end ifset
30380
30381 @c ************************************************
30382 @ifset unw
30383 @node Microsoft Windows Topics
30384 @appendix Microsoft Windows Topics
30385 @cindex Windows NT
30386 @cindex Windows 95
30387 @cindex Windows 98
30388
30389 @noindent
30390 This chapter describes topics that are specific to the Microsoft Windows
30391 platforms (NT, 2000, and XP Professional).
30392
30393 @menu
30394 * Using GNAT on Windows::
30395 * Using a network installation of GNAT::
30396 * CONSOLE and WINDOWS subsystems::
30397 * Temporary Files::
30398 * Mixed-Language Programming on Windows::
30399 * Windows Calling Conventions::
30400 * Introduction to Dynamic Link Libraries (DLLs)::
30401 * Using DLLs with GNAT::
30402 * Building DLLs with GNAT::
30403 * Building DLLs with GNAT Project files::
30404 * Building DLLs with gnatdll::
30405 * GNAT and Windows Resources::
30406 * Debugging a DLL::
30407 * Setting Stack Size from gnatlink::
30408 * Setting Heap Size from gnatlink::
30409 @end menu
30410
30411 @node Using GNAT on Windows
30412 @section Using GNAT on Windows
30413
30414 @noindent
30415 One of the strengths of the GNAT technology is that its tool set
30416 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
30417 @code{gdb} debugger, etc.) is used in the same way regardless of the
30418 platform.
30419
30420 On Windows this tool set is complemented by a number of Microsoft-specific
30421 tools that have been provided to facilitate interoperability with Windows
30422 when this is required. With these tools:
30423
30424 @itemize @bullet
30425
30426 @item
30427 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
30428 subsystems.
30429
30430 @item
30431 You can use any Dynamically Linked Library (DLL) in your Ada code (both
30432 relocatable and non-relocatable DLLs are supported).
30433
30434 @item
30435 You can build Ada DLLs for use in other applications. These applications
30436 can be written in a language other than Ada (e.g., C, C++, etc). Again both
30437 relocatable and non-relocatable Ada DLLs are supported.
30438
30439 @item
30440 You can include Windows resources in your Ada application.
30441
30442 @item
30443 You can use or create COM/DCOM objects.
30444 @end itemize
30445
30446 @noindent
30447 Immediately below are listed all known general GNAT-for-Windows restrictions.
30448 Other restrictions about specific features like Windows Resources and DLLs
30449 are listed in separate sections below.
30450
30451 @itemize @bullet
30452
30453 @item
30454 It is not possible to use @code{GetLastError} and @code{SetLastError}
30455 when tasking, protected records, or exceptions are used. In these
30456 cases, in order to implement Ada semantics, the GNAT run-time system
30457 calls certain Win32 routines that set the last error variable to 0 upon
30458 success. It should be possible to use @code{GetLastError} and
30459 @code{SetLastError} when tasking, protected record, and exception
30460 features are not used, but it is not guaranteed to work.
30461
30462 @item
30463 It is not possible to link against Microsoft libraries except for
30464 import libraries. The library must be built to be compatible with
30465 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
30466 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
30467 not be compatible with the GNAT runtime. Even if the library is
30468 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
30469
30470 @item
30471 When the compilation environment is located on FAT32 drives, users may
30472 experience recompilations of the source files that have not changed if
30473 Daylight Saving Time (DST) state has changed since the last time files
30474 were compiled. NTFS drives do not have this problem.
30475
30476 @item
30477 No components of the GNAT toolset use any entries in the Windows
30478 registry. The only entries that can be created are file associations and
30479 PATH settings, provided the user has chosen to create them at installation
30480 time, as well as some minimal book-keeping information needed to correctly
30481 uninstall or integrate different GNAT products.
30482 @end itemize
30483
30484 @node Using a network installation of GNAT
30485 @section Using a network installation of GNAT
30486
30487 @noindent
30488 Make sure the system on which GNAT is installed is accessible from the
30489 current machine, i.e., the install location is shared over the network.
30490 Shared resources are accessed on Windows by means of UNC paths, which
30491 have the format @code{\\server\sharename\path}
30492
30493 In order to use such a network installation, simply add the UNC path of the
30494 @file{bin} directory of your GNAT installation in front of your PATH. For
30495 example, if GNAT is installed in @file{\GNAT} directory of a share location
30496 called @file{c-drive} on a machine @file{LOKI}, the following command will
30497 make it available:
30498
30499 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
30500
30501 Be aware that every compilation using the network installation results in the
30502 transfer of large amounts of data across the network and will likely cause
30503 serious performance penalty.
30504
30505 @node CONSOLE and WINDOWS subsystems
30506 @section CONSOLE and WINDOWS subsystems
30507 @cindex CONSOLE Subsystem
30508 @cindex WINDOWS Subsystem
30509 @cindex -mwindows
30510
30511 @noindent
30512 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
30513 (which is the default subsystem) will always create a console when
30514 launching the application. This is not something desirable when the
30515 application has a Windows GUI. To get rid of this console the
30516 application must be using the @code{WINDOWS} subsystem. To do so
30517 the @option{-mwindows} linker option must be specified.
30518
30519 @smallexample
30520 $ gnatmake winprog -largs -mwindows
30521 @end smallexample
30522
30523 @node Temporary Files
30524 @section Temporary Files
30525 @cindex Temporary files
30526
30527 @noindent
30528 It is possible to control where temporary files gets created by setting
30529 the @env{TMP} environment variable. The file will be created:
30530
30531 @itemize
30532 @item Under the directory pointed to by the @env{TMP} environment variable if
30533 this directory exists.
30534
30535 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30536 set (or not pointing to a directory) and if this directory exists.
30537
30538 @item Under the current working directory otherwise.
30539 @end itemize
30540
30541 @noindent
30542 This allows you to determine exactly where the temporary
30543 file will be created. This is particularly useful in networked
30544 environments where you may not have write access to some
30545 directories.
30546
30547 @node Mixed-Language Programming on Windows
30548 @section Mixed-Language Programming on Windows
30549
30550 @noindent
30551 Developing pure Ada applications on Windows is no different than on
30552 other GNAT-supported platforms. However, when developing or porting an
30553 application that contains a mix of Ada and C/C++, the choice of your
30554 Windows C/C++ development environment conditions your overall
30555 interoperability strategy.
30556
30557 If you use @command{gcc} to compile the non-Ada part of your application,
30558 there are no Windows-specific restrictions that affect the overall
30559 interoperability with your Ada code. If you plan to use
30560 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
30561 the following limitations:
30562
30563 @itemize @bullet
30564 @item
30565 You cannot link your Ada code with an object or library generated with
30566 Microsoft tools if these use the @code{.tls} section (Thread Local
30567 Storage section) since the GNAT linker does not yet support this section.
30568
30569 @item
30570 You cannot link your Ada code with an object or library generated with
30571 Microsoft tools if these use I/O routines other than those provided in
30572 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
30573 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
30574 libraries can cause a conflict with @code{msvcrt.dll} services. For
30575 instance Visual C++ I/O stream routines conflict with those in
30576 @code{msvcrt.dll}.
30577 @end itemize
30578
30579 @noindent
30580 If you do want to use the Microsoft tools for your non-Ada code and hit one
30581 of the above limitations, you have two choices:
30582
30583 @enumerate
30584 @item
30585 Encapsulate your non-Ada code in a DLL to be linked with your Ada
30586 application. In this case, use the Microsoft or whatever environment to
30587 build the DLL and use GNAT to build your executable
30588 (@pxref{Using DLLs with GNAT}).
30589
30590 @item
30591 Or you can encapsulate your Ada code in a DLL to be linked with the
30592 other part of your application. In this case, use GNAT to build the DLL
30593 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
30594 environment to build your executable.
30595 @end enumerate
30596
30597 @node Windows Calling Conventions
30598 @section Windows Calling Conventions
30599 @findex Stdcall
30600 @findex APIENTRY
30601
30602 @menu
30603 * C Calling Convention::
30604 * Stdcall Calling Convention::
30605 * Win32 Calling Convention::
30606 * DLL Calling Convention::
30607 @end menu
30608
30609 @noindent
30610 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30611 (callee), there are several ways to push @code{G}'s parameters on the
30612 stack and there are several possible scenarios to clean up the stack
30613 upon @code{G}'s return. A calling convention is an agreed upon software
30614 protocol whereby the responsibilities between the caller (@code{F}) and
30615 the callee (@code{G}) are clearly defined. Several calling conventions
30616 are available for Windows:
30617
30618 @itemize @bullet
30619 @item
30620 @code{C} (Microsoft defined)
30621
30622 @item
30623 @code{Stdcall} (Microsoft defined)
30624
30625 @item
30626 @code{Win32} (GNAT specific)
30627
30628 @item
30629 @code{DLL} (GNAT specific)
30630 @end itemize
30631
30632 @node C Calling Convention
30633 @subsection @code{C} Calling Convention
30634
30635 @noindent
30636 This is the default calling convention used when interfacing to C/C++
30637 routines compiled with either @command{gcc} or Microsoft Visual C++.
30638
30639 In the @code{C} calling convention subprogram parameters are pushed on the
30640 stack by the caller from right to left. The caller itself is in charge of
30641 cleaning up the stack after the call. In addition, the name of a routine
30642 with @code{C} calling convention is mangled by adding a leading underscore.
30643
30644 The name to use on the Ada side when importing (or exporting) a routine
30645 with @code{C} calling convention is the name of the routine. For
30646 instance the C function:
30647
30648 @smallexample
30649 int get_val (long);
30650 @end smallexample
30651
30652 @noindent
30653 should be imported from Ada as follows:
30654
30655 @smallexample @c ada
30656 @group
30657 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30658 pragma Import (C, Get_Val, External_Name => "get_val");
30659 @end group
30660 @end smallexample
30661
30662 @noindent
30663 Note that in this particular case the @code{External_Name} parameter could
30664 have been omitted since, when missing, this parameter is taken to be the
30665 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30666 is missing, as in the above example, this parameter is set to be the
30667 @code{External_Name} with a leading underscore.
30668
30669 When importing a variable defined in C, you should always use the @code{C}
30670 calling convention unless the object containing the variable is part of a
30671 DLL (in which case you should use the @code{Stdcall} calling
30672 convention, @pxref{Stdcall Calling Convention}).
30673
30674 @node Stdcall Calling Convention
30675 @subsection @code{Stdcall} Calling Convention
30676
30677 @noindent
30678 This convention, which was the calling convention used for Pascal
30679 programs, is used by Microsoft for all the routines in the Win32 API for
30680 efficiency reasons. It must be used to import any routine for which this
30681 convention was specified.
30682
30683 In the @code{Stdcall} calling convention subprogram parameters are pushed
30684 on the stack by the caller from right to left. The callee (and not the
30685 caller) is in charge of cleaning the stack on routine exit. In addition,
30686 the name of a routine with @code{Stdcall} calling convention is mangled by
30687 adding a leading underscore (as for the @code{C} calling convention) and a
30688 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
30689 bytes) of the parameters passed to the routine.
30690
30691 The name to use on the Ada side when importing a C routine with a
30692 @code{Stdcall} calling convention is the name of the C routine. The leading
30693 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
30694 the compiler. For instance the Win32 function:
30695
30696 @smallexample
30697 @b{APIENTRY} int get_val (long);
30698 @end smallexample
30699
30700 @noindent
30701 should be imported from Ada as follows:
30702
30703 @smallexample @c ada
30704 @group
30705 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30706 pragma Import (Stdcall, Get_Val);
30707 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30708 @end group
30709 @end smallexample
30710
30711 @noindent
30712 As for the @code{C} calling convention, when the @code{External_Name}
30713 parameter is missing, it is taken to be the name of the Ada entity in lower
30714 case. If instead of writing the above import pragma you write:
30715
30716 @smallexample @c ada
30717 @group
30718 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30719 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30720 @end group
30721 @end smallexample
30722
30723 @noindent
30724 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30725 of specifying the @code{External_Name} parameter you specify the
30726 @code{Link_Name} as in the following example:
30727
30728 @smallexample @c ada
30729 @group
30730 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30731 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30732 @end group
30733 @end smallexample
30734
30735 @noindent
30736 then the imported routine is @code{retrieve_val}, that is, there is no
30737 decoration at all. No leading underscore and no Stdcall suffix
30738 @code{@@}@code{@var{nn}}.
30739
30740 @noindent
30741 This is especially important as in some special cases a DLL's entry
30742 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
30743 name generated for a call has it.
30744
30745 @noindent
30746 It is also possible to import variables defined in a DLL by using an
30747 import pragma for a variable. As an example, if a DLL contains a
30748 variable defined as:
30749
30750 @smallexample
30751 int my_var;
30752 @end smallexample
30753
30754 @noindent
30755 then, to access this variable from Ada you should write:
30756
30757 @smallexample @c ada
30758 @group
30759 My_Var : Interfaces.C.int;
30760 pragma Import (Stdcall, My_Var);
30761 @end group
30762 @end smallexample
30763
30764 @noindent
30765 Note that to ease building cross-platform bindings this convention
30766 will be handled as a @code{C} calling convention on non-Windows platforms.
30767
30768 @node Win32 Calling Convention
30769 @subsection @code{Win32} Calling Convention
30770
30771 @noindent
30772 This convention, which is GNAT-specific is fully equivalent to the
30773 @code{Stdcall} calling convention described above.
30774
30775 @node DLL Calling Convention
30776 @subsection @code{DLL} Calling Convention
30777
30778 @noindent
30779 This convention, which is GNAT-specific is fully equivalent to the
30780 @code{Stdcall} calling convention described above.
30781
30782 @node Introduction to Dynamic Link Libraries (DLLs)
30783 @section Introduction to Dynamic Link Libraries (DLLs)
30784 @findex DLL
30785
30786 @noindent
30787 A Dynamically Linked Library (DLL) is a library that can be shared by
30788 several applications running under Windows. A DLL can contain any number of
30789 routines and variables.
30790
30791 One advantage of DLLs is that you can change and enhance them without
30792 forcing all the applications that depend on them to be relinked or
30793 recompiled. However, you should be aware than all calls to DLL routines are
30794 slower since, as you will understand below, such calls are indirect.
30795
30796 To illustrate the remainder of this section, suppose that an application
30797 wants to use the services of a DLL @file{API.dll}. To use the services
30798 provided by @file{API.dll} you must statically link against the DLL or
30799 an import library which contains a jump table with an entry for each
30800 routine and variable exported by the DLL. In the Microsoft world this
30801 import library is called @file{API.lib}. When using GNAT this import
30802 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30803 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30804
30805 After you have linked your application with the DLL or the import library
30806 and you run your application, here is what happens:
30807
30808 @enumerate
30809 @item
30810 Your application is loaded into memory.
30811
30812 @item
30813 The DLL @file{API.dll} is mapped into the address space of your
30814 application. This means that:
30815
30816 @itemize @bullet
30817 @item
30818 The DLL will use the stack of the calling thread.
30819
30820 @item
30821 The DLL will use the virtual address space of the calling process.
30822
30823 @item
30824 The DLL will allocate memory from the virtual address space of the calling
30825 process.
30826
30827 @item
30828 Handles (pointers) can be safely exchanged between routines in the DLL
30829 routines and routines in the application using the DLL.
30830 @end itemize
30831
30832 @item
30833 The entries in the jump table (from the import library @file{libAPI.dll.a}
30834 or @file{API.lib} or automatically created when linking against a DLL)
30835 which is part of your application are initialized with the addresses
30836 of the routines and variables in @file{API.dll}.
30837
30838 @item
30839 If present in @file{API.dll}, routines @code{DllMain} or
30840 @code{DllMainCRTStartup} are invoked. These routines typically contain
30841 the initialization code needed for the well-being of the routines and
30842 variables exported by the DLL.
30843 @end enumerate
30844
30845 @noindent
30846 There is an additional point which is worth mentioning. In the Windows
30847 world there are two kind of DLLs: relocatable and non-relocatable
30848 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30849 in the target application address space. If the addresses of two
30850 non-relocatable DLLs overlap and these happen to be used by the same
30851 application, a conflict will occur and the application will run
30852 incorrectly. Hence, when possible, it is always preferable to use and
30853 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30854 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30855 User's Guide) removes the debugging symbols from the DLL but the DLL can
30856 still be relocated.
30857
30858 As a side note, an interesting difference between Microsoft DLLs and
30859 Unix shared libraries, is the fact that on most Unix systems all public
30860 routines are exported by default in a Unix shared library, while under
30861 Windows it is possible (but not required) to list exported routines in
30862 a definition file (@pxref{The Definition File}).
30863
30864 @node Using DLLs with GNAT
30865 @section Using DLLs with GNAT
30866
30867 @menu
30868 * Creating an Ada Spec for the DLL Services::
30869 * Creating an Import Library::
30870 @end menu
30871
30872 @noindent
30873 To use the services of a DLL, say @file{API.dll}, in your Ada application
30874 you must have:
30875
30876 @enumerate
30877 @item
30878 The Ada spec for the routines and/or variables you want to access in
30879 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30880 header files provided with the DLL.
30881
30882 @item
30883 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30884 mentioned an import library is a statically linked library containing the
30885 import table which will be filled at load time to point to the actual
30886 @file{API.dll} routines. Sometimes you don't have an import library for the
30887 DLL you want to use. The following sections will explain how to build
30888 one. Note that this is optional.
30889
30890 @item
30891 The actual DLL, @file{API.dll}.
30892 @end enumerate
30893
30894 @noindent
30895 Once you have all the above, to compile an Ada application that uses the
30896 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30897 you simply issue the command
30898
30899 @smallexample
30900 $ gnatmake my_ada_app -largs -lAPI
30901 @end smallexample
30902
30903 @noindent
30904 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30905 tells the GNAT linker to look first for a library named @file{API.lib}
30906 (Microsoft-style name) and if not found for a libraries named
30907 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
30908 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
30909 contains the following pragma
30910
30911 @smallexample @c ada
30912 pragma Linker_Options ("-lAPI");
30913 @end smallexample
30914
30915 @noindent
30916 you do not have to add @option{-largs -lAPI} at the end of the
30917 @command{gnatmake} command.
30918
30919 If any one of the items above is missing you will have to create it
30920 yourself. The following sections explain how to do so using as an
30921 example a fictitious DLL called @file{API.dll}.
30922
30923 @node Creating an Ada Spec for the DLL Services
30924 @subsection Creating an Ada Spec for the DLL Services
30925
30926 @noindent
30927 A DLL typically comes with a C/C++ header file which provides the
30928 definitions of the routines and variables exported by the DLL. The Ada
30929 equivalent of this header file is a package spec that contains definitions
30930 for the imported entities. If the DLL you intend to use does not come with
30931 an Ada spec you have to generate one such spec yourself. For example if
30932 the header file of @file{API.dll} is a file @file{api.h} containing the
30933 following two definitions:
30934
30935 @smallexample
30936 @group
30937 @cartouche
30938 int some_var;
30939 int get (char *);
30940 @end cartouche
30941 @end group
30942 @end smallexample
30943
30944 @noindent
30945 then the equivalent Ada spec could be:
30946
30947 @smallexample @c ada
30948 @group
30949 @cartouche
30950 with Interfaces.C.Strings;
30951 package API is
30952    use Interfaces;
30953
30954    Some_Var : C.int;
30955    function Get (Str : C.Strings.Chars_Ptr) return C.int;
30956
30957 private
30958    pragma Import (C, Get);
30959    pragma Import (DLL, Some_Var);
30960 end API;
30961 @end cartouche
30962 @end group
30963 @end smallexample
30964
30965 @noindent
30966 Note that a variable is
30967 @strong{always imported with a Stdcall convention}. A function
30968 can have @code{C} or @code{Stdcall} convention.
30969 (@pxref{Windows Calling Conventions}).
30970
30971 @node Creating an Import Library
30972 @subsection Creating an Import Library
30973 @cindex Import library
30974
30975 @menu
30976 * The Definition File::
30977 * GNAT-Style Import Library::
30978 * Microsoft-Style Import Library::
30979 @end menu
30980
30981 @noindent
30982 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30983 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30984 with @file{API.dll} you can skip this section. You can also skip this
30985 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30986 as in this case it is possible to link directly against the
30987 DLL. Otherwise read on.
30988
30989 @node The Definition File
30990 @subsubsection The Definition File
30991 @cindex Definition file
30992 @findex .def
30993
30994 @noindent
30995 As previously mentioned, and unlike Unix systems, the list of symbols
30996 that are exported from a DLL must be provided explicitly in Windows.
30997 The main goal of a definition file is precisely that: list the symbols
30998 exported by a DLL. A definition file (usually a file with a @code{.def}
30999 suffix) has the following structure:
31000
31001 @smallexample
31002 @group
31003 @cartouche
31004 @r{[}LIBRARY @var{name}@r{]}
31005 @r{[}DESCRIPTION @var{string}@r{]}
31006 EXPORTS
31007    @var{symbol1}
31008    @var{symbol2}
31009    @dots{}
31010 @end cartouche
31011 @end group
31012 @end smallexample
31013
31014 @table @code
31015 @item LIBRARY @var{name}
31016 This section, which is optional, gives the name of the DLL.
31017
31018 @item DESCRIPTION @var{string}
31019 This section, which is optional, gives a description string that will be
31020 embedded in the import library.
31021
31022 @item EXPORTS
31023 This section gives the list of exported symbols (procedures, functions or
31024 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31025 section of @file{API.def} looks like:
31026
31027 @smallexample
31028 @group
31029 @cartouche
31030 EXPORTS
31031    some_var
31032    get
31033 @end cartouche
31034 @end group
31035 @end smallexample
31036 @end table
31037
31038 @noindent
31039 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31040 (@pxref{Windows Calling Conventions}) for a Stdcall
31041 calling convention function in the exported symbols list.
31042
31043 @noindent
31044 There can actually be other sections in a definition file, but these
31045 sections are not relevant to the discussion at hand.
31046
31047 @node GNAT-Style Import Library
31048 @subsubsection GNAT-Style Import Library
31049
31050 @noindent
31051 To create a static import library from @file{API.dll} with the GNAT tools
31052 you should proceed as follows:
31053
31054 @enumerate
31055 @item
31056 Create the definition file @file{API.def} (@pxref{The Definition File}).
31057 For that use the @code{dll2def} tool as follows:
31058
31059 @smallexample
31060 $ dll2def API.dll > API.def
31061 @end smallexample
31062
31063 @noindent
31064 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31065 to standard output the list of entry points in the DLL. Note that if
31066 some routines in the DLL have the @code{Stdcall} convention
31067 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31068 suffix then you'll have to edit @file{api.def} to add it, and specify
31069 @option{-k} to @command{gnatdll} when creating the import library.
31070
31071 @noindent
31072 Here are some hints to find the right @code{@@}@var{nn} suffix.
31073
31074 @enumerate
31075 @item
31076 If you have the Microsoft import library (.lib), it is possible to get
31077 the right symbols by using Microsoft @code{dumpbin} tool (see the
31078 corresponding Microsoft documentation for further details).
31079
31080 @smallexample
31081 $ dumpbin /exports api.lib
31082 @end smallexample
31083
31084 @item
31085 If you have a message about a missing symbol at link time the compiler
31086 tells you what symbol is expected. You just have to go back to the
31087 definition file and add the right suffix.
31088 @end enumerate
31089
31090 @item
31091 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31092 (@pxref{Using gnatdll}) as follows:
31093
31094 @smallexample
31095 $ gnatdll -e API.def -d API.dll
31096 @end smallexample
31097
31098 @noindent
31099 @code{gnatdll} takes as input a definition file @file{API.def} and the
31100 name of the DLL containing the services listed in the definition file
31101 @file{API.dll}. The name of the static import library generated is
31102 computed from the name of the definition file as follows: if the
31103 definition file name is @var{xyz}@code{.def}, the import library name will
31104 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31105 @option{-e} could have been removed because the name of the definition
31106 file (before the ``@code{.def}'' suffix) is the same as the name of the
31107 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31108 @end enumerate
31109
31110 @node Microsoft-Style Import Library
31111 @subsubsection Microsoft-Style Import Library
31112
31113 @noindent
31114 With GNAT you can either use a GNAT-style or Microsoft-style import
31115 library. A Microsoft import library is needed only if you plan to make an
31116 Ada DLL available to applications developed with Microsoft
31117 tools (@pxref{Mixed-Language Programming on Windows}).
31118
31119 To create a Microsoft-style import library for @file{API.dll} you
31120 should proceed as follows:
31121
31122 @enumerate
31123 @item
31124 Create the definition file @file{API.def} from the DLL. For this use either
31125 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31126 tool (see the corresponding Microsoft documentation for further details).
31127
31128 @item
31129 Build the actual import library using Microsoft's @code{lib} utility:
31130
31131 @smallexample
31132 $ lib -machine:IX86 -def:API.def -out:API.lib
31133 @end smallexample
31134
31135 @noindent
31136 If you use the above command the definition file @file{API.def} must
31137 contain a line giving the name of the DLL:
31138
31139 @smallexample
31140 LIBRARY      "API"
31141 @end smallexample
31142
31143 @noindent
31144 See the Microsoft documentation for further details about the usage of
31145 @code{lib}.
31146 @end enumerate
31147
31148 @node Building DLLs with GNAT
31149 @section Building DLLs with GNAT
31150 @cindex DLLs, building
31151
31152 @noindent
31153 This section explain how to build DLLs using the GNAT built-in DLL
31154 support. With the following procedure it is straight forward to build
31155 and use DLLs with GNAT.
31156
31157 @enumerate
31158
31159 @item building object files
31160
31161 The first step is to build all objects files that are to be included
31162 into the DLL. This is done by using the standard @command{gnatmake} tool.
31163
31164 @item building the DLL
31165
31166 To build the DLL you must use @command{gcc}'s @option{-shared}
31167 option. It is quite simple to use this method:
31168
31169 @smallexample
31170 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
31171 @end smallexample
31172
31173 It is important to note that in this case all symbols found in the
31174 object files are automatically exported. It is possible to restrict
31175 the set of symbols to export by passing to @command{gcc} a definition
31176 file, @pxref{The Definition File}. For example:
31177
31178 @smallexample
31179 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
31180 @end smallexample
31181
31182 If you use a definition file you must export the elaboration procedures
31183 for every package that required one. Elaboration procedures are named
31184 using the package name followed by "_E".
31185
31186 @item preparing DLL to be used
31187
31188 For the DLL to be used by client programs the bodies must be hidden
31189 from it and the .ali set with read-only attribute. This is very important
31190 otherwise GNAT will recompile all packages and will not actually use
31191 the code in the DLL. For example:
31192
31193 @smallexample
31194 $ mkdir apilib
31195 $ copy *.ads *.ali api.dll apilib
31196 $ attrib +R apilib\*.ali
31197 @end smallexample
31198
31199 @end enumerate
31200
31201 At this point it is possible to use the DLL by directly linking
31202 against it. Note that you must use the GNAT shared runtime when using
31203 GNAT shared libraries. This is achieved by using @option{-shared} binder's
31204 option.
31205
31206 @smallexample
31207 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
31208 @end smallexample
31209
31210 @node Building DLLs with GNAT Project files
31211 @section Building DLLs with GNAT Project files
31212 @cindex DLLs, building
31213
31214 @noindent
31215 There is nothing specific to Windows in the build process.
31216 @pxref{Library Projects}.
31217
31218 @noindent
31219 Due to a system limitation, it is not possible under Windows to create threads
31220 when inside the @code{DllMain} routine which is used for auto-initialization
31221 of shared libraries, so it is not possible to have library level tasks in SALs.
31222
31223 @node Building DLLs with gnatdll
31224 @section Building DLLs with gnatdll
31225 @cindex DLLs, building
31226
31227 @menu
31228 * Limitations When Using Ada DLLs from Ada::
31229 * Exporting Ada Entities::
31230 * Ada DLLs and Elaboration::
31231 * Ada DLLs and Finalization::
31232 * Creating a Spec for Ada DLLs::
31233 * Creating the Definition File::
31234 * Using gnatdll::
31235 @end menu
31236
31237 @noindent
31238 Note that it is preferred to use the built-in GNAT DLL support
31239 (@pxref{Building DLLs with GNAT}) or GNAT Project files
31240 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
31241
31242 This section explains how to build DLLs containing Ada code using
31243 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
31244 remainder of this section.
31245
31246 The steps required to build an Ada DLL that is to be used by Ada as well as
31247 non-Ada applications are as follows:
31248
31249 @enumerate
31250 @item
31251 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
31252 @code{Stdcall} calling convention to avoid any Ada name mangling for the
31253 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
31254 skip this step if you plan to use the Ada DLL only from Ada applications.
31255
31256 @item
31257 Your Ada code must export an initialization routine which calls the routine
31258 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
31259 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
31260 routine exported by the Ada DLL must be invoked by the clients of the DLL
31261 to initialize the DLL.
31262
31263 @item
31264 When useful, the DLL should also export a finalization routine which calls
31265 routine @code{adafinal} generated by @command{gnatbind} to perform the
31266 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
31267 The finalization routine exported by the Ada DLL must be invoked by the
31268 clients of the DLL when the DLL services are no further needed.
31269
31270 @item
31271 You must provide a spec for the services exported by the Ada DLL in each
31272 of the programming languages to which you plan to make the DLL available.
31273
31274 @item
31275 You must provide a definition file listing the exported entities
31276 (@pxref{The Definition File}).
31277
31278 @item
31279 Finally you must use @code{gnatdll} to produce the DLL and the import
31280 library (@pxref{Using gnatdll}).
31281 @end enumerate
31282
31283 @noindent
31284 Note that a relocatable DLL stripped using the @code{strip}
31285 binutils tool will not be relocatable anymore. To build a DLL without
31286 debug information pass @code{-largs -s} to @code{gnatdll}. This
31287 restriction does not apply to a DLL built using a Library Project.
31288 @pxref{Library Projects}.
31289
31290 @node Limitations When Using Ada DLLs from Ada
31291 @subsection Limitations When Using Ada DLLs from Ada
31292
31293 @noindent
31294 When using Ada DLLs from Ada applications there is a limitation users
31295 should be aware of. Because on Windows the GNAT run time is not in a DLL of
31296 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31297 each Ada DLL includes the services of the GNAT run time that are necessary
31298 to the Ada code inside the DLL. As a result, when an Ada program uses an
31299 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31300 one in the main program.
31301
31302 It is therefore not possible to exchange GNAT run-time objects between the
31303 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31304 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
31305 types, etc.
31306
31307 It is completely safe to exchange plain elementary, array or record types,
31308 Windows object handles, etc.
31309
31310 @node Exporting Ada Entities
31311 @subsection Exporting Ada Entities
31312 @cindex Export table
31313
31314 @noindent
31315 Building a DLL is a way to encapsulate a set of services usable from any
31316 application. As a result, the Ada entities exported by a DLL should be
31317 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
31318 any Ada name mangling. As an example here is an Ada package
31319 @code{API}, spec and body, exporting two procedures, a function, and a
31320 variable:
31321
31322 @smallexample @c ada
31323 @group
31324 @cartouche
31325 with Interfaces.C; use Interfaces;
31326 package API is
31327    Count : C.int := 0;
31328    function Factorial (Val : C.int) return C.int;
31329
31330    procedure Initialize_API;
31331    procedure Finalize_API;
31332    --  Initialization & Finalization routines. More in the next section.
31333 private
31334    pragma Export (C, Initialize_API);
31335    pragma Export (C, Finalize_API);
31336    pragma Export (C, Count);
31337    pragma Export (C, Factorial);
31338 end API;
31339 @end cartouche
31340 @end group
31341 @end smallexample
31342
31343 @smallexample @c ada
31344 @group
31345 @cartouche
31346 package body API is
31347    function Factorial (Val : C.int) return C.int is
31348       Fact : C.int := 1;
31349    begin
31350       Count := Count + 1;
31351       for K in 1 .. Val loop
31352          Fact := Fact * K;
31353       end loop;
31354       return Fact;
31355    end Factorial;
31356
31357    procedure Initialize_API is
31358       procedure Adainit;
31359       pragma Import (C, Adainit);
31360    begin
31361       Adainit;
31362    end Initialize_API;
31363
31364    procedure Finalize_API is
31365       procedure Adafinal;
31366       pragma Import (C, Adafinal);
31367    begin
31368       Adafinal;
31369    end Finalize_API;
31370 end API;
31371 @end cartouche
31372 @end group
31373 @end smallexample
31374
31375 @noindent
31376 If the Ada DLL you are building will only be used by Ada applications
31377 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
31378 convention. As an example, the previous package could be written as
31379 follows:
31380
31381 @smallexample @c ada
31382 @group
31383 @cartouche
31384 package API is
31385    Count : Integer := 0;
31386    function Factorial (Val : Integer) return Integer;
31387
31388    procedure Initialize_API;
31389    procedure Finalize_API;
31390    --  Initialization and Finalization routines.
31391 end API;
31392 @end cartouche
31393 @end group
31394 @end smallexample
31395
31396 @smallexample @c ada
31397 @group
31398 @cartouche
31399 package body API is
31400    function Factorial (Val : Integer) return Integer is
31401       Fact : Integer := 1;
31402    begin
31403       Count := Count + 1;
31404       for K in 1 .. Val loop
31405          Fact := Fact * K;
31406       end loop;
31407       return Fact;
31408    end Factorial;
31409
31410    @dots{}
31411    --  The remainder of this package body is unchanged.
31412 end API;
31413 @end cartouche
31414 @end group
31415 @end smallexample
31416
31417 @noindent
31418 Note that if you do not export the Ada entities with a @code{C} or
31419 @code{Stdcall} convention you will have to provide the mangled Ada names
31420 in the definition file of the Ada DLL
31421 (@pxref{Creating the Definition File}).
31422
31423 @node Ada DLLs and Elaboration
31424 @subsection Ada DLLs and Elaboration
31425 @cindex DLLs and elaboration
31426
31427 @noindent
31428 The DLL that you are building contains your Ada code as well as all the
31429 routines in the Ada library that are needed by it. The first thing a
31430 user of your DLL must do is elaborate the Ada code
31431 (@pxref{Elaboration Order Handling in GNAT}).
31432
31433 To achieve this you must export an initialization routine
31434 (@code{Initialize_API} in the previous example), which must be invoked
31435 before using any of the DLL services. This elaboration routine must call
31436 the Ada elaboration routine @code{adainit} generated by the GNAT binder
31437 (@pxref{Binding with Non-Ada Main Programs}). See the body of
31438 @code{Initialize_Api} for an example. Note that the GNAT binder is
31439 automatically invoked during the DLL build process by the @code{gnatdll}
31440 tool (@pxref{Using gnatdll}).
31441
31442 When a DLL is loaded, Windows systematically invokes a routine called
31443 @code{DllMain}. It would therefore be possible to call @code{adainit}
31444 directly from @code{DllMain} without having to provide an explicit
31445 initialization routine. Unfortunately, it is not possible to call
31446 @code{adainit} from the @code{DllMain} if your program has library level
31447 tasks because access to the @code{DllMain} entry point is serialized by
31448 the system (that is, only a single thread can execute ``through'' it at a
31449 time), which means that the GNAT run time will deadlock waiting for the
31450 newly created task to complete its initialization.
31451
31452 @node Ada DLLs and Finalization
31453 @subsection Ada DLLs and Finalization
31454 @cindex DLLs and finalization
31455
31456 @noindent
31457 When the services of an Ada DLL are no longer needed, the client code should
31458 invoke the DLL finalization routine, if available. The DLL finalization
31459 routine is in charge of releasing all resources acquired by the DLL. In the
31460 case of the Ada code contained in the DLL, this is achieved by calling
31461 routine @code{adafinal} generated by the GNAT binder
31462 (@pxref{Binding with Non-Ada Main Programs}).
31463 See the body of @code{Finalize_Api} for an
31464 example. As already pointed out the GNAT binder is automatically invoked
31465 during the DLL build process by the @code{gnatdll} tool
31466 (@pxref{Using gnatdll}).
31467
31468 @node Creating a Spec for Ada DLLs
31469 @subsection Creating a Spec for Ada DLLs
31470
31471 @noindent
31472 To use the services exported by the Ada DLL from another programming
31473 language (e.g.@: C), you have to translate the specs of the exported Ada
31474 entities in that language. For instance in the case of @code{API.dll},
31475 the corresponding C header file could look like:
31476
31477 @smallexample
31478 @group
31479 @cartouche
31480 extern int *_imp__count;
31481 #define count (*_imp__count)
31482 int factorial (int);
31483 @end cartouche
31484 @end group
31485 @end smallexample
31486
31487 @noindent
31488 It is important to understand that when building an Ada DLL to be used by
31489 other Ada applications, you need two different specs for the packages
31490 contained in the DLL: one for building the DLL and the other for using
31491 the DLL. This is because the @code{DLL} calling convention is needed to
31492 use a variable defined in a DLL, but when building the DLL, the variable
31493 must have either the @code{Ada} or @code{C} calling convention. As an
31494 example consider a DLL comprising the following package @code{API}:
31495
31496 @smallexample @c ada
31497 @group
31498 @cartouche
31499 package API is
31500    Count : Integer := 0;
31501    @dots{}
31502    --  Remainder of the package omitted.
31503 end API;
31504 @end cartouche
31505 @end group
31506 @end smallexample
31507
31508 @noindent
31509 After producing a DLL containing package @code{API}, the spec that
31510 must be used to import @code{API.Count} from Ada code outside of the
31511 DLL is:
31512
31513 @smallexample @c ada
31514 @group
31515 @cartouche
31516 package API is
31517    Count : Integer;
31518    pragma Import (DLL, Count);
31519 end API;
31520 @end cartouche
31521 @end group
31522 @end smallexample
31523
31524 @node Creating the Definition File
31525 @subsection Creating the Definition File
31526
31527 @noindent
31528 The definition file is the last file needed to build the DLL. It lists
31529 the exported symbols. As an example, the definition file for a DLL
31530 containing only package @code{API} (where all the entities are exported
31531 with a @code{C} calling convention) is:
31532
31533 @smallexample
31534 @group
31535 @cartouche
31536 EXPORTS
31537     count
31538     factorial
31539     finalize_api
31540     initialize_api
31541 @end cartouche
31542 @end group
31543 @end smallexample
31544
31545 @noindent
31546 If the @code{C} calling convention is missing from package @code{API},
31547 then the definition file contains the mangled Ada names of the above
31548 entities, which in this case are:
31549
31550 @smallexample
31551 @group
31552 @cartouche
31553 EXPORTS
31554     api__count
31555     api__factorial
31556     api__finalize_api
31557     api__initialize_api
31558 @end cartouche
31559 @end group
31560 @end smallexample
31561
31562 @node Using gnatdll
31563 @subsection Using @code{gnatdll}
31564 @findex gnatdll
31565
31566 @menu
31567 * gnatdll Example::
31568 * gnatdll behind the Scenes::
31569 * Using dlltool::
31570 @end menu
31571
31572 @noindent
31573 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31574 and non-Ada sources that make up your DLL have been compiled.
31575 @code{gnatdll} is actually in charge of two distinct tasks: build the
31576 static import library for the DLL and the actual DLL. The form of the
31577 @code{gnatdll} command is
31578
31579 @smallexample
31580 @cartouche
31581 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31582 @c Expanding @ovar macro inline (explanation in macro def comments)
31583 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31584 @end cartouche
31585 @end smallexample
31586
31587 @noindent
31588 where @var{list-of-files} is a list of ALI and object files. The object
31589 file list must be the exact list of objects corresponding to the non-Ada
31590 sources whose services are to be included in the DLL. The ALI file list
31591 must be the exact list of ALI files for the corresponding Ada sources
31592 whose services are to be included in the DLL. If @var{list-of-files} is
31593 missing, only the static import library is generated.
31594
31595 @noindent
31596 You may specify any of the following switches to @code{gnatdll}:
31597
31598 @table @code
31599 @c @item -a@ovar{address}
31600 @c Expanding @ovar macro inline (explanation in macro def comments)
31601 @item -a@r{[}@var{address}@r{]}
31602 @cindex @option{-a} (@code{gnatdll})
31603 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31604 specified the default address @var{0x11000000} will be used. By default,
31605 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31606 advise the reader to build relocatable DLL.
31607
31608 @item -b @var{address}
31609 @cindex @option{-b} (@code{gnatdll})
31610 Set the relocatable DLL base address. By default the address is
31611 @code{0x11000000}.
31612
31613 @item -bargs @var{opts}
31614 @cindex @option{-bargs} (@code{gnatdll})
31615 Binder options. Pass @var{opts} to the binder.
31616
31617 @item -d @var{dllfile}
31618 @cindex @option{-d} (@code{gnatdll})
31619 @var{dllfile} is the name of the DLL. This switch must be present for
31620 @code{gnatdll} to do anything. The name of the generated import library is
31621 obtained algorithmically from @var{dllfile} as shown in the following
31622 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31623 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31624 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31625 as shown in the following example:
31626 if @var{dllfile} is @code{xyz.dll}, the definition
31627 file used is @code{xyz.def}.
31628
31629 @item -e @var{deffile}
31630 @cindex @option{-e} (@code{gnatdll})
31631 @var{deffile} is the name of the definition file.
31632
31633 @item -g
31634 @cindex @option{-g} (@code{gnatdll})
31635 Generate debugging information. This information is stored in the object
31636 file and copied from there to the final DLL file by the linker,
31637 where it can be read by the debugger. You must use the
31638 @option{-g} switch if you plan on using the debugger or the symbolic
31639 stack traceback.
31640
31641 @item -h
31642 @cindex @option{-h} (@code{gnatdll})
31643 Help mode. Displays @code{gnatdll} switch usage information.
31644
31645 @item -Idir
31646 @cindex @option{-I} (@code{gnatdll})
31647 Direct @code{gnatdll} to search the @var{dir} directory for source and
31648 object files needed to build the DLL.
31649 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31650
31651 @item -k
31652 @cindex @option{-k} (@code{gnatdll})
31653 Removes the @code{@@}@var{nn} suffix from the import library's exported
31654 names, but keeps them for the link names. You must specify this
31655 option if you want to use a @code{Stdcall} function in a DLL for which
31656 the @code{@@}@var{nn} suffix has been removed. This is the case for most
31657 of the Windows NT DLL for example. This option has no effect when
31658 @option{-n} option is specified.
31659
31660 @item -l @var{file}
31661 @cindex @option{-l} (@code{gnatdll})
31662 The list of ALI and object files used to build the DLL are listed in
31663 @var{file}, instead of being given in the command line. Each line in
31664 @var{file} contains the name of an ALI or object file.
31665
31666 @item -n
31667 @cindex @option{-n} (@code{gnatdll})
31668 No Import. Do not create the import library.
31669
31670 @item -q
31671 @cindex @option{-q} (@code{gnatdll})
31672 Quiet mode. Do not display unnecessary messages.
31673
31674 @item -v
31675 @cindex @option{-v} (@code{gnatdll})
31676 Verbose mode. Display extra information.
31677
31678 @item -largs @var{opts}
31679 @cindex @option{-largs} (@code{gnatdll})
31680 Linker options. Pass @var{opts} to the linker.
31681 @end table
31682
31683 @node gnatdll Example
31684 @subsubsection @code{gnatdll} Example
31685
31686 @noindent
31687 As an example the command to build a relocatable DLL from @file{api.adb}
31688 once @file{api.adb} has been compiled and @file{api.def} created is
31689
31690 @smallexample
31691 $ gnatdll -d api.dll api.ali
31692 @end smallexample
31693
31694 @noindent
31695 The above command creates two files: @file{libapi.dll.a} (the import
31696 library) and @file{api.dll} (the actual DLL). If you want to create
31697 only the DLL, just type:
31698
31699 @smallexample
31700 $ gnatdll -d api.dll -n api.ali
31701 @end smallexample
31702
31703 @noindent
31704 Alternatively if you want to create just the import library, type:
31705
31706 @smallexample
31707 $ gnatdll -d api.dll
31708 @end smallexample
31709
31710 @node gnatdll behind the Scenes
31711 @subsubsection @code{gnatdll} behind the Scenes
31712
31713 @noindent
31714 This section details the steps involved in creating a DLL. @code{gnatdll}
31715 does these steps for you. Unless you are interested in understanding what
31716 goes on behind the scenes, you should skip this section.
31717
31718 We use the previous example of a DLL containing the Ada package @code{API},
31719 to illustrate the steps necessary to build a DLL. The starting point is a
31720 set of objects that will make up the DLL and the corresponding ALI
31721 files. In the case of this example this means that @file{api.o} and
31722 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31723 the following:
31724
31725 @enumerate
31726 @item
31727 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31728 the information necessary to generate relocation information for the
31729 DLL.
31730
31731 @smallexample
31732 @group
31733 $ gnatbind -n api
31734 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31735 @end group
31736 @end smallexample
31737
31738 @noindent
31739 In addition to the base file, the @command{gnatlink} command generates an
31740 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31741 asks @command{gnatlink} to generate the routines @code{DllMain} and
31742 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31743 is loaded into memory.
31744
31745 @item
31746 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31747 export table (@file{api.exp}). The export table contains the relocation
31748 information in a form which can be used during the final link to ensure
31749 that the Windows loader is able to place the DLL anywhere in memory.
31750
31751 @smallexample
31752 @group
31753 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31754           --output-exp api.exp
31755 @end group
31756 @end smallexample
31757
31758 @item
31759 @code{gnatdll} builds the base file using the new export table. Note that
31760 @command{gnatbind} must be called once again since the binder generated file
31761 has been deleted during the previous call to @command{gnatlink}.
31762
31763 @smallexample
31764 @group
31765 $ gnatbind -n api
31766 $ gnatlink api -o api.jnk api.exp -mdll
31767       -Wl,--base-file,api.base
31768 @end group
31769 @end smallexample
31770
31771 @item
31772 @code{gnatdll} builds the new export table using the new base file and
31773 generates the DLL import library @file{libAPI.dll.a}.
31774
31775 @smallexample
31776 @group
31777 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31778           --output-exp api.exp --output-lib libAPI.a
31779 @end group
31780 @end smallexample
31781
31782 @item
31783 Finally @code{gnatdll} builds the relocatable DLL using the final export
31784 table.
31785
31786 @smallexample
31787 @group
31788 $ gnatbind -n api
31789 $ gnatlink api api.exp -o api.dll -mdll
31790 @end group
31791 @end smallexample
31792 @end enumerate
31793
31794 @node Using dlltool
31795 @subsubsection Using @code{dlltool}
31796
31797 @noindent
31798 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31799 DLLs and static import libraries. This section summarizes the most
31800 common @code{dlltool} switches. The form of the @code{dlltool} command
31801 is
31802
31803 @smallexample
31804 @c $ dlltool @ovar{switches}
31805 @c Expanding @ovar macro inline (explanation in macro def comments)
31806 $ dlltool @r{[}@var{switches}@r{]}
31807 @end smallexample
31808
31809 @noindent
31810 @code{dlltool} switches include:
31811
31812 @table @option
31813 @item --base-file @var{basefile}
31814 @cindex @option{--base-file} (@command{dlltool})
31815 Read the base file @var{basefile} generated by the linker. This switch
31816 is used to create a relocatable DLL.
31817
31818 @item --def @var{deffile}
31819 @cindex @option{--def} (@command{dlltool})
31820 Read the definition file.
31821
31822 @item --dllname @var{name}
31823 @cindex @option{--dllname} (@command{dlltool})
31824 Gives the name of the DLL. This switch is used to embed the name of the
31825 DLL in the static import library generated by @code{dlltool} with switch
31826 @option{--output-lib}.
31827
31828 @item -k
31829 @cindex @option{-k} (@command{dlltool})
31830 Kill @code{@@}@var{nn} from exported names
31831 (@pxref{Windows Calling Conventions}
31832 for a discussion about @code{Stdcall}-style symbols.
31833
31834 @item --help
31835 @cindex @option{--help} (@command{dlltool})
31836 Prints the @code{dlltool} switches with a concise description.
31837
31838 @item --output-exp @var{exportfile}
31839 @cindex @option{--output-exp} (@command{dlltool})
31840 Generate an export file @var{exportfile}. The export file contains the
31841 export table (list of symbols in the DLL) and is used to create the DLL.
31842
31843 @item --output-lib @var{libfile}
31844 @cindex @option{--output-lib} (@command{dlltool})
31845 Generate a static import library @var{libfile}.
31846
31847 @item -v
31848 @cindex @option{-v} (@command{dlltool})
31849 Verbose mode.
31850
31851 @item --as @var{assembler-name}
31852 @cindex @option{--as} (@command{dlltool})
31853 Use @var{assembler-name} as the assembler. The default is @code{as}.
31854 @end table
31855
31856 @node GNAT and Windows Resources
31857 @section GNAT and Windows Resources
31858 @cindex Resources, windows
31859
31860 @menu
31861 * Building Resources::
31862 * Compiling Resources::
31863 * Using Resources::
31864 @end menu
31865
31866 @noindent
31867 Resources are an easy way to add Windows specific objects to your
31868 application. The objects that can be added as resources include:
31869
31870 @itemize @bullet
31871 @item
31872 menus
31873
31874 @item
31875 accelerators
31876
31877 @item
31878 dialog boxes
31879
31880 @item
31881 string tables
31882
31883 @item
31884 bitmaps
31885
31886 @item
31887 cursors
31888
31889 @item
31890 icons
31891
31892 @item
31893 fonts
31894 @end itemize
31895
31896 @noindent
31897 This section explains how to build, compile and use resources.
31898
31899 @node Building Resources
31900 @subsection Building Resources
31901 @cindex Resources, building
31902
31903 @noindent
31904 A resource file is an ASCII file. By convention resource files have an
31905 @file{.rc} extension.
31906 The easiest way to build a resource file is to use Microsoft tools
31907 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31908 @code{dlgedit.exe} to build dialogs.
31909 It is always possible to build an @file{.rc} file yourself by writing a
31910 resource script.
31911
31912 It is not our objective to explain how to write a resource file. A
31913 complete description of the resource script language can be found in the
31914 Microsoft documentation.
31915
31916 @node Compiling Resources
31917 @subsection Compiling Resources
31918 @findex rc
31919 @findex windres
31920 @cindex Resources, compiling
31921
31922 @noindent
31923 This section describes how to build a GNAT-compatible (COFF) object file
31924 containing the resources. This is done using the Resource Compiler
31925 @code{windres} as follows:
31926
31927 @smallexample
31928 $ windres -i myres.rc -o myres.o
31929 @end smallexample
31930
31931 @noindent
31932 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31933 file. You can specify an alternate preprocessor (usually named
31934 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31935 parameter. A list of all possible options may be obtained by entering
31936 the command @code{windres} @option{--help}.
31937
31938 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31939 to produce a @file{.res} file (binary resource file). See the
31940 corresponding Microsoft documentation for further details. In this case
31941 you need to use @code{windres} to translate the @file{.res} file to a
31942 GNAT-compatible object file as follows:
31943
31944 @smallexample
31945 $ windres -i myres.res -o myres.o
31946 @end smallexample
31947
31948 @node Using Resources
31949 @subsection Using Resources
31950 @cindex Resources, using
31951
31952 @noindent
31953 To include the resource file in your program just add the
31954 GNAT-compatible object file for the resource(s) to the linker
31955 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31956 option:
31957
31958 @smallexample
31959 $ gnatmake myprog -largs myres.o
31960 @end smallexample
31961
31962 @node Debugging a DLL
31963 @section Debugging a DLL
31964 @cindex DLL debugging
31965
31966 @menu
31967 * Program and DLL Both Built with GCC/GNAT::
31968 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31969 @end menu
31970
31971 @noindent
31972 Debugging a DLL is similar to debugging a standard program. But
31973 we have to deal with two different executable parts: the DLL and the
31974 program that uses it. We have the following four possibilities:
31975
31976 @enumerate 1
31977 @item
31978 The program and the DLL are built with @code{GCC/GNAT}.
31979 @item
31980 The program is built with foreign tools and the DLL is built with
31981 @code{GCC/GNAT}.
31982 @item
31983 The program is built with @code{GCC/GNAT} and the DLL is built with
31984 foreign tools.
31985 @item
31986 @end enumerate
31987
31988 @noindent
31989 In this section we address only cases one and two above.
31990 There is no point in trying to debug
31991 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31992 information in it. To do so you must use a debugger compatible with the
31993 tools suite used to build the DLL.
31994
31995 @node Program and DLL Both Built with GCC/GNAT
31996 @subsection Program and DLL Both Built with GCC/GNAT
31997
31998 @noindent
31999 This is the simplest case. Both the DLL and the program have @code{GDB}
32000 compatible debugging information. It is then possible to break anywhere in
32001 the process. Let's suppose here that the main procedure is named
32002 @code{ada_main} and that in the DLL there is an entry point named
32003 @code{ada_dll}.
32004
32005 @noindent
32006 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32007 program must have been built with the debugging information (see GNAT -g
32008 switch). Here are the step-by-step instructions for debugging it:
32009
32010 @enumerate 1
32011 @item Launch @code{GDB} on the main program.
32012
32013 @smallexample
32014 $ gdb -nw ada_main
32015 @end smallexample
32016
32017 @item Start the program and stop at the beginning of the main procedure
32018
32019 @smallexample
32020 (gdb) start
32021 @end smallexample
32022
32023 @noindent
32024 This step is required to be able to set a breakpoint inside the DLL. As long
32025 as the program is not run, the DLL is not loaded. This has the
32026 consequence that the DLL debugging information is also not loaded, so it is not
32027 possible to set a breakpoint in the DLL.
32028
32029 @item Set a breakpoint inside the DLL
32030
32031 @smallexample
32032 (gdb) break ada_dll
32033 (gdb) cont
32034 @end smallexample
32035
32036 @end enumerate
32037
32038 @noindent
32039 At this stage a breakpoint is set inside the DLL. From there on
32040 you can use the standard approach to debug the whole program
32041 (@pxref{Running and Debugging Ada Programs}).
32042
32043 @ignore
32044 @c This used to work, probably because the DLLs were non-relocatable
32045 @c keep this section around until the problem is sorted out.
32046
32047 To break on the @code{DllMain} routine it is not possible to follow
32048 the procedure above. At the time the program stop on @code{ada_main}
32049 the @code{DllMain} routine as already been called. Either you can use
32050 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32051
32052 @enumerate 1
32053 @item Launch @code{GDB} on the main program.
32054
32055 @smallexample
32056 $ gdb ada_main
32057 @end smallexample
32058
32059 @item Load DLL symbols
32060
32061 @smallexample
32062 (gdb) add-sym api.dll
32063 @end smallexample
32064
32065 @item Set a breakpoint inside the DLL
32066
32067 @smallexample
32068 (gdb) break ada_dll.adb:45
32069 @end smallexample
32070
32071 Note that at this point it is not possible to break using the routine symbol
32072 directly as the program is not yet running. The solution is to break
32073 on the proper line (break in @file{ada_dll.adb} line 45).
32074
32075 @item Start the program
32076
32077 @smallexample
32078 (gdb) run
32079 @end smallexample
32080
32081 @end enumerate
32082 @end ignore
32083
32084 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32085 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32086
32087 @menu
32088 * Debugging the DLL Directly::
32089 * Attaching to a Running Process::
32090 @end menu
32091
32092 @noindent
32093 In this case things are slightly more complex because it is not possible to
32094 start the main program and then break at the beginning to load the DLL and the
32095 associated DLL debugging information. It is not possible to break at the
32096 beginning of the program because there is no @code{GDB} debugging information,
32097 and therefore there is no direct way of getting initial control. This
32098 section addresses this issue by describing some methods that can be used
32099 to break somewhere in the DLL to debug it.
32100
32101 @noindent
32102 First suppose that the main procedure is named @code{main} (this is for
32103 example some C code built with Microsoft Visual C) and that there is a
32104 DLL named @code{test.dll} containing an Ada entry point named
32105 @code{ada_dll}.
32106
32107 @noindent
32108 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32109 been built with debugging information (see GNAT -g option).
32110
32111 @node Debugging the DLL Directly
32112 @subsubsection Debugging the DLL Directly
32113
32114 @enumerate 1
32115 @item
32116 Find out the executable starting address
32117
32118 @smallexample
32119 $ objdump --file-header main.exe
32120 @end smallexample
32121
32122 The starting address is reported on the last line. For example:
32123
32124 @smallexample
32125 main.exe:     file format pei-i386
32126 architecture: i386, flags 0x0000010a:
32127 EXEC_P, HAS_DEBUG, D_PAGED
32128 start address 0x00401010
32129 @end smallexample
32130
32131 @item
32132 Launch the debugger on the executable.
32133
32134 @smallexample
32135 $ gdb main.exe
32136 @end smallexample
32137
32138 @item
32139 Set a breakpoint at the starting address, and launch the program.
32140
32141 @smallexample
32142 $ (gdb) break *0x00401010
32143 $ (gdb) run
32144 @end smallexample
32145
32146 The program will stop at the given address.
32147
32148 @item
32149 Set a breakpoint on a DLL subroutine.
32150
32151 @smallexample
32152 (gdb) break ada_dll.adb:45
32153 @end smallexample
32154
32155 Or if you want to break using a symbol on the DLL, you need first to
32156 select the Ada language (language used by the DLL).
32157
32158 @smallexample
32159 (gdb) set language ada
32160 (gdb) break ada_dll
32161 @end smallexample
32162
32163 @item
32164 Continue the program.
32165
32166 @smallexample
32167 (gdb) cont
32168 @end smallexample
32169
32170 @noindent
32171 This will run the program until it reaches the breakpoint that has been
32172 set. From that point you can use the standard way to debug a program
32173 as described in (@pxref{Running and Debugging Ada Programs}).
32174
32175 @end enumerate
32176
32177 @noindent
32178 It is also possible to debug the DLL by attaching to a running process.
32179
32180 @node Attaching to a Running Process
32181 @subsubsection Attaching to a Running Process
32182 @cindex DLL debugging, attach to process
32183
32184 @noindent
32185 With @code{GDB} it is always possible to debug a running process by
32186 attaching to it. It is possible to debug a DLL this way. The limitation
32187 of this approach is that the DLL must run long enough to perform the
32188 attach operation. It may be useful for instance to insert a time wasting
32189 loop in the code of the DLL to meet this criterion.
32190
32191 @enumerate 1
32192
32193 @item Launch the main program @file{main.exe}.
32194
32195 @smallexample
32196 $ main
32197 @end smallexample
32198
32199 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
32200 that the process PID for @file{main.exe} is 208.
32201
32202 @item Launch gdb.
32203
32204 @smallexample
32205 $ gdb
32206 @end smallexample
32207
32208 @item Attach to the running process to be debugged.
32209
32210 @smallexample
32211 (gdb) attach 208
32212 @end smallexample
32213
32214 @item Load the process debugging information.
32215
32216 @smallexample
32217 (gdb) symbol-file main.exe
32218 @end smallexample
32219
32220 @item Break somewhere in the DLL.
32221
32222 @smallexample
32223 (gdb) break ada_dll
32224 @end smallexample
32225
32226 @item Continue process execution.
32227
32228 @smallexample
32229 (gdb) cont
32230 @end smallexample
32231
32232 @end enumerate
32233
32234 @noindent
32235 This last step will resume the process execution, and stop at
32236 the breakpoint we have set. From there you can use the standard
32237 approach to debug a program as described in
32238 (@pxref{Running and Debugging Ada Programs}).
32239
32240 @node Setting Stack Size from gnatlink
32241 @section Setting Stack Size from @command{gnatlink}
32242
32243 @noindent
32244 It is possible to specify the program stack size at link time. On modern
32245 versions of Windows, starting with XP, this is mostly useful to set the size of
32246 the main stack (environment task). The other task stacks are set with pragma
32247 Storage_Size or with the @command{gnatbind -d} command.
32248
32249 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32250 reserve size of individual tasks, the link-time stack size applies to all
32251 tasks, and pragma Storage_Size has no effect.
32252 In particular, Stack Overflow checks are made against this
32253 link-time specified size.
32254
32255 This setting can be done with
32256 @command{gnatlink} using either:
32257
32258 @itemize @bullet
32259
32260 @item using @option{-Xlinker} linker option
32261
32262 @smallexample
32263 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
32264 @end smallexample
32265
32266 This sets the stack reserve size to 0x10000 bytes and the stack commit
32267 size to 0x1000 bytes.
32268
32269 @item using @option{-Wl} linker option
32270
32271 @smallexample
32272 $ gnatlink hello -Wl,--stack=0x1000000
32273 @end smallexample
32274
32275 This sets the stack reserve size to 0x1000000 bytes. Note that with
32276 @option{-Wl} option it is not possible to set the stack commit size
32277 because the coma is a separator for this option.
32278
32279 @end itemize
32280
32281 @node Setting Heap Size from gnatlink
32282 @section Setting Heap Size from @command{gnatlink}
32283
32284 @noindent
32285 Under Windows systems, it is possible to specify the program heap size from
32286 @command{gnatlink} using either:
32287
32288 @itemize @bullet
32289
32290 @item using @option{-Xlinker} linker option
32291
32292 @smallexample
32293 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
32294 @end smallexample
32295
32296 This sets the heap reserve size to 0x10000 bytes and the heap commit
32297 size to 0x1000 bytes.
32298
32299 @item using @option{-Wl} linker option
32300
32301 @smallexample
32302 $ gnatlink hello -Wl,--heap=0x1000000
32303 @end smallexample
32304
32305 This sets the heap reserve size to 0x1000000 bytes. Note that with
32306 @option{-Wl} option it is not possible to set the heap commit size
32307 because the coma is a separator for this option.
32308
32309 @end itemize
32310
32311 @end ifset
32312
32313 @c **********************************
32314 @c * GNU Free Documentation License *
32315 @c **********************************
32316 @include fdl.texi
32317 @c GNU Free Documentation License
32318
32319 @node Index,,GNU Free Documentation License, Top
32320 @unnumbered Index
32321
32322 @printindex cp
32323
32324 @contents
32325 @c Put table of contents at end, otherwise it precedes the "title page" in
32326 @c the .txt version
32327 @c Edit the pdf file to move the contents to the beginning, after the title
32328 @c page
32329
32330 @bye