OSDN Git Service

2006-10-31 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c                     Copyright (C) 1992-2006, AdaCore                       o
11 @c                                                                            o
12 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
13 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
14 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
15 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
16 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
17 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
18 @c  for  more details.  You should have  received  a copy of the GNU General  o
19 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
20 @c  to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor,  o
21 @c  Boston, MA 02110-1301, USA.                                               o
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
24
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
26 @c
27 @c                           GNAT_UGN Style Guide
28 @c
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
31 @c
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
37 @c
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
41 @c
42 @c  2. DO NOT use @example. Use @smallexample instead.
43 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c        context.  These can interfere with the readability of the texi
45 @c        source file.  Instead, use one of the following annotated
46 @c        @smallexample commands, and preprocess the texi file with the
47 @c        ada2texi tool (which generates appropriate highlighting):
48 @c        @smallexample @c ada
49 @c        @smallexample @c adanocomment
50 @c        @smallexample @c projectfile
51 @c     b) The "@c ada" markup will result in boldface for reserved words
52 @c        and italics for comments
53 @c     c) The "@c adanocomment" markup will result only in boldface for
54 @c        reserved words (comments are left alone)
55 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c        of reserved words include the new reserved words for project files
57 @c
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
60 @c
61 @c  4. The @item command should be on a line of its own if it is in an
62 @c     @itemize or @enumerate command.
63 @c
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
66 @c
67 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
68 @c     cause the document build to fail.
69 @c
70 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c     This command inhibits page breaks, so long examples in a @cartouche can
72 @c     lead to large, ugly patches of empty space on a page.
73 @c
74 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c        or the unw flag set.  The unw flag covers topics for both Unix and
76 @c        Windows.
77 @c
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
79
80 @ifset vms
81 @setfilename gnat_ugn_vms.info
82 @end ifset
83
84 @ifset unw
85 @setfilename gnat_ugn_unw.info
86 @end ifset
87
88 @set FSFEDITION
89 @set EDITION GNAT
90
91 @ifset unw
92 @set PLATFORM
93 @set FILE gnat_ugn_unw
94 @end ifset
95
96 @ifset vms
97 @set PLATFORM OpenVMS
98 @set FILE gnat_ugn_vms
99 @end ifset
100
101 @settitle @value{EDITION} User's Guide @value{PLATFORM}
102 @dircategory GNU Ada tools
103 @direntry
104 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
105 @end direntry
106
107 @include gcc-common.texi
108
109 @setchapternewpage odd
110 @syncodeindex fn cp
111 @c %**end of header
112
113 @copying
114 Copyright @copyright{} 1995-2005, Free Software Foundation
115
116 Permission is granted to copy, distribute and/or modify this document
117 under the terms of the GNU Free Documentation License, Version 1.2
118 or any later version published by the Free Software Foundation;
119 with the Invariant Sections being ``GNU Free Documentation License'', with the
120 Front-Cover Texts being
121 ``@value{EDITION} User's Guide'',
122 and with no Back-Cover Texts.
123 A copy of the license is included in the section entitled
124 ``GNU Free Documentation License''.
125 @end copying
126
127 @titlepage
128
129 @title @value{EDITION} User's Guide
130
131 @ifset vms
132 @sp 1
133 @flushright
134 @titlefont{@i{@value{PLATFORM}}}
135 @end flushright
136 @end ifset
137
138 @sp 2
139
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
142
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 95 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 * Other Utility Programs::
198 * Running and Debugging Ada Programs::
199 @ifset vms
200 * Compatibility with HP Ada::
201 @end ifset
202 * Platform-Specific Information for the Run-Time Libraries::
203 * Example of Binder Output File::
204 * Elaboration Order Handling in GNAT::
205 * Inline Assembler::
206 * Compatibility and Porting Guide::
207 @ifset unw
208 * Microsoft Windows Topics::
209 @end ifset
210 * GNU Free Documentation License::
211 * Index::
212
213  --- The Detailed Node Listing ---
214
215 About This Guide
216
217 * What This Guide Contains::
218 * What You Should Know before Reading This Guide::
219 * Related Information::
220 * Conventions::
221
222 Getting Started with GNAT
223
224 * Running GNAT::
225 * Running a Simple Ada Program::
226 * Running a Program with Multiple Units::
227 * Using the gnatmake Utility::
228 @ifset vms
229 * Editing with Emacs::
230 @end ifset
231 @ifclear vms
232 * Introduction to GPS::
233 * Introduction to Glide and GVD::
234 @end ifclear
235
236 The GNAT Compilation Model
237
238 * Source Representation::
239 * Foreign Language Representation::
240 * File Naming Rules::
241 * Using Other File Names::
242 * Alternative File Naming Schemes::
243 * Generating Object Files::
244 * Source Dependencies::
245 * The Ada Library Information Files::
246 * Binding an Ada Program::
247 * Mixed Language Programming::
248 @ifclear vms
249 * Building Mixed Ada & C++ Programs::
250 * Comparison between GNAT and C/C++ Compilation Models::
251 @end ifclear
252 * Comparison between GNAT and Conventional Ada Library Models::
253 @ifset vms
254 * Placement of temporary files::
255 @end ifset
256
257 Foreign Language Representation
258
259 * Latin-1::
260 * Other 8-Bit Codes::
261 * Wide Character Encodings::
262
263 Compiling Ada Programs With gcc
264
265 * Compiling Programs::
266 * Switches for gcc::
267 * Search Paths and the Run-Time Library (RTL)::
268 * Order of Compilation Issues::
269 * Examples::
270
271 Switches for gcc
272
273 * Output and Error Message Control::
274 * Warning Message Control::
275 * Debugging and Assertion Control::
276 * Validity Checking::
277 * Style Checking::
278 * Run-Time Checks::
279 * Using gcc for Syntax Checking::
280 * Using gcc for Semantic Checking::
281 * Compiling Different Versions of Ada::
282 * Character Set Control::
283 * File Naming Control::
284 * Subprogram Inlining Control::
285 * Auxiliary Output Control::
286 * Debugging Control::
287 * Exception Handling Control::
288 * Units to Sources Mapping Files::
289 * Integrated Preprocessing::
290 @ifset vms
291 * Return Codes::
292 @end ifset
293
294 Binding Ada Programs With gnatbind
295
296 * Running gnatbind::
297 * Switches for gnatbind::
298 * Command-Line Access::
299 * Search Paths for gnatbind::
300 * Examples of gnatbind Usage::
301
302 Switches for gnatbind
303
304 * Consistency-Checking Modes::
305 * Binder Error Message Control::
306 * Elaboration Control::
307 * Output Control::
308 * Binding with Non-Ada Main Programs::
309 * Binding Programs with No Main Subprogram::
310
311 Linking Using gnatlink
312
313 * Running gnatlink::
314 * Switches for gnatlink::
315
316 The GNAT Make Program gnatmake
317
318 * Running gnatmake::
319 * Switches for gnatmake::
320 * Mode Switches for gnatmake::
321 * Notes on the Command Line::
322 * How gnatmake Works::
323 * Examples of gnatmake Usage::
324
325 Improving Performance
326 * Performance Considerations::
327 * Reducing Size of Ada Executables with gnatelim::
328 * Reducing Size of Executables with unused subprogram/data elimination::
329
330 Performance Considerations
331 * Controlling Run-Time Checks::
332 * Use of Restrictions::
333 * Optimization Levels::
334 * Debugging Optimized Code::
335 * Inlining of Subprograms::
336 * Other Optimization Switches::
337 * Optimization and Strict Aliasing::
338 @ifset vms
339 * Coverage Analysis::
340 @end ifset
341
342 Reducing Size of Ada Executables with gnatelim
343 * About gnatelim::
344 * Running gnatelim::
345 * Correcting the List of Eliminate Pragmas::
346 * Making Your Executables Smaller::
347 * Summary of the gnatelim Usage Cycle::
348
349 Reducing Size of Executables with unused subprogram/data elimination
350 * About unused subprogram/data elimination::
351 * Compilation options::
352
353 Renaming Files Using gnatchop
354
355 * Handling Files with Multiple Units::
356 * Operating gnatchop in Compilation Mode::
357 * Command Line for gnatchop::
358 * Switches for gnatchop::
359 * Examples of gnatchop Usage::
360
361 Configuration Pragmas
362
363 * Handling of Configuration Pragmas::
364 * The Configuration Pragmas Files::
365
366 Handling Arbitrary File Naming Conventions Using gnatname
367
368 * Arbitrary File Naming Conventions::
369 * Running gnatname::
370 * Switches for gnatname::
371 * Examples of gnatname Usage::
372
373 GNAT Project Manager
374
375 * Introduction::
376 * Examples of Project Files::
377 * Project File Syntax::
378 * Objects and Sources in Project Files::
379 * Importing Projects::
380 * Project Extension::
381 * Project Hierarchy Extension::
382 * External References in Project Files::
383 * Packages in Project Files::
384 * Variables from Imported Projects::
385 * Naming Schemes::
386 * Library Projects::
387 * Stand-alone Library Projects::
388 * Switches Related to Project Files::
389 * Tools Supporting Project Files::
390 * An Extended Example::
391 * Project File Complete Syntax::
392
393 The Cross-Referencing Tools gnatxref and gnatfind
394
395 * gnatxref Switches::
396 * gnatfind Switches::
397 * Project Files for gnatxref and gnatfind::
398 * Regular Expressions in gnatfind and gnatxref::
399 * Examples of gnatxref Usage::
400 * Examples of gnatfind Usage::
401
402 The GNAT Pretty-Printer gnatpp
403
404 * Switches for gnatpp::
405 * Formatting Rules::
406
407 The GNAT Metrics Tool gnatmetric
408
409 * Switches for gnatmetric::
410
411 File Name Krunching Using gnatkr
412
413 * About gnatkr::
414 * Using gnatkr::
415 * Krunching Method::
416 * Examples of gnatkr Usage::
417
418 Preprocessing Using gnatprep
419
420 * Using gnatprep::
421 * Switches for gnatprep::
422 * Form of Definitions File::
423 * Form of Input Text for gnatprep::
424
425 @ifset vms
426 The GNAT Run-Time Library Builder gnatlbr
427
428 * Running gnatlbr::
429 * Switches for gnatlbr::
430 * Examples of gnatlbr Usage::
431 @end ifset
432
433 The GNAT Library Browser gnatls
434
435 * Running gnatls::
436 * Switches for gnatls::
437 * Examples of gnatls Usage::
438
439 Cleaning Up Using gnatclean
440
441 * Running gnatclean::
442 * Switches for gnatclean::
443 @c * Examples of gnatclean Usage::
444
445 @ifclear vms
446
447 GNAT and Libraries
448
449 * Introduction to Libraries in GNAT::
450 * General Ada Libraries::
451 * Stand-alone Ada Libraries::
452 * Rebuilding the GNAT Run-Time Library::
453
454 Using the GNU make Utility
455
456 * Using gnatmake in a Makefile::
457 * Automatically Creating a List of Directories::
458 * Generating the Command Line Switches::
459 * Overcoming Command Line Length Limits::
460 @end ifclear
461
462 Memory Management Issues
463
464 * Some Useful Memory Pools::
465 * The GNAT Debug Pool Facility::
466 @ifclear vms
467 * The gnatmem Tool::
468 @end ifclear
469
470 Stack Related Facilities
471
472 * Stack Overflow Checking::
473 * Static Stack Usage Analysis::
474 * Dynamic Stack Usage Analysis::
475
476 Some Useful Memory Pools
477
478 The GNAT Debug Pool Facility
479
480 @ifclear vms
481 The gnatmem Tool
482
483 * Running gnatmem::
484 * Switches for gnatmem::
485 * Example of gnatmem Usage::
486 @end ifclear
487
488 Verifying properties using gnatcheck
489
490 * Format of the Report File::
491 * General gnatcheck Switches::
492 * gnatcheck Rule Options::
493 * Add the Results of Compiler Checks to gnatcheck Output::
494
495  Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 @ifclear vms
505 * Ada Mode for Glide::
506 @end ifclear
507 * Converting Ada Files to html with gnathtml::
508
509 Running and Debugging Ada Programs
510
511 * The GNAT Debugger GDB::
512 * Running GDB::
513 * Introduction to GDB Commands::
514 * Using Ada Expressions::
515 * Calling User-Defined Subprograms::
516 * Using the Next Command in a Function::
517 * Ada Exceptions::
518 * Ada Tasks::
519 * Debugging Generic Units::
520 * GNAT Abnormal Termination or Failure to Terminate::
521 * Naming Conventions for GNAT Source Files::
522 * Getting Internal Debugging Information::
523 * Stack Traceback::
524
525 @ifset vms
526 * LSE::
527 @end ifset
528
529 @ifset vms
530 Compatibility with HP Ada
531
532 * Ada 95 Compatibility::
533 * Differences in the Definition of Package System::
534 * Language-Related Features::
535 * The Package STANDARD::
536 * The Package SYSTEM::
537 * Tasking and Task-Related Features::
538 * Pragmas and Pragma-Related Features::
539 * Library of Predefined Units::
540 * Bindings::
541 * Main Program Definition::
542 * Implementation-Defined Attributes::
543 * Compiler and Run-Time Interfacing::
544 * Program Compilation and Library Management::
545 * Input-Output::
546 * Implementation Limits::
547 * Tools and Utilities::
548
549 Language-Related Features
550
551 * Integer Types and Representations::
552 * Floating-Point Types and Representations::
553 * Pragmas Float_Representation and Long_Float::
554 * Fixed-Point Types and Representations::
555 * Record and Array Component Alignment::
556 * Address Clauses::
557 * Other Representation Clauses::
558
559 Tasking and Task-Related Features
560
561 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
562 * Assigning Task IDs::
563 * Task IDs and Delays::
564 * Task-Related Pragmas::
565 * Scheduling and Task Priority::
566 * The Task Stack::
567 * External Interrupts::
568
569 Pragmas and Pragma-Related Features
570
571 * Restrictions on the Pragma INLINE::
572 * Restrictions on the Pragma INTERFACE::
573 * Restrictions on the Pragma SYSTEM_NAME::
574
575 Library of Predefined Units
576
577 * Changes to DECLIB::
578
579 Bindings
580
581 * Shared Libraries and Options Files::
582 * Interfaces to C::
583 @end ifset
584
585 Platform-Specific Information for the Run-Time Libraries
586
587 * Summary of Run-Time Configurations::
588 * Specifying a Run-Time Library::
589 * Choosing the Scheduling Policy::
590 * Solaris-Specific Considerations::
591 * Linux-Specific Considerations::
592 * AIX-Specific Considerations::
593
594 Example of Binder Output File
595
596 Elaboration Order Handling in GNAT
597
598 * Elaboration Code in Ada 95::
599 * Checking the Elaboration Order in Ada 95::
600 * Controlling the Elaboration Order in Ada 95::
601 * Controlling Elaboration in GNAT - Internal Calls::
602 * Controlling Elaboration in GNAT - External Calls::
603 * Default Behavior in GNAT - Ensuring Safety::
604 * Treatment of Pragma Elaborate::
605 * Elaboration Issues for Library Tasks::
606 * Mixing Elaboration Models::
607 * What to Do If the Default Elaboration Behavior Fails::
608 * Elaboration for Access-to-Subprogram Values::
609 * Summary of Procedures for Elaboration Control::
610 * Other Elaboration Order Considerations::
611
612 Inline Assembler
613
614 * Basic Assembler Syntax::
615 * A Simple Example of Inline Assembler::
616 * Output Variables in Inline Assembler::
617 * Input Variables in Inline Assembler::
618 * Inlining Inline Assembler Code::
619 * Other Asm Functionality::
620
621 Compatibility and Porting Guide
622
623 * Compatibility with Ada 83::
624 * Implementation-dependent characteristics::
625 @ifclear vms
626 @c This brief section is only in the non-VMS version
627 @c The complete chapter on HP Ada issues is in the VMS version
628 * Compatibility with HP Ada 83::
629 @end ifclear
630 * Compatibility with Other Ada 95 Systems::
631 * Representation Clauses::
632 @ifset vms
633 * Transitioning to 64-Bit GNAT for OpenVMS::
634 @end ifset
635
636 @ifset unw
637 Microsoft Windows Topics
638
639 * Using GNAT on Windows::
640 * CONSOLE and WINDOWS subsystems::
641 * Temporary Files::
642 * Mixed-Language Programming on Windows::
643 * Windows Calling Conventions::
644 * Introduction to Dynamic Link Libraries (DLLs)::
645 * Using DLLs with GNAT::
646 * Building DLLs with GNAT::
647 * GNAT and Windows Resources::
648 * Debugging a DLL::
649 * Setting Stack Size from gnatlink::
650 * Setting Heap Size from gnatlink::
651 @end ifset
652
653 * Index::
654 @end menu
655 @end ifnottex
656
657 @node About This Guide
658 @unnumbered About This Guide
659
660 @noindent
661 @ifset vms
662 This guide describes the use of @value{EDITION},
663 a full language compiler for the Ada
664 95 programming language, implemented on OpenVMS for HP's Alpha and
665 Integrity server (I64) platforms.
666 @end ifset
667 @ifclear vms
668 This guide describes the use of @value{EDITION},
669 a compiler and software development
670 toolset for the full Ada 95 programming language.
671 @end ifclear
672 It describes the features of the compiler and tools, and details
673 how to use them to build Ada 95 applications.
674
675 @ifset PROEDITION
676 For ease of exposition, ``GNAT Pro'' will be referred to simply as
677 ``GNAT'' in the remainder of this document.
678 @end ifset
679
680 @menu
681 * What This Guide Contains::
682 * What You Should Know before Reading This Guide::
683 * Related Information::
684 * Conventions::
685 @end menu
686
687 @node What This Guide Contains
688 @unnumberedsec What This Guide Contains
689
690 @noindent
691 This guide contains the following chapters:
692 @itemize @bullet
693
694 @item
695 @ref{Getting Started with GNAT}, describes how to get started compiling
696 and running Ada programs with the GNAT Ada programming environment.
697 @item
698 @ref{The GNAT Compilation Model}, describes the compilation model used
699 by GNAT.
700
701 @item
702 @ref{Compiling Using gcc}, describes how to compile
703 Ada programs with @command{gcc}, the Ada compiler.
704
705 @item
706 @ref{Binding Using gnatbind}, describes how to
707 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
708 utility.
709
710 @item
711 @ref{Linking Using gnatlink},
712 describes @command{gnatlink}, a
713 program that provides for linking using the GNAT run-time library to
714 construct a program. @command{gnatlink} can also incorporate foreign language
715 object units into the executable.
716
717 @item
718 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
719 utility that automatically determines the set of sources
720 needed by an Ada compilation unit, and executes the necessary compilations
721 binding and link.
722
723 @item
724 @ref{Improving Performance}, shows various techniques for making your
725 Ada program run faster or take less space.
726 It discusses the effect of the compiler's optimization switch and
727 also describes the @command{gnatelim} tool and unused subprogram/data
728 elimination.
729
730 @item
731 @ref{Renaming Files Using gnatchop}, describes
732 @code{gnatchop}, a utility that allows you to preprocess a file that
733 contains Ada source code, and split it into one or more new files, one
734 for each compilation unit.
735
736 @item
737 @ref{Configuration Pragmas}, describes the configuration pragmas
738 handled by GNAT.
739
740 @item
741 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
742 shows how to override the default GNAT file naming conventions,
743 either for an individual unit or globally.
744
745 @item
746 @ref{GNAT Project Manager}, describes how to use project files
747 to organize large projects.
748
749 @item
750 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
751 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
752 way to navigate through sources.
753
754 @item
755 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
756 version of an Ada source file with control over casing, indentation,
757 comment placement, and other elements of program presentation style.
758
759 @item
760 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
761 metrics for an Ada source file, such as the number of types and subprograms,
762 and assorted complexity measures.
763
764 @item
765 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
766 file name krunching utility, used to handle shortened
767 file names on operating systems with a limit on the length of names.
768
769 @item
770 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
771 preprocessor utility that allows a single source file to be used to
772 generate multiple or parameterized source files, by means of macro
773 substitution.
774
775 @ifset vms
776 @item
777 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
778 a tool for rebuilding the GNAT run time with user-supplied
779 configuration pragmas.
780 @end ifset
781
782 @item
783 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
784 utility that displays information about compiled units, including dependences
785 on the corresponding sources files, and consistency of compilations.
786
787 @item
788 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
789 to delete files that are produced by the compiler, binder and linker.
790
791 @ifclear vms
792 @item
793 @ref{GNAT and Libraries}, describes the process of creating and using
794 Libraries with GNAT. It also describes how to recompile the GNAT run-time
795 library.
796
797 @item
798 @ref{Using the GNU make Utility}, describes some techniques for using
799 the GNAT toolset in Makefiles.
800 @end ifclear
801
802 @item
803 @ref{Memory Management Issues}, describes some useful predefined storage pools
804 and in particular the GNAT Debug Pool facility, which helps detect incorrect
805 memory references.
806 @ifclear vms
807 It also describes @command{gnatmem}, a utility that monitors dynamic
808 allocation and deallocation and helps detect ``memory leaks''.
809 @end ifclear
810
811 @item
812 @ref{Stack Related Facilities}, describes some useful tools associated with
813 stack checking and analysis.
814
815 @item
816 @ref{Verifying properties using gnatcheck}, discusses @code{gnatcheck},
817 a utility that checks Ada code against a set of rules.
818
819 @item
820 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
821 a utility that generates empty but compilable bodies for library units.
822
823 @item
824 @ref{Other Utility Programs}, discusses several other GNAT utilities,
825 including @code{gnathtml}.
826
827 @item
828 @ref{Running and Debugging Ada Programs}, describes how to run and debug
829 Ada programs.
830
831 @ifset vms
832 @item
833 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
834 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
835 developed by Digital Equipment Corporation and currently supported by HP.}
836 for OpenVMS Alpha. This product was formerly known as DEC Ada,
837 @cindex DEC Ada
838 and for
839 historical compatibility reasons, the relevant libraries still use the
840 DEC prefix.
841 @end ifset
842
843 @item
844 @ref{Platform-Specific Information for the Run-Time Libraries},
845 describes the various run-time
846 libraries supported by GNAT on various platforms and explains how to
847 choose a particular library.
848
849 @item
850 @ref{Example of Binder Output File}, shows the source code for the binder
851 output file for a sample program.
852
853 @item
854 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
855 you deal with elaboration order issues.
856
857 @item
858 @ref{Inline Assembler}, shows how to use the inline assembly facility
859 in an Ada program.
860
861 @item
862 @ref{Compatibility and Porting Guide}, includes sections on compatibility
863 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
864 in porting code from other environments.
865
866 @ifset unw
867 @item
868 @ref{Microsoft Windows Topics}, presents information relevant to the
869 Microsoft Windows platform.
870 @end ifset
871 @end itemize
872
873 @c *************************************************
874 @node What You Should Know before Reading This Guide
875 @c *************************************************
876 @unnumberedsec What You Should Know before Reading This Guide
877
878 @cindex Ada 95 Language Reference Manual
879 @noindent
880 This user's guide assumes that you are familiar with Ada 95 language, as
881 described in the International Standard ANSI/ISO/IEC-8652:1995, January
882 1995.
883
884 @node Related Information
885 @unnumberedsec Related Information
886
887 @noindent
888 For further information about related tools, refer to the following
889 documents:
890
891 @itemize @bullet
892 @item
893 @cite{GNAT Reference Manual}, which contains all reference
894 material for the GNAT implementation of Ada 95.
895
896 @ifset unw
897 @item
898 @cite{Using the GNAT Programming System}, which describes the GPS
899 integrated development environment.
900
901 @item
902 @cite{GNAT Programming System Tutorial}, which introduces the
903 main GPS features through examples.
904 @end ifset
905
906 @item
907 @cite{Ada 95 Language Reference Manual}, which contains all reference
908 material for the Ada 95 programming language.
909
910 @item
911 @cite{Debugging with GDB}
912 @ifset vms
913 , located in the GNU:[DOCS] directory,
914 @end ifset
915 contains all details on the use of the GNU source-level debugger.
916
917 @item
918 @cite{GNU Emacs Manual}
919 @ifset vms
920 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
921 @end ifset
922 contains full information on the extensible editor and programming
923 environment Emacs.
924
925 @end itemize
926
927 @c **************
928 @node Conventions
929 @unnumberedsec Conventions
930 @cindex Conventions
931 @cindex Typographical conventions
932
933 @noindent
934 Following are examples of the typographical and graphic conventions used
935 in this guide:
936
937 @itemize @bullet
938 @item
939 @code{Functions}, @code{utility program names}, @code{standard names},
940 and @code{classes}.
941
942 @item
943 @samp{Option flags}
944
945 @item
946 @file{File Names}, @file{button names}, and @file{field names}.
947
948 @item
949 @var{Variables}.
950
951 @item
952 @emph{Emphasis}.
953
954 @item
955 [optional information or parameters]
956
957 @item
958 Examples are described by text
959 @smallexample
960 and then shown this way.
961 @end smallexample
962 @end itemize
963
964 @noindent
965 Commands that are entered by the user are preceded in this manual by the
966 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
967 uses this sequence as a prompt, then the commands will appear exactly as
968 you see them in the manual. If your system uses some other prompt, then
969 the command will appear with the @code{$} replaced by whatever prompt
970 character you are using.
971
972 @ifset unw
973 Full file names are shown with the ``@code{/}'' character
974 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
975 If you are using GNAT on a Windows platform, please note that
976 the ``@code{\}'' character should be used instead.
977 @end ifset
978
979 @c ****************************
980 @node Getting Started with GNAT
981 @chapter Getting Started with GNAT
982
983 @noindent
984 This chapter describes some simple ways of using GNAT to build
985 executable Ada programs.
986 @ifset unw
987 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
988 show how to use the command line environment.
989 @ref{Introduction to Glide and GVD}, provides a brief
990 introduction to the visually-oriented IDE for GNAT.
991 Supplementing Glide on some platforms is GPS, the
992 GNAT Programming System, which offers a richer graphical
993 ``look and feel'', enhanced configurability, support for
994 development in other programming language, comprehensive
995 browsing features, and many other capabilities.
996 For information on GPS please refer to
997 @cite{Using the GNAT Programming System}.
998 @end ifset
999
1000 @menu
1001 * Running GNAT::
1002 * Running a Simple Ada Program::
1003 * Running a Program with Multiple Units::
1004 * Using the gnatmake Utility::
1005 @ifset vms
1006 * Editing with Emacs::
1007 @end ifset
1008 @ifclear vms
1009 * Introduction to GPS::
1010 * Introduction to Glide and GVD::
1011 @end ifclear
1012 @end menu
1013
1014 @node Running GNAT
1015 @section Running GNAT
1016
1017 @noindent
1018 Three steps are needed to create an executable file from an Ada source
1019 file:
1020
1021 @enumerate
1022 @item
1023 The source file(s) must be compiled.
1024 @item
1025 The file(s) must be bound using the GNAT binder.
1026 @item
1027 All appropriate object files must be linked to produce an executable.
1028 @end enumerate
1029
1030 @noindent
1031 All three steps are most commonly handled by using the @command{gnatmake}
1032 utility program that, given the name of the main program, automatically
1033 performs the necessary compilation, binding and linking steps.
1034
1035 @node Running a Simple Ada Program
1036 @section Running a Simple Ada Program
1037
1038 @noindent
1039 Any text editor may be used to prepare an Ada program.
1040 @ifclear vms
1041 If @code{Glide} is
1042 used, the optional Ada mode may be helpful in laying out the program.
1043 @end ifclear
1044 The
1045 program text is a normal text file. We will suppose in our initial
1046 example that you have used your editor to prepare the following
1047 standard format text file:
1048
1049 @smallexample @c ada
1050 @cartouche
1051 with Ada.Text_IO; use Ada.Text_IO;
1052 procedure Hello is
1053 begin
1054    Put_Line ("Hello WORLD!");
1055 end Hello;
1056 @end cartouche
1057 @end smallexample
1058
1059 @noindent
1060 This file should be named @file{hello.adb}.
1061 With the normal default file naming conventions, GNAT requires
1062 that each file
1063 contain a single compilation unit whose file name is the
1064 unit name,
1065 with periods replaced by hyphens; the
1066 extension is @file{ads} for a
1067 spec and @file{adb} for a body.
1068 You can override this default file naming convention by use of the
1069 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1070 Alternatively, if you want to rename your files according to this default
1071 convention, which is probably more convenient if you will be using GNAT
1072 for all your compilations, then the @code{gnatchop} utility
1073 can be used to generate correctly-named source files
1074 (@pxref{Renaming Files Using gnatchop}).
1075
1076 You can compile the program using the following command (@code{$} is used
1077 as the command prompt in the examples in this document):
1078
1079 @smallexample
1080 $ gcc -c hello.adb
1081 @end smallexample
1082
1083 @noindent
1084 @command{gcc} is the command used to run the compiler. This compiler is
1085 capable of compiling programs in several languages, including Ada 95 and
1086 C. It assumes that you have given it an Ada program if the file extension is
1087 either @file{.ads} or @file{.adb}, and it will then call
1088 the GNAT compiler to compile the specified file.
1089
1090 @ifclear vms
1091 The @option{-c} switch is required. It tells @command{gcc} to only do a
1092 compilation. (For C programs, @command{gcc} can also do linking, but this
1093 capability is not used directly for Ada programs, so the @option{-c}
1094 switch must always be present.)
1095 @end ifclear
1096
1097 This compile command generates a file
1098 @file{hello.o}, which is the object
1099 file corresponding to your Ada program. It also generates
1100 an ``Ada Library Information'' file @file{hello.ali},
1101 which contains additional information used to check
1102 that an Ada program is consistent.
1103 To build an executable file,
1104 use @code{gnatbind} to bind the program
1105 and @command{gnatlink} to link it. The
1106 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1107 @file{ALI} file, but the default extension of @file{.ali} can
1108 be omitted. This means that in the most common case, the argument
1109 is simply the name of the main program:
1110
1111 @smallexample
1112 $ gnatbind hello
1113 $ gnatlink hello
1114 @end smallexample
1115
1116 @noindent
1117 A simpler method of carrying out these steps is to use
1118 @command{gnatmake},
1119 a master program that invokes all the required
1120 compilation, binding and linking tools in the correct order. In particular,
1121 @command{gnatmake} automatically recompiles any sources that have been
1122 modified since they were last compiled, or sources that depend
1123 on such modified sources, so that ``version skew'' is avoided.
1124 @cindex Version skew (avoided by @command{gnatmake})
1125
1126 @smallexample
1127 $ gnatmake hello.adb
1128 @end smallexample
1129
1130 @noindent
1131 The result is an executable program called @file{hello}, which can be
1132 run by entering:
1133
1134 @smallexample
1135 $ ^hello^RUN HELLO^
1136 @end smallexample
1137
1138 @noindent
1139 assuming that the current directory is on the search path
1140 for executable programs.
1141
1142 @noindent
1143 and, if all has gone well, you will see
1144
1145 @smallexample
1146 Hello WORLD!
1147 @end smallexample
1148
1149 @noindent
1150 appear in response to this command.
1151
1152 @c ****************************************
1153 @node Running a Program with Multiple Units
1154 @section Running a Program with Multiple Units
1155
1156 @noindent
1157 Consider a slightly more complicated example that has three files: a
1158 main program, and the spec and body of a package:
1159
1160 @smallexample @c ada
1161 @cartouche
1162 @group
1163 package Greetings is
1164    procedure Hello;
1165    procedure Goodbye;
1166 end Greetings;
1167
1168 with Ada.Text_IO; use Ada.Text_IO;
1169 package body Greetings is
1170    procedure Hello is
1171    begin
1172       Put_Line ("Hello WORLD!");
1173    end Hello;
1174
1175    procedure Goodbye is
1176    begin
1177       Put_Line ("Goodbye WORLD!");
1178    end Goodbye;
1179 end Greetings;
1180 @end group
1181
1182 @group
1183 with Greetings;
1184 procedure Gmain is
1185 begin
1186    Greetings.Hello;
1187    Greetings.Goodbye;
1188 end Gmain;
1189 @end group
1190 @end cartouche
1191 @end smallexample
1192
1193 @noindent
1194 Following the one-unit-per-file rule, place this program in the
1195 following three separate files:
1196
1197 @table @file
1198 @item greetings.ads
1199 spec of package @code{Greetings}
1200
1201 @item greetings.adb
1202 body of package @code{Greetings}
1203
1204 @item gmain.adb
1205 body of main program
1206 @end table
1207
1208 @noindent
1209 To build an executable version of
1210 this program, we could use four separate steps to compile, bind, and link
1211 the program, as follows:
1212
1213 @smallexample
1214 $ gcc -c gmain.adb
1215 $ gcc -c greetings.adb
1216 $ gnatbind gmain
1217 $ gnatlink gmain
1218 @end smallexample
1219
1220 @noindent
1221 Note that there is no required order of compilation when using GNAT.
1222 In particular it is perfectly fine to compile the main program first.
1223 Also, it is not necessary to compile package specs in the case where
1224 there is an accompanying body; you only need to compile the body. If you want
1225 to submit these files to the compiler for semantic checking and not code
1226 generation, then use the
1227 @option{-gnatc} switch:
1228
1229 @smallexample
1230 $ gcc -c greetings.ads -gnatc
1231 @end smallexample
1232
1233 @noindent
1234 Although the compilation can be done in separate steps as in the
1235 above example, in practice it is almost always more convenient
1236 to use the @command{gnatmake} tool. All you need to know in this case
1237 is the name of the main program's source file. The effect of the above four
1238 commands can be achieved with a single one:
1239
1240 @smallexample
1241 $ gnatmake gmain.adb
1242 @end smallexample
1243
1244 @noindent
1245 In the next section we discuss the advantages of using @command{gnatmake} in
1246 more detail.
1247
1248 @c *****************************
1249 @node Using the gnatmake Utility
1250 @section Using the @command{gnatmake} Utility
1251
1252 @noindent
1253 If you work on a program by compiling single components at a time using
1254 @command{gcc}, you typically keep track of the units you modify. In order to
1255 build a consistent system, you compile not only these units, but also any
1256 units that depend on the units you have modified.
1257 For example, in the preceding case,
1258 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1259 you edit @file{greetings.ads}, you must recompile both
1260 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1261 units that depend on @file{greetings.ads}.
1262
1263 @code{gnatbind} will warn you if you forget one of these compilation
1264 steps, so that it is impossible to generate an inconsistent program as a
1265 result of forgetting to do a compilation. Nevertheless it is tedious and
1266 error-prone to keep track of dependencies among units.
1267 One approach to handle the dependency-bookkeeping is to use a
1268 makefile. However, makefiles present maintenance problems of their own:
1269 if the dependencies change as you change the program, you must make
1270 sure that the makefile is kept up-to-date manually, which is also an
1271 error-prone process.
1272
1273 The @command{gnatmake} utility takes care of these details automatically.
1274 Invoke it using either one of the following forms:
1275
1276 @smallexample
1277 $ gnatmake gmain.adb
1278 $ gnatmake ^gmain^GMAIN^
1279 @end smallexample
1280
1281 @noindent
1282 The argument is the name of the file containing the main program;
1283 you may omit the extension. @command{gnatmake}
1284 examines the environment, automatically recompiles any files that need
1285 recompiling, and binds and links the resulting set of object files,
1286 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1287 In a large program, it
1288 can be extremely helpful to use @command{gnatmake}, because working out by hand
1289 what needs to be recompiled can be difficult.
1290
1291 Note that @command{gnatmake}
1292 takes into account all the Ada 95 rules that
1293 establish dependencies among units. These include dependencies that result
1294 from inlining subprogram bodies, and from
1295 generic instantiation. Unlike some other
1296 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1297 found by the compiler on a previous compilation, which may possibly
1298 be wrong when sources change. @command{gnatmake} determines the exact set of
1299 dependencies from scratch each time it is run.
1300
1301 @ifset vms
1302 @node Editing with Emacs
1303 @section Editing with Emacs
1304 @cindex Emacs
1305
1306 @noindent
1307 Emacs is an extensible self-documenting text editor that is available in a
1308 separate VMSINSTAL kit.
1309
1310 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1311 click on the Emacs Help menu and run the Emacs Tutorial.
1312 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1313 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1314
1315 Documentation on Emacs and other tools is available in Emacs under the
1316 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1317 use the middle mouse button to select a topic (e.g. Emacs).
1318
1319 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1320 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1321 get to the Emacs manual.
1322 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1323 prompt.
1324
1325 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1326 which is sufficiently extensible to provide for a complete programming
1327 environment and shell for the sophisticated user.
1328 @end ifset
1329
1330 @ifclear vms
1331 @node Introduction to GPS
1332 @section Introduction to GPS
1333 @cindex GPS (GNAT Programming System)
1334 @cindex GNAT Programming System (GPS)
1335 @noindent
1336 Although the command line interface (@command{gnatmake}, etc.) alone
1337 is sufficient, a graphical Interactive Development
1338 Environment can make it easier for you to compose, navigate, and debug
1339 programs.  This section describes the main features of GPS
1340 (``GNAT Programming System''), the GNAT graphical IDE.
1341 You will see how to use GPS to build and debug an executable, and
1342 you will also learn some of the basics of the GNAT ``project'' facility.
1343
1344 GPS enables you to do much more than is presented here;
1345 e.g., you can produce a call graph, interface to a third-party
1346 Version Control System, and inspect the generated assembly language
1347 for a program.
1348 Indeed, GPS also supports languages other than Ada.
1349 Such additional information, and an explanation of all of the GPS menu
1350 items. may be found in the on-line help, which includes
1351 a user's guide and a tutorial (these are also accessible from the GNAT
1352 startup menu).
1353
1354 @menu
1355 * Building a New Program with GPS::
1356 * Simple Debugging with GPS::
1357 @end menu
1358
1359 @node Building a New Program with GPS
1360 @subsection Building a New Program with GPS
1361 @noindent
1362 GPS invokes the GNAT compilation tools using information
1363 contained in a @emph{project} (also known as a @emph{project file}):
1364 a collection of properties such
1365 as source directories, identities of main subprograms, tool switches, etc.,
1366 and their associated values.
1367 See @ref{GNAT Project Manager} for details.
1368 In order to run GPS, you will need to either create a new project
1369 or else open an existing one.
1370
1371 This section will explain how you can use GPS to create a project,
1372 to associate Ada source files with a project, and to build and run
1373 programs.
1374
1375 @enumerate
1376 @item @emph{Creating a project}
1377
1378 Invoke GPS, either from the command line or the platform's IDE.
1379 After it starts, GPS will display a ``Welcome'' screen with three
1380 radio buttons:
1381
1382 @itemize @bullet
1383 @item
1384 @code{Start with default project in directory}
1385
1386 @item
1387 @code{Create new project with wizard}
1388
1389 @item
1390 @code{Open existing project}
1391 @end itemize
1392
1393 @noindent
1394 Select @code{Create new project with wizard} and press @code{OK}.
1395 A new window will appear.  In the text box labeled with
1396 @code{Enter the name of the project to create}, type @file{sample}
1397 as the project name.
1398 In the next box, browse to choose the directory in which you
1399 would like to create the project file.
1400 After selecting an appropriate directory, press @code{Forward}.
1401
1402 A window will appear with the title
1403 @code{Version Control System Configuration}.
1404 Simply press @code{Forward}.
1405
1406 A window will appear with the title
1407 @code{Please select the source directories for this project}.
1408 The directory that you specified for the project file will be selected
1409 by default as the one to use for sources; simply press @code{Forward}.
1410
1411 A window will appear with the title
1412 @code{Please select the build directory for this project}.
1413 The directory that you specified for the project file will be selected
1414 by default for object files and executables;
1415 simply press @code{Forward}.
1416
1417 A window will appear with the title
1418 @code{Please select the main units for this project}.
1419 You will supply this information later, after creating the source file.
1420 Simply press @code{Forward} for now.
1421
1422 A window will appear with the title
1423 @code{Please select the switches to build the project}.
1424 Press @code{Apply}.  This will create a project file named
1425 @file{sample.prj} in the directory that you had specified.
1426
1427 @item @emph{Creating and saving the source file}
1428
1429 After you create the new project, a GPS window will appear, which is
1430 partitioned into two main sections:
1431
1432 @itemize @bullet
1433 @item
1434 A @emph{Workspace area}, initially greyed out, which you will use for
1435 creating and editing source files
1436
1437 @item
1438 Directly below, a @emph{Messages area}, which initially displays a
1439 ``Welcome'' message.
1440 (If the Messages area is not visible, drag its border upward to expand it.)
1441 @end itemize
1442
1443 @noindent
1444 Select @code{File} on the menu bar, and then the @code{New} command.
1445 The Workspace area will become white, and you can now
1446 enter the source program explicitly.
1447 Type the following text
1448
1449 @smallexample @c ada
1450 @group
1451 with Ada.Text_IO; use Ada.Text_IO;
1452 procedure Hello is
1453 begin
1454   Put_Line("Hello from GPS!");
1455 end Hello;
1456 @end group
1457 @end smallexample
1458
1459 @noindent
1460 Select @code{File}, then @code{Save As}, and enter the source file name
1461 @file{hello.adb}.
1462 The file will be saved in the same directory you specified as the
1463 location of the default project file.
1464
1465 @item @emph{Updating the project file}
1466
1467 You need to add the new source file to the project.
1468 To do this, select
1469 the @code{Project} menu and then @code{Edit project properties}.
1470 Click the @code{Main files} tab on the left, and then the
1471 @code{Add} button.
1472 Choose @file{hello.adb} from the list, and press @code{Open}.
1473 The project settings window will reflect this action.
1474 Click @code{OK}.
1475
1476 @item @emph{Building and running the program}
1477
1478 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1479 and select @file{hello.adb}.
1480 The Messages window will display the resulting invocations of @command{gcc},
1481 @command{gnatbind}, and @command{gnatlink}
1482 (reflecting the default switch settings from the
1483 project file that you created) and then a ``successful compilation/build''
1484 message.
1485
1486 To run the program, choose the @code{Build} menu, then @code{Run}, and
1487 select @command{hello}.
1488 An @emph{Arguments Selection} window will appear.
1489 There are no command line arguments, so just click @code{OK}.
1490
1491 The Messages window will now display the program's output (the string
1492 @code{Hello from GPS}), and at the bottom of the GPS window a status
1493 update is displayed (@code{Run: hello}).
1494 Close the GPS window (or select @code{File}, then @code{Exit}) to
1495 terminate this GPS session.
1496 @end enumerate
1497
1498 @node Simple Debugging with GPS
1499 @subsection Simple Debugging with GPS
1500 @noindent
1501 This section illustrates basic debugging techniques (setting breakpoints,
1502 examining/modifying variables, single stepping).
1503
1504 @enumerate
1505 @item @emph{Opening a project}
1506
1507 Start GPS and select @code{Open existing project}; browse to
1508 specify the project file @file{sample.prj} that you had created in the
1509 earlier example.
1510
1511 @item @emph{Creating a source file}
1512
1513 Select @code{File}, then @code{New}, and type in the following program:
1514
1515 @smallexample @c ada
1516 @group
1517 with Ada.Text_IO; use Ada.Text_IO;
1518 procedure Example is
1519    Line : String (1..80);
1520    N    : Natural;
1521 begin
1522    Put_Line("Type a line of text at each prompt; an empty line to exit");
1523    loop
1524       Put(": ");
1525       Get_Line (Line, N);
1526       Put_Line (Line (1..N) );
1527       exit when N=0;
1528    end loop;
1529 end Example;
1530 @end group
1531 @end smallexample
1532
1533 @noindent
1534 Select @code{File}, then @code{Save as}, and enter the file name
1535 @file{example.adb}.
1536
1537 @item @emph{Updating the project file}
1538
1539 Add @code{Example} as a new main unit for the project:
1540 @enumerate a
1541 @item
1542 Select @code{Project}, then @code{Edit Project Properties}.
1543
1544 @item
1545 Select the @code{Main files} tab, click @code{Add}, then
1546 select the file @file{example.adb} from the list, and
1547 click @code{Open}.
1548 You will see the file name appear in the list of main units
1549
1550 @item
1551 Click @code{OK}
1552 @end enumerate
1553
1554 @item @emph{Building/running the executable}
1555
1556 To build the executable
1557 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1558
1559 Run the program to see its effect (in the Messages area).
1560 Each line that you enter is displayed; an empty line will
1561 cause the loop to exit and the program to terminate.
1562
1563 @item @emph{Debugging the program}
1564
1565 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1566 which are required for debugging, are on by default when you create
1567 a new project.
1568 Thus unless you intentionally remove these settings, you will be able
1569 to debug any program that you develop using GPS.
1570
1571 @enumerate a
1572 @item @emph{Initializing}
1573
1574 Select @code{Debug}, then @code{Initialize}, then @file{example}
1575
1576 @item @emph{Setting a breakpoint}
1577
1578 After performing the initialization step, you will observe a small
1579 icon to the right of each line number.
1580 This serves as a toggle for breakpoints; clicking the icon will
1581 set a breakpoint at the corresponding line (the icon will change to
1582 a red circle with an ``x''), and clicking it again
1583 will remove the breakpoint / reset the icon.
1584
1585 For purposes of this example, set a breakpoint at line 10 (the
1586 statement @code{Put_Line@ (Line@ (1..N));}
1587
1588 @item @emph{Starting program execution}
1589
1590 Select @code{Debug}, then @code{Run}.  When the
1591 @code{Program Arguments} window appears, click @code{OK}.
1592 A console window will appear; enter some line of text,
1593 e.g. @code{abcde}, at the prompt.
1594 The program will pause execution when it gets to the
1595 breakpoint, and the corresponding line is highlighted.
1596
1597 @item @emph{Examining a variable}
1598
1599 Move the mouse over one of the occurrences of the variable @code{N}.
1600 You will see the value (5) displayed, in ``tool tip'' fashion.
1601 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1602 You will see information about @code{N} appear in the @code{Debugger Data}
1603 pane, showing the value as 5.
1604
1605 @item @emph{Assigning a new value to a variable}
1606
1607 Right click on the @code{N} in the @code{Debugger Data} pane, and
1608 select @code{Set value of N}.
1609 When the input window appears, enter the value @code{4} and click
1610 @code{OK}.
1611 This value does not automatically appear in the @code{Debugger Data}
1612 pane; to see it, right click again on the @code{N} in the
1613 @code{Debugger Data} pane and select @code{Update value}.
1614 The new value, 4, will appear in red.
1615
1616 @item @emph{Single stepping}
1617
1618 Select @code{Debug}, then @code{Next}.
1619 This will cause the next statement to be executed, in this case the
1620 call of @code{Put_Line} with the string slice.
1621 Notice in the console window that the displayed string is simply
1622 @code{abcd} and not @code{abcde} which you had entered.
1623 This is because the upper bound of the slice is now 4 rather than 5.
1624
1625 @item @emph{Removing a breakpoint}
1626
1627 Toggle the breakpoint icon at line 10.
1628
1629 @item @emph{Resuming execution from a breakpoint}
1630
1631 Select @code{Debug}, then @code{Continue}.
1632 The program will reach the next iteration of the loop, and
1633 wait for input after displaying the prompt.
1634 This time, just hit the @kbd{Enter} key.
1635 The value of @code{N} will be 0, and the program will terminate.
1636 The console window will disappear.
1637 @end enumerate
1638 @end enumerate
1639
1640 @node Introduction to Glide and GVD
1641 @section Introduction to Glide and GVD
1642 @cindex Glide
1643 @cindex GVD
1644 @noindent
1645 This section describes the main features of Glide,
1646 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1647 the GNU Visual Debugger.
1648 These tools may be present in addition to, or in place of, GPS on some
1649 platforms.
1650 Additional information on Glide and GVD may be found
1651 in the on-line help for these tools.
1652
1653 @menu
1654 * Building a New Program with Glide::
1655 * Simple Debugging with GVD::
1656 * Other Glide Features::
1657 @end menu
1658
1659 @node Building a New Program with Glide
1660 @subsection Building a New Program with Glide
1661 @noindent
1662 The simplest way to invoke Glide is to enter @command{glide}
1663 at the command prompt.  It will generally be useful to issue this
1664 as a background command, thus allowing you to continue using
1665 your command window for other purposes while Glide is running:
1666
1667 @smallexample
1668 $ glide&
1669 @end smallexample
1670
1671 @noindent
1672 Glide will start up with an initial screen displaying the top-level menu items
1673 as well as some other information.  The menu selections are as follows
1674 @itemize @bullet
1675 @item @code{Buffers}
1676 @item @code{Files}
1677 @item @code{Tools}
1678 @item @code{Edit}
1679 @item @code{Search}
1680 @item @code{Mule}
1681 @item @code{Glide}
1682 @item @code{Help}
1683 @end itemize
1684
1685 @noindent
1686 For this introductory example, you will need to create a new Ada source file.
1687 First, select the @code{Files} menu.  This will pop open a menu with around
1688 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1689 Depending on the platform, you may see a pop-up window where you can browse
1690 to an appropriate directory and then enter the file name, or else simply
1691 see a line at the bottom of the Glide window where you can likewise enter
1692 the file name.  Note that in Glide, when you attempt to open a non-existent
1693 file, the effect is to create a file with that name.  For this example enter
1694 @file{hello.adb} as the name of the file.
1695
1696 A new buffer will now appear, occupying the entire Glide window,
1697 with the file name at the top.  The menu selections are slightly different
1698 from the ones you saw on the opening screen; there is an @code{Entities} item,
1699 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1700 the file extension to identify the source language, so @file{adb} indicates
1701 an Ada source file.
1702
1703 You will enter some of the source program lines explicitly,
1704 and use the syntax-oriented template mechanism to enter other lines.
1705 First, type the following text:
1706 @smallexample
1707 with Ada.Text_IO; use Ada.Text_IO;
1708 procedure Hello is
1709 begin
1710 @end smallexample
1711
1712 @noindent
1713 Observe that Glide uses different colors to distinguish reserved words from
1714 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1715 automatically indented in anticipation of declarations.  When you enter
1716 @code{begin}, Glide recognizes that there are no declarations and thus places
1717 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1718 indented, where the statement(s) will be placed.
1719
1720 The main part of the program will be a @code{for} loop.  Instead of entering
1721 the text explicitly, however, use a statement template.  Select the @code{Ada}
1722 item on the top menu bar, move the mouse to the @code{Statements} item,
1723 and you will see a large selection of alternatives.  Choose @code{for loop}.
1724 You will be prompted (at the bottom of the buffer) for a loop name;
1725 simply press the @key{Enter} key since a loop name is not needed.
1726 You should see the beginning of a @code{for} loop appear in the source
1727 program window.  You will now be prompted for the name of the loop variable;
1728 enter a line with the identifier @code{ind} (lower case).  Note that,
1729 by default, Glide capitalizes the name (you can override such behavior
1730 if you wish, although this is outside the scope of this introduction).
1731 Next, Glide prompts you for the loop range; enter a line containing
1732 @code{1..5} and you will see this also appear in the source program,
1733 together with the remaining elements of the @code{for} loop syntax.
1734
1735 Next enter the statement (with an intentional error, a missing semicolon)
1736 that will form the body of the loop:
1737 @smallexample
1738 Put_Line("Hello, World" & Integer'Image(I))
1739 @end smallexample
1740
1741 @noindent
1742 Finally, type @code{end Hello;} as the last line in the program.
1743 Now save the file: choose the @code{File} menu item, and then the
1744 @code{Save buffer} selection.  You will see a message at the bottom
1745 of the buffer confirming that the file has been saved.
1746
1747 You are now ready to attempt to build the program.  Select the @code{Ada}
1748 item from the top menu bar.  Although we could choose simply to compile
1749 the file, we will instead attempt to do a build (which invokes
1750 @command{gnatmake}) since, if the compile is successful, we want to build
1751 an executable.  Thus select @code{Ada build}.  This will fail because of the
1752 compilation error, and you will notice that the Glide window has been split:
1753 the top window contains the source file, and the bottom window contains the
1754 output from the GNAT tools. Glide allows you to navigate from a compilation
1755 error to the source file position corresponding to the error: click the
1756 middle mouse button (or simultaneously press the left and right buttons,
1757 on a two-button mouse) on the diagnostic line in the tool window.  The
1758 focus will shift to the source window, and the cursor will be positioned
1759 on the character at which the error was detected.
1760
1761 Correct the error: type in a semicolon to terminate the statement.
1762 Although you can again save the file explicitly, you can also simply invoke
1763 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1764 This time the build will succeed; the tool output window shows you the
1765 options that are supplied by default.  The GNAT tools' output (e.g.
1766 object and ALI files, executable) will go in the directory from which
1767 Glide was launched.
1768
1769 To execute the program, choose @code{Ada} and then @code{Run}.
1770 You should see the program's output displayed in the bottom window:
1771
1772 @smallexample
1773 Hello, world 1
1774 Hello, world 2
1775 Hello, world 3
1776 Hello, world 4
1777 Hello, world 5
1778 @end smallexample
1779
1780 @node Simple Debugging with GVD
1781 @subsection Simple Debugging with GVD
1782
1783 @noindent
1784 This section describes how to set breakpoints, examine/modify variables,
1785 and step through execution.
1786
1787 In order to enable debugging, you need to pass the @option{-g} switch
1788 to both the compiler and to @command{gnatlink}.  If you are using
1789 the command line, passing @option{-g} to @command{gnatmake} will have
1790 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1791 by issuing the command:
1792
1793 @smallexample
1794 $ gvd hello
1795 @end smallexample
1796
1797 @noindent
1798 If you are using Glide, then @option{-g} is passed to the relevant tools
1799 by default when you do a build.  Start the debugger by selecting the
1800 @code{Ada} menu item, and then @code{Debug}.
1801
1802 GVD comes up in a multi-part window.  One pane shows the names of files
1803 comprising your executable; another pane shows the source code of the current
1804 unit (initially your main subprogram), another pane shows the debugger output
1805 and user interactions, and the fourth pane (the data canvas at the top
1806 of the window) displays data objects that you have selected.
1807
1808 To the left of the source file pane, you will notice green dots adjacent
1809 to some lines.  These are lines for which object code exists and where
1810 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1811 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1812 in a red circle.  Clicking the circle toggles the breakpoint off,
1813 and the red circle is replaced by the green dot.
1814
1815 For this example, set a breakpoint at the statement where @code{Put_Line}
1816 is invoked.
1817
1818 Start program execution by selecting the @code{Run} button on the top menu bar.
1819 (The @code{Start} button will also start your program, but it will
1820 cause program execution to break at the entry to your main subprogram.)
1821 Evidence of reaching the breakpoint will appear: the source file line will be
1822 highlighted, and the debugger interactions pane will display
1823 a relevant message.
1824
1825 You can examine the values of variables in several ways.  Move the mouse
1826 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1827 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1828 and select @code{Display Ind}; a box showing the variable's name and value
1829 will appear in the data canvas.
1830
1831 Although a loop index is a constant with respect to Ada semantics,
1832 you can change its value in the debugger.  Right-click in the box
1833 for @code{Ind}, and select the @code{Set Value of Ind} item.
1834 Enter @code{2} as the new value, and press @command{OK}.
1835 The box for @code{Ind} shows the update.
1836
1837 Press the @code{Step} button on the top menu bar; this will step through
1838 one line of program text (the invocation of @code{Put_Line}), and you can
1839 observe the effect of having modified @code{Ind} since the value displayed
1840 is @code{2}.
1841
1842 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1843 button.  You will see the remaining output lines displayed in the debugger
1844 interaction window, along with a message confirming normal program
1845 termination.
1846
1847 @node Other Glide Features
1848 @subsection Other Glide Features
1849
1850 @noindent
1851 You may have observed that some of the menu selections contain abbreviations;
1852 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1853 These are @emph{shortcut keys} that you can use instead of selecting
1854 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1855 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1856 of selecting @code{Files} and then @code{Open file...}.
1857
1858 To abort a Glide command, type @key{Ctrl-g}.
1859
1860 If you want Glide to start with an existing source file, you can either
1861 launch Glide as above and then open the file via @code{Files} @result{}
1862 @code{Open file...}, or else simply pass the name of the source file
1863 on the command line:
1864
1865 @smallexample
1866 $ glide hello.adb&
1867 @end smallexample
1868
1869 @noindent
1870 While you are using Glide, a number of @emph{buffers} exist.
1871 You create some explicitly; e.g., when you open/create a file.
1872 Others arise as an effect of the commands that you issue; e.g., the buffer
1873 containing the output of the tools invoked during a build.  If a buffer
1874 is hidden, you can bring it into a visible window by first opening
1875 the @code{Buffers} menu and then selecting the desired entry.
1876
1877 If a buffer occupies only part of the Glide screen and you want to expand it
1878 to fill the entire screen, then click in the buffer and then select
1879 @code{Files} @result{} @code{One Window}.
1880
1881 If a window is occupied by one buffer and you want to split the window
1882 to bring up a second buffer, perform the following steps:
1883 @itemize @bullet
1884 @item Select @code{Files} @result{} @code{Split Window};
1885 this will produce two windows each of which holds the original buffer
1886 (these are not copies, but rather different views of the same buffer contents)
1887
1888 @item With the focus in one of the windows,
1889 select the desired buffer from the @code{Buffers} menu
1890 @end itemize
1891
1892 @noindent
1893 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1894 @end ifclear
1895
1896 @node The GNAT Compilation Model
1897 @chapter The GNAT Compilation Model
1898 @cindex GNAT compilation model
1899 @cindex Compilation model
1900
1901 @menu
1902 * Source Representation::
1903 * Foreign Language Representation::
1904 * File Naming Rules::
1905 * Using Other File Names::
1906 * Alternative File Naming Schemes::
1907 * Generating Object Files::
1908 * Source Dependencies::
1909 * The Ada Library Information Files::
1910 * Binding an Ada Program::
1911 * Mixed Language Programming::
1912 @ifclear vms
1913 * Building Mixed Ada & C++ Programs::
1914 * Comparison between GNAT and C/C++ Compilation Models::
1915 @end ifclear
1916 * Comparison between GNAT and Conventional Ada Library Models::
1917 @ifset vms
1918 * Placement of temporary files::
1919 @end ifset
1920 @end menu
1921
1922 @noindent
1923 This chapter describes the compilation model used by GNAT. Although
1924 similar to that used by other languages, such as C and C++, this model
1925 is substantially different from the traditional Ada compilation models,
1926 which are based on a library. The model is initially described without
1927 reference to the library-based model. If you have not previously used an
1928 Ada compiler, you need only read the first part of this chapter. The
1929 last section describes and discusses the differences between the GNAT
1930 model and the traditional Ada compiler models. If you have used other
1931 Ada compilers, this section will help you to understand those
1932 differences, and the advantages of the GNAT model.
1933
1934 @node Source Representation
1935 @section Source Representation
1936 @cindex Latin-1
1937
1938 @noindent
1939 Ada source programs are represented in standard text files, using
1940 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1941 7-bit ASCII set, plus additional characters used for
1942 representing foreign languages (@pxref{Foreign Language Representation}
1943 for support of non-USA character sets). The format effector characters
1944 are represented using their standard ASCII encodings, as follows:
1945
1946 @table @code
1947 @item VT
1948 @findex VT
1949 Vertical tab, @code{16#0B#}
1950
1951 @item HT
1952 @findex HT
1953 Horizontal tab, @code{16#09#}
1954
1955 @item CR
1956 @findex CR
1957 Carriage return, @code{16#0D#}
1958
1959 @item LF
1960 @findex LF
1961 Line feed, @code{16#0A#}
1962
1963 @item FF
1964 @findex FF
1965 Form feed, @code{16#0C#}
1966 @end table
1967
1968 @noindent
1969 Source files are in standard text file format. In addition, GNAT will
1970 recognize a wide variety of stream formats, in which the end of
1971 physical lines is marked by any of the following sequences:
1972 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1973 in accommodating files that are imported from other operating systems.
1974
1975 @cindex End of source file
1976 @cindex Source file, end
1977 @findex SUB
1978 The end of a source file is normally represented by the physical end of
1979 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1980 recognized as signalling the end of the source file. Again, this is
1981 provided for compatibility with other operating systems where this
1982 code is used to represent the end of file.
1983
1984 Each file contains a single Ada compilation unit, including any pragmas
1985 associated with the unit. For example, this means you must place a
1986 package declaration (a package @dfn{spec}) and the corresponding body in
1987 separate files. An Ada @dfn{compilation} (which is a sequence of
1988 compilation units) is represented using a sequence of files. Similarly,
1989 you will place each subunit or child unit in a separate file.
1990
1991 @node Foreign Language Representation
1992 @section Foreign Language Representation
1993
1994 @noindent
1995 GNAT supports the standard character sets defined in Ada 95 as well as
1996 several other non-standard character sets for use in localized versions
1997 of the compiler (@pxref{Character Set Control}).
1998 @menu
1999 * Latin-1::
2000 * Other 8-Bit Codes::
2001 * Wide Character Encodings::
2002 @end menu
2003
2004 @node Latin-1
2005 @subsection Latin-1
2006 @cindex Latin-1
2007
2008 @noindent
2009 The basic character set is Latin-1. This character set is defined by ISO
2010 standard 8859, part 1. The lower half (character codes @code{16#00#}
2011 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
2012 is used to represent additional characters. These include extended letters
2013 used by European languages, such as French accents, the vowels with umlauts
2014 used in German, and the extra letter A-ring used in Swedish.
2015
2016 @findex Ada.Characters.Latin_1
2017 For a complete list of Latin-1 codes and their encodings, see the source
2018 file of library unit @code{Ada.Characters.Latin_1} in file
2019 @file{a-chlat1.ads}.
2020 You may use any of these extended characters freely in character or
2021 string literals. In addition, the extended characters that represent
2022 letters can be used in identifiers.
2023
2024 @node Other 8-Bit Codes
2025 @subsection Other 8-Bit Codes
2026
2027 @noindent
2028 GNAT also supports several other 8-bit coding schemes:
2029
2030 @table @asis
2031 @item ISO 8859-2 (Latin-2)
2032 @cindex Latin-2
2033 @cindex ISO 8859-2
2034 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2035 equivalence.
2036
2037 @item ISO 8859-3 (Latin-3)
2038 @cindex Latin-3
2039 @cindex ISO 8859-3
2040 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2041 equivalence.
2042
2043 @item ISO 8859-4 (Latin-4)
2044 @cindex Latin-4
2045 @cindex ISO 8859-4
2046 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2047 equivalence.
2048
2049 @item ISO 8859-5 (Cyrillic)
2050 @cindex ISO 8859-5
2051 @cindex Cyrillic
2052 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2053 lowercase equivalence.
2054
2055 @item ISO 8859-15 (Latin-9)
2056 @cindex ISO 8859-15
2057 @cindex Latin-9
2058 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2059 lowercase equivalence
2060
2061 @item IBM PC (code page 437)
2062 @cindex code page 437
2063 This code page is the normal default for PCs in the U.S. It corresponds
2064 to the original IBM PC character set. This set has some, but not all, of
2065 the extended Latin-1 letters, but these letters do not have the same
2066 encoding as Latin-1. In this mode, these letters are allowed in
2067 identifiers with uppercase and lowercase equivalence.
2068
2069 @item IBM PC (code page 850)
2070 @cindex code page 850
2071 This code page is a modification of 437 extended to include all the
2072 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2073 mode, all these letters are allowed in identifiers with uppercase and
2074 lowercase equivalence.
2075
2076 @item Full Upper 8-bit
2077 Any character in the range 80-FF allowed in identifiers, and all are
2078 considered distinct. In other words, there are no uppercase and lowercase
2079 equivalences in this range. This is useful in conjunction with
2080 certain encoding schemes used for some foreign character sets (e.g.
2081 the typical method of representing Chinese characters on the PC).
2082
2083 @item No Upper-Half
2084 No upper-half characters in the range 80-FF are allowed in identifiers.
2085 This gives Ada 83 compatibility for identifier names.
2086 @end table
2087
2088 @noindent
2089 For precise data on the encodings permitted, and the uppercase and lowercase
2090 equivalences that are recognized, see the file @file{csets.adb} in
2091 the GNAT compiler sources. You will need to obtain a full source release
2092 of GNAT to obtain this file.
2093
2094 @node Wide Character Encodings
2095 @subsection Wide Character Encodings
2096
2097 @noindent
2098 GNAT allows wide character codes to appear in character and string
2099 literals, and also optionally in identifiers, by means of the following
2100 possible encoding schemes:
2101
2102 @table @asis
2103
2104 @item Hex Coding
2105 In this encoding, a wide character is represented by the following five
2106 character sequence:
2107
2108 @smallexample
2109 ESC a b c d
2110 @end smallexample
2111
2112 @noindent
2113 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2114 characters (using uppercase letters) of the wide character code. For
2115 example, ESC A345 is used to represent the wide character with code
2116 @code{16#A345#}.
2117 This scheme is compatible with use of the full Wide_Character set.
2118
2119 @item Upper-Half Coding
2120 @cindex Upper-Half Coding
2121 The wide character with encoding @code{16#abcd#} where the upper bit is on
2122 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2123 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2124 character, but is not required to be in the upper half. This method can
2125 be also used for shift-JIS or EUC, where the internal coding matches the
2126 external coding.
2127
2128 @item Shift JIS Coding
2129 @cindex Shift JIS Coding
2130 A wide character is represented by a two-character sequence,
2131 @code{16#ab#} and
2132 @code{16#cd#}, with the restrictions described for upper-half encoding as
2133 described above. The internal character code is the corresponding JIS
2134 character according to the standard algorithm for Shift-JIS
2135 conversion. Only characters defined in the JIS code set table can be
2136 used with this encoding method.
2137
2138 @item EUC Coding
2139 @cindex EUC Coding
2140 A wide character is represented by a two-character sequence
2141 @code{16#ab#} and
2142 @code{16#cd#}, with both characters being in the upper half. The internal
2143 character code is the corresponding JIS character according to the EUC
2144 encoding algorithm. Only characters defined in the JIS code set table
2145 can be used with this encoding method.
2146
2147 @item UTF-8 Coding
2148 A wide character is represented using
2149 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2150 10646-1/Am.2. Depending on the character value, the representation
2151 is a one, two, or three byte sequence:
2152 @smallexample
2153 @iftex
2154 @leftskip=.7cm
2155 @end iftex
2156 16#0000#-16#007f#: 2#0xxxxxxx#
2157 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2158 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2159
2160 @end smallexample
2161
2162 @noindent
2163 where the xxx bits correspond to the left-padded bits of the
2164 16-bit character value. Note that all lower half ASCII characters
2165 are represented as ASCII bytes and all upper half characters and
2166 other wide characters are represented as sequences of upper-half
2167 (The full UTF-8 scheme allows for encoding 31-bit characters as
2168 6-byte sequences, but in this implementation, all UTF-8 sequences
2169 of four or more bytes length will be treated as illegal).
2170 @item Brackets Coding
2171 In this encoding, a wide character is represented by the following eight
2172 character sequence:
2173
2174 @smallexample
2175 [ " a b c d " ]
2176 @end smallexample
2177
2178 @noindent
2179 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2180 characters (using uppercase letters) of the wide character code. For
2181 example, [``A345''] is used to represent the wide character with code
2182 @code{16#A345#}. It is also possible (though not required) to use the
2183 Brackets coding for upper half characters. For example, the code
2184 @code{16#A3#} can be represented as @code{[``A3'']}.
2185
2186 This scheme is compatible with use of the full Wide_Character set,
2187 and is also the method used for wide character encoding in the standard
2188 ACVC (Ada Compiler Validation Capability) test suite distributions.
2189
2190 @end table
2191
2192 @noindent
2193 Note: Some of these coding schemes do not permit the full use of the
2194 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2195 use of the upper half of the Latin-1 set.
2196
2197 @node File Naming Rules
2198 @section File Naming Rules
2199
2200 @noindent
2201 The default file name is determined by the name of the unit that the
2202 file contains. The name is formed by taking the full expanded name of
2203 the unit and replacing the separating dots with hyphens and using
2204 ^lowercase^uppercase^ for all letters.
2205
2206 An exception arises if the file name generated by the above rules starts
2207 with one of the characters
2208 @ifset vms
2209 A,G,I, or S,
2210 @end ifset
2211 @ifclear vms
2212 a,g,i, or s,
2213 @end ifclear
2214 and the second character is a
2215 minus. In this case, the character ^tilde^dollar sign^ is used in place
2216 of the minus. The reason for this special rule is to avoid clashes with
2217 the standard names for child units of the packages System, Ada,
2218 Interfaces, and GNAT, which use the prefixes
2219 @ifset vms
2220 S- A- I- and G-
2221 @end ifset
2222 @ifclear vms
2223 s- a- i- and g-
2224 @end ifclear
2225 respectively.
2226
2227 The file extension is @file{.ads} for a spec and
2228 @file{.adb} for a body. The following list shows some
2229 examples of these rules.
2230
2231 @table @file
2232 @item main.ads
2233 Main (spec)
2234 @item main.adb
2235 Main (body)
2236 @item arith_functions.ads
2237 Arith_Functions (package spec)
2238 @item arith_functions.adb
2239 Arith_Functions (package body)
2240 @item func-spec.ads
2241 Func.Spec (child package spec)
2242 @item func-spec.adb
2243 Func.Spec (child package body)
2244 @item main-sub.adb
2245 Sub (subunit of Main)
2246 @item ^a~bad.adb^A$BAD.ADB^
2247 A.Bad (child package body)
2248 @end table
2249
2250 @noindent
2251 Following these rules can result in excessively long
2252 file names if corresponding
2253 unit names are long (for example, if child units or subunits are
2254 heavily nested). An option is available to shorten such long file names
2255 (called file name ``krunching''). This may be particularly useful when
2256 programs being developed with GNAT are to be used on operating systems
2257 with limited file name lengths. @xref{Using gnatkr}.
2258
2259 Of course, no file shortening algorithm can guarantee uniqueness over
2260 all possible unit names; if file name krunching is used, it is your
2261 responsibility to ensure no name clashes occur. Alternatively you
2262 can specify the exact file names that you want used, as described
2263 in the next section. Finally, if your Ada programs are migrating from a
2264 compiler with a different naming convention, you can use the gnatchop
2265 utility to produce source files that follow the GNAT naming conventions.
2266 (For details @pxref{Renaming Files Using gnatchop}.)
2267
2268 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2269 systems, case is not significant. So for example on @code{Windows XP}
2270 if the canonical name is @code{main-sub.adb}, you can use the file name
2271 @code{Main-Sub.adb} instead. However, case is significant for other
2272 operating systems, so for example, if you want to use other than
2273 canonically cased file names on a Unix system, you need to follow
2274 the procedures described in the next section.
2275
2276 @node Using Other File Names
2277 @section Using Other File Names
2278 @cindex File names
2279
2280 @noindent
2281 In the previous section, we have described the default rules used by
2282 GNAT to determine the file name in which a given unit resides. It is
2283 often convenient to follow these default rules, and if you follow them,
2284 the compiler knows without being explicitly told where to find all
2285 the files it needs.
2286
2287 However, in some cases, particularly when a program is imported from
2288 another Ada compiler environment, it may be more convenient for the
2289 programmer to specify which file names contain which units. GNAT allows
2290 arbitrary file names to be used by means of the Source_File_Name pragma.
2291 The form of this pragma is as shown in the following examples:
2292 @cindex Source_File_Name pragma
2293
2294 @smallexample @c ada
2295 @cartouche
2296 pragma Source_File_Name (My_Utilities.Stacks,
2297   Spec_File_Name => "myutilst_a.ada");
2298 pragma Source_File_name (My_Utilities.Stacks,
2299   Body_File_Name => "myutilst.ada");
2300 @end cartouche
2301 @end smallexample
2302
2303 @noindent
2304 As shown in this example, the first argument for the pragma is the unit
2305 name (in this example a child unit). The second argument has the form
2306 of a named association. The identifier
2307 indicates whether the file name is for a spec or a body;
2308 the file name itself is given by a string literal.
2309
2310 The source file name pragma is a configuration pragma, which means that
2311 normally it will be placed in the @file{gnat.adc}
2312 file used to hold configuration
2313 pragmas that apply to a complete compilation environment.
2314 For more details on how the @file{gnat.adc} file is created and used
2315 see @ref{Handling of Configuration Pragmas}.
2316 @cindex @file{gnat.adc}
2317
2318 @ifclear vms
2319 GNAT allows completely arbitrary file names to be specified using the
2320 source file name pragma. However, if the file name specified has an
2321 extension other than @file{.ads} or @file{.adb} it is necessary to use
2322 a special syntax when compiling the file. The name in this case must be
2323 preceded by the special sequence @code{-x} followed by a space and the name
2324 of the language, here @code{ada}, as in:
2325
2326 @smallexample
2327 $ gcc -c -x ada peculiar_file_name.sim
2328 @end smallexample
2329 @end ifclear
2330
2331 @noindent
2332 @command{gnatmake} handles non-standard file names in the usual manner (the
2333 non-standard file name for the main program is simply used as the
2334 argument to gnatmake). Note that if the extension is also non-standard,
2335 then it must be included in the gnatmake command, it may not be omitted.
2336
2337 @node Alternative File Naming Schemes
2338 @section Alternative File Naming Schemes
2339 @cindex File naming schemes, alternative
2340 @cindex File names
2341
2342 In the previous section, we described the use of the @code{Source_File_Name}
2343 pragma to allow arbitrary names to be assigned to individual source files.
2344 However, this approach requires one pragma for each file, and especially in
2345 large systems can result in very long @file{gnat.adc} files, and also create
2346 a maintenance problem.
2347
2348 GNAT also provides a facility for specifying systematic file naming schemes
2349 other than the standard default naming scheme previously described. An
2350 alternative scheme for naming is specified by the use of
2351 @code{Source_File_Name} pragmas having the following format:
2352 @cindex Source_File_Name pragma
2353
2354 @smallexample @c ada
2355 pragma Source_File_Name (
2356    Spec_File_Name  => FILE_NAME_PATTERN
2357  [,Casing          => CASING_SPEC]
2358  [,Dot_Replacement => STRING_LITERAL]);
2359
2360 pragma Source_File_Name (
2361    Body_File_Name  => FILE_NAME_PATTERN
2362  [,Casing          => CASING_SPEC]
2363  [,Dot_Replacement => STRING_LITERAL]);
2364
2365 pragma Source_File_Name (
2366    Subunit_File_Name  => FILE_NAME_PATTERN
2367  [,Casing             => CASING_SPEC]
2368  [,Dot_Replacement    => STRING_LITERAL]);
2369
2370 FILE_NAME_PATTERN ::= STRING_LITERAL
2371 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2372 @end smallexample
2373
2374 @noindent
2375 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2376 It contains a single asterisk character, and the unit name is substituted
2377 systematically for this asterisk. The optional parameter
2378 @code{Casing} indicates
2379 whether the unit name is to be all upper-case letters, all lower-case letters,
2380 or mixed-case. If no
2381 @code{Casing} parameter is used, then the default is all
2382 ^lower-case^upper-case^.
2383
2384 The optional @code{Dot_Replacement} string is used to replace any periods
2385 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2386 argument is used then separating dots appear unchanged in the resulting
2387 file name.
2388 Although the above syntax indicates that the
2389 @code{Casing} argument must appear
2390 before the @code{Dot_Replacement} argument, but it
2391 is also permissible to write these arguments in the opposite order.
2392
2393 As indicated, it is possible to specify different naming schemes for
2394 bodies, specs, and subunits. Quite often the rule for subunits is the
2395 same as the rule for bodies, in which case, there is no need to give
2396 a separate @code{Subunit_File_Name} rule, and in this case the
2397 @code{Body_File_name} rule is used for subunits as well.
2398
2399 The separate rule for subunits can also be used to implement the rather
2400 unusual case of a compilation environment (e.g. a single directory) which
2401 contains a subunit and a child unit with the same unit name. Although
2402 both units cannot appear in the same partition, the Ada Reference Manual
2403 allows (but does not require) the possibility of the two units coexisting
2404 in the same environment.
2405
2406 The file name translation works in the following steps:
2407
2408 @itemize @bullet
2409
2410 @item
2411 If there is a specific @code{Source_File_Name} pragma for the given unit,
2412 then this is always used, and any general pattern rules are ignored.
2413
2414 @item
2415 If there is a pattern type @code{Source_File_Name} pragma that applies to
2416 the unit, then the resulting file name will be used if the file exists. If
2417 more than one pattern matches, the latest one will be tried first, and the
2418 first attempt resulting in a reference to a file that exists will be used.
2419
2420 @item
2421 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2422 for which the corresponding file exists, then the standard GNAT default
2423 naming rules are used.
2424
2425 @end itemize
2426
2427 @noindent
2428 As an example of the use of this mechanism, consider a commonly used scheme
2429 in which file names are all lower case, with separating periods copied
2430 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2431 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2432 two pragmas appear:
2433
2434 @smallexample @c ada
2435 pragma Source_File_Name
2436   (Spec_File_Name => "*.1.ada");
2437 pragma Source_File_Name
2438   (Body_File_Name => "*.2.ada");
2439 @end smallexample
2440
2441 @noindent
2442 The default GNAT scheme is actually implemented by providing the following
2443 default pragmas internally:
2444
2445 @smallexample @c ada
2446 pragma Source_File_Name
2447   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2448 pragma Source_File_Name
2449   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2450 @end smallexample
2451
2452 @noindent
2453 Our final example implements a scheme typically used with one of the
2454 Ada 83 compilers, where the separator character for subunits was ``__''
2455 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2456 by adding @file{.ADA}, and subunits by
2457 adding @file{.SEP}. All file names were
2458 upper case. Child units were not present of course since this was an
2459 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2460 the same double underscore separator for child units.
2461
2462 @smallexample @c ada
2463 pragma Source_File_Name
2464   (Spec_File_Name => "*_.ADA",
2465    Dot_Replacement => "__",
2466    Casing = Uppercase);
2467 pragma Source_File_Name
2468   (Body_File_Name => "*.ADA",
2469    Dot_Replacement => "__",
2470    Casing = Uppercase);
2471 pragma Source_File_Name
2472   (Subunit_File_Name => "*.SEP",
2473    Dot_Replacement => "__",
2474    Casing = Uppercase);
2475 @end smallexample
2476
2477 @node Generating Object Files
2478 @section Generating Object Files
2479
2480 @noindent
2481 An Ada program consists of a set of source files, and the first step in
2482 compiling the program is to generate the corresponding object files.
2483 These are generated by compiling a subset of these source files.
2484 The files you need to compile are the following:
2485
2486 @itemize @bullet
2487 @item
2488 If a package spec has no body, compile the package spec to produce the
2489 object file for the package.
2490
2491 @item
2492 If a package has both a spec and a body, compile the body to produce the
2493 object file for the package. The source file for the package spec need
2494 not be compiled in this case because there is only one object file, which
2495 contains the code for both the spec and body of the package.
2496
2497 @item
2498 For a subprogram, compile the subprogram body to produce the object file
2499 for the subprogram. The spec, if one is present, is as usual in a
2500 separate file, and need not be compiled.
2501
2502 @item
2503 @cindex Subunits
2504 In the case of subunits, only compile the parent unit. A single object
2505 file is generated for the entire subunit tree, which includes all the
2506 subunits.
2507
2508 @item
2509 Compile child units independently of their parent units
2510 (though, of course, the spec of all the ancestor unit must be present in order
2511 to compile a child unit).
2512
2513 @item
2514 @cindex Generics
2515 Compile generic units in the same manner as any other units. The object
2516 files in this case are small dummy files that contain at most the
2517 flag used for elaboration checking. This is because GNAT always handles generic
2518 instantiation by means of macro expansion. However, it is still necessary to
2519 compile generic units, for dependency checking and elaboration purposes.
2520 @end itemize
2521
2522 @noindent
2523 The preceding rules describe the set of files that must be compiled to
2524 generate the object files for a program. Each object file has the same
2525 name as the corresponding source file, except that the extension is
2526 @file{.o} as usual.
2527
2528 You may wish to compile other files for the purpose of checking their
2529 syntactic and semantic correctness. For example, in the case where a
2530 package has a separate spec and body, you would not normally compile the
2531 spec. However, it is convenient in practice to compile the spec to make
2532 sure it is error-free before compiling clients of this spec, because such
2533 compilations will fail if there is an error in the spec.
2534
2535 GNAT provides an option for compiling such files purely for the
2536 purposes of checking correctness; such compilations are not required as
2537 part of the process of building a program. To compile a file in this
2538 checking mode, use the @option{-gnatc} switch.
2539
2540 @node Source Dependencies
2541 @section Source Dependencies
2542
2543 @noindent
2544 A given object file clearly depends on the source file which is compiled
2545 to produce it. Here we are using @dfn{depends} in the sense of a typical
2546 @code{make} utility; in other words, an object file depends on a source
2547 file if changes to the source file require the object file to be
2548 recompiled.
2549 In addition to this basic dependency, a given object may depend on
2550 additional source files as follows:
2551
2552 @itemize @bullet
2553 @item
2554 If a file being compiled @code{with}'s a unit @var{X}, the object file
2555 depends on the file containing the spec of unit @var{X}. This includes
2556 files that are @code{with}'ed implicitly either because they are parents
2557 of @code{with}'ed child units or they are run-time units required by the
2558 language constructs used in a particular unit.
2559
2560 @item
2561 If a file being compiled instantiates a library level generic unit, the
2562 object file depends on both the spec and body files for this generic
2563 unit.
2564
2565 @item
2566 If a file being compiled instantiates a generic unit defined within a
2567 package, the object file depends on the body file for the package as
2568 well as the spec file.
2569
2570 @item
2571 @findex Inline
2572 @cindex @option{-gnatn} switch
2573 If a file being compiled contains a call to a subprogram for which
2574 pragma @code{Inline} applies and inlining is activated with the
2575 @option{-gnatn} switch, the object file depends on the file containing the
2576 body of this subprogram as well as on the file containing the spec. Note
2577 that for inlining to actually occur as a result of the use of this switch,
2578 it is necessary to compile in optimizing mode.
2579
2580 @cindex @option{-gnatN} switch
2581 The use of @option{-gnatN} activates a more extensive inlining optimization
2582 that is performed by the front end of the compiler. This inlining does
2583 not require that the code generation be optimized. Like @option{-gnatn},
2584 the use of this switch generates additional dependencies.
2585 Note that
2586 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2587 to specify both options.
2588
2589 @item
2590 If an object file O  depends on the proper body of a subunit through inlining
2591 or instantiation, it depends on the parent unit of the subunit. This means that
2592 any modification of the parent unit or one of its subunits affects the
2593 compilation of O.
2594
2595 @item
2596 The object file for a parent unit depends on all its subunit body files.
2597
2598 @item
2599 The previous two rules meant that for purposes of computing dependencies and
2600 recompilation, a body and all its subunits are treated as an indivisible whole.
2601
2602 @noindent
2603 These rules are applied transitively: if unit @code{A} @code{with}'s
2604 unit @code{B}, whose elaboration calls an inlined procedure in package
2605 @code{C}, the object file for unit @code{A} will depend on the body of
2606 @code{C}, in file @file{c.adb}.
2607
2608 The set of dependent files described by these rules includes all the
2609 files on which the unit is semantically dependent, as described in the
2610 Ada 95 Language Reference Manual. However, it is a superset of what the
2611 ARM describes, because it includes generic, inline, and subunit dependencies.
2612
2613 An object file must be recreated by recompiling the corresponding source
2614 file if any of the source files on which it depends are modified. For
2615 example, if the @code{make} utility is used to control compilation,
2616 the rule for an Ada object file must mention all the source files on
2617 which the object file depends, according to the above definition.
2618 The determination of the necessary
2619 recompilations is done automatically when one uses @command{gnatmake}.
2620 @end itemize
2621
2622 @node The Ada Library Information Files
2623 @section The Ada Library Information Files
2624 @cindex Ada Library Information files
2625 @cindex @file{ALI} files
2626
2627 @noindent
2628 Each compilation actually generates two output files. The first of these
2629 is the normal object file that has a @file{.o} extension. The second is a
2630 text file containing full dependency information. It has the same
2631 name as the source file, but an @file{.ali} extension.
2632 This file is known as the Ada Library Information (@file{ALI}) file.
2633 The following information is contained in the @file{ALI} file.
2634
2635 @itemize @bullet
2636 @item
2637 Version information (indicates which version of GNAT was used to compile
2638 the unit(s) in question)
2639
2640 @item
2641 Main program information (including priority and time slice settings,
2642 as well as the wide character encoding used during compilation).
2643
2644 @item
2645 List of arguments used in the @command{gcc} command for the compilation
2646
2647 @item
2648 Attributes of the unit, including configuration pragmas used, an indication
2649 of whether the compilation was successful, exception model used etc.
2650
2651 @item
2652 A list of relevant restrictions applying to the unit (used for consistency)
2653 checking.
2654
2655 @item
2656 Categorization information (e.g. use of pragma @code{Pure}).
2657
2658 @item
2659 Information on all @code{with}'ed units, including presence of
2660 @code{Elaborate} or @code{Elaborate_All} pragmas.
2661
2662 @item
2663 Information from any @code{Linker_Options} pragmas used in the unit
2664
2665 @item
2666 Information on the use of @code{Body_Version} or @code{Version}
2667 attributes in the unit.
2668
2669 @item
2670 Dependency information. This is a list of files, together with
2671 time stamp and checksum information. These are files on which
2672 the unit depends in the sense that recompilation is required
2673 if any of these units are modified.
2674
2675 @item
2676 Cross-reference data. Contains information on all entities referenced
2677 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2678 provide cross-reference information.
2679
2680 @end itemize
2681
2682 @noindent
2683 For a full detailed description of the format of the @file{ALI} file,
2684 see the source of the body of unit @code{Lib.Writ}, contained in file
2685 @file{lib-writ.adb} in the GNAT compiler sources.
2686
2687 @node Binding an Ada Program
2688 @section Binding an Ada Program
2689
2690 @noindent
2691 When using languages such as C and C++, once the source files have been
2692 compiled the only remaining step in building an executable program
2693 is linking the object modules together. This means that it is possible to
2694 link an inconsistent version of a program, in which two units have
2695 included different versions of the same header.
2696
2697 The rules of Ada do not permit such an inconsistent program to be built.
2698 For example, if two clients have different versions of the same package,
2699 it is illegal to build a program containing these two clients.
2700 These rules are enforced by the GNAT binder, which also determines an
2701 elaboration order consistent with the Ada rules.
2702
2703 The GNAT binder is run after all the object files for a program have
2704 been created. It is given the name of the main program unit, and from
2705 this it determines the set of units required by the program, by reading the
2706 corresponding ALI files. It generates error messages if the program is
2707 inconsistent or if no valid order of elaboration exists.
2708
2709 If no errors are detected, the binder produces a main program, in Ada by
2710 default, that contains calls to the elaboration procedures of those
2711 compilation unit that require them, followed by
2712 a call to the main program. This Ada program is compiled to generate the
2713 object file for the main program. The name of
2714 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2715 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2716 main program unit.
2717
2718 Finally, the linker is used to build the resulting executable program,
2719 using the object from the main program from the bind step as well as the
2720 object files for the Ada units of the program.
2721
2722 @node Mixed Language Programming
2723 @section Mixed Language Programming
2724 @cindex Mixed Language Programming
2725
2726 @noindent
2727 This section describes how to develop a mixed-language program,
2728 specifically one that comprises units in both Ada and C.
2729
2730 @menu
2731 * Interfacing to C::
2732 * Calling Conventions::
2733 @end menu
2734
2735 @node Interfacing to C
2736 @subsection Interfacing to C
2737 @noindent
2738 Interfacing Ada with a foreign language such as C involves using
2739 compiler directives to import and/or export entity definitions in each
2740 language---using @code{extern} statements in C, for instance, and the
2741 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2742 a full treatment of these topics, read Appendix B, section 1 of the Ada
2743 95 Language Reference Manual.
2744
2745 There are two ways to build a program using GNAT that contains some Ada
2746 sources and some foreign language sources, depending on whether or not
2747 the main subprogram is written in Ada.  Here is a source example with
2748 the main subprogram in Ada:
2749
2750 @smallexample
2751 /* file1.c */
2752 #include <stdio.h>
2753
2754 void print_num (int num)
2755 @{
2756   printf ("num is %d.\n", num);
2757   return;
2758 @}
2759
2760 /* file2.c */
2761
2762 /* num_from_Ada is declared in my_main.adb */
2763 extern int num_from_Ada;
2764
2765 int get_num (void)
2766 @{
2767   return num_from_Ada;
2768 @}
2769 @end smallexample
2770
2771 @smallexample @c ada
2772 --  my_main.adb
2773 procedure My_Main is
2774
2775    --  Declare then export an Integer entity called num_from_Ada
2776    My_Num : Integer := 10;
2777    pragma Export (C, My_Num, "num_from_Ada");
2778
2779    --  Declare an Ada function spec for Get_Num, then use
2780    --  C function get_num for the implementation.
2781    function Get_Num return Integer;
2782    pragma Import (C, Get_Num, "get_num");
2783
2784    --  Declare an Ada procedure spec for Print_Num, then use
2785    --  C function print_num for the implementation.
2786    procedure Print_Num (Num : Integer);
2787    pragma Import (C, Print_Num, "print_num");
2788
2789 begin
2790    Print_Num (Get_Num);
2791 end My_Main;
2792 @end smallexample
2793
2794 @enumerate
2795 @item
2796 To build this example, first compile the foreign language files to
2797 generate object files:
2798 @smallexample
2799 ^gcc -c file1.c^gcc -c FILE1.C^
2800 ^gcc -c file2.c^gcc -c FILE2.C^
2801 @end smallexample
2802
2803 @item
2804 Then, compile the Ada units to produce a set of object files and ALI
2805 files:
2806 @smallexample
2807 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2808 @end smallexample
2809
2810 @item
2811 Run the Ada binder on the Ada main program:
2812 @smallexample
2813 gnatbind my_main.ali
2814 @end smallexample
2815
2816 @item
2817 Link the Ada main program, the Ada objects and the other language
2818 objects:
2819 @smallexample
2820 gnatlink my_main.ali file1.o file2.o
2821 @end smallexample
2822 @end enumerate
2823
2824 The last three steps can be grouped in a single command:
2825 @smallexample
2826 gnatmake my_main.adb -largs file1.o file2.o
2827 @end smallexample
2828
2829 @cindex Binder output file
2830 @noindent
2831 If the main program is in a language other than Ada, then you may have
2832 more than one entry point into the Ada subsystem. You must use a special
2833 binder option to generate callable routines that initialize and
2834 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2835 Calls to the initialization and finalization routines must be inserted
2836 in the main program, or some other appropriate point in the code. The
2837 call to initialize the Ada units must occur before the first Ada
2838 subprogram is called, and the call to finalize the Ada units must occur
2839 after the last Ada subprogram returns. The binder will place the
2840 initialization and finalization subprograms into the
2841 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2842 sources.  To illustrate, we have the following example:
2843
2844 @smallexample
2845 /* main.c */
2846 extern void adainit (void);
2847 extern void adafinal (void);
2848 extern int add (int, int);
2849 extern int sub (int, int);
2850
2851 int main (int argc, char *argv[])
2852 @{
2853   int a = 21, b = 7;
2854
2855   adainit();
2856
2857   /* Should print "21 + 7 = 28" */
2858   printf ("%d + %d = %d\n", a, b, add (a, b));
2859   /* Should print "21 - 7 = 14" */
2860   printf ("%d - %d = %d\n", a, b, sub (a, b));
2861
2862   adafinal();
2863 @}
2864 @end smallexample
2865
2866 @smallexample @c ada
2867 --  unit1.ads
2868 package Unit1 is
2869    function Add (A, B : Integer) return Integer;
2870    pragma Export (C, Add, "add");
2871 end Unit1;
2872
2873 --  unit1.adb
2874 package body Unit1 is
2875    function Add (A, B : Integer) return Integer is
2876    begin
2877       return A + B;
2878    end Add;
2879 end Unit1;
2880
2881 --  unit2.ads
2882 package Unit2 is
2883    function Sub (A, B : Integer) return Integer;
2884    pragma Export (C, Sub, "sub");
2885 end Unit2;
2886
2887 --  unit2.adb
2888 package body Unit2 is
2889    function Sub (A, B : Integer) return Integer is
2890    begin
2891       return A - B;
2892    end Sub;
2893 end Unit2;
2894 @end smallexample
2895
2896 @enumerate
2897 @item
2898 The build procedure for this application is similar to the last
2899 example's.  First, compile the foreign language files to generate object
2900 files:
2901 @smallexample
2902 ^gcc -c main.c^gcc -c main.c^
2903 @end smallexample
2904
2905 @item
2906 Next, compile the Ada units to produce a set of object files and ALI
2907 files:
2908 @smallexample
2909 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2910 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2911 @end smallexample
2912
2913 @item
2914 Run the Ada binder on every generated ALI file.  Make sure to use the
2915 @option{-n} option to specify a foreign main program:
2916 @smallexample
2917 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2918 @end smallexample
2919
2920 @item
2921 Link the Ada main program, the Ada objects and the foreign language
2922 objects. You need only list the last ALI file here:
2923 @smallexample
2924 gnatlink unit2.ali main.o -o exec_file
2925 @end smallexample
2926
2927 This procedure yields a binary executable called @file{exec_file}.
2928 @end enumerate
2929
2930 @node Calling Conventions
2931 @subsection Calling Conventions
2932 @cindex Foreign Languages
2933 @cindex Calling Conventions
2934 GNAT follows standard calling sequence conventions and will thus interface
2935 to any other language that also follows these conventions. The following
2936 Convention identifiers are recognized by GNAT:
2937
2938 @table @code
2939 @cindex Interfacing to Ada
2940 @cindex Other Ada compilers
2941 @cindex Convention Ada
2942 @item Ada
2943 This indicates that the standard Ada calling sequence will be
2944 used and all Ada data items may be passed without any limitations in the
2945 case where GNAT is used to generate both the caller and callee. It is also
2946 possible to mix GNAT generated code and code generated by another Ada
2947 compiler. In this case, the data types should be restricted to simple
2948 cases, including primitive types. Whether complex data types can be passed
2949 depends on the situation. Probably it is safe to pass simple arrays, such
2950 as arrays of integers or floats. Records may or may not work, depending
2951 on whether both compilers lay them out identically. Complex structures
2952 involving variant records, access parameters, tasks, or protected types,
2953 are unlikely to be able to be passed.
2954
2955 Note that in the case of GNAT running
2956 on a platform that supports HP Ada 83, a higher degree of compatibility
2957 can be guaranteed, and in particular records are layed out in an identical
2958 manner in the two compilers. Note also that if output from two different
2959 compilers is mixed, the program is responsible for dealing with elaboration
2960 issues. Probably the safest approach is to write the main program in the
2961 version of Ada other than GNAT, so that it takes care of its own elaboration
2962 requirements, and then call the GNAT-generated adainit procedure to ensure
2963 elaboration of the GNAT components. Consult the documentation of the other
2964 Ada compiler for further details on elaboration.
2965
2966 However, it is not possible to mix the tasking run time of GNAT and
2967 HP Ada 83, All the tasking operations must either be entirely within
2968 GNAT compiled sections of the program, or entirely within HP Ada 83
2969 compiled sections of the program.
2970
2971 @cindex Interfacing to Assembly
2972 @cindex Convention Assembler
2973 @item Assembler
2974 Specifies assembler as the convention. In practice this has the
2975 same effect as convention Ada (but is not equivalent in the sense of being
2976 considered the same convention).
2977
2978 @cindex Convention Asm
2979 @findex Asm
2980 @item Asm
2981 Equivalent to Assembler.
2982
2983 @cindex Interfacing to COBOL
2984 @cindex Convention COBOL
2985 @findex COBOL
2986 @item COBOL
2987 Data will be passed according to the conventions described
2988 in section B.4 of the Ada 95 Reference Manual.
2989
2990 @findex C
2991 @cindex Interfacing to C
2992 @cindex Convention C
2993 @item C
2994 Data will be passed according to the conventions described
2995 in section B.3 of the Ada 95 Reference Manual.
2996
2997 A note on interfacing to a C ``varargs'' function:
2998 @findex C varargs function
2999 @cindex Interfacing to C varargs function
3000 @cindex varargs function interfaces
3001
3002 @itemize @bullet
3003 @item
3004 In C, @code{varargs} allows a function to take a variable number of
3005 arguments. There is no direct equivalent in this to Ada. One
3006 approach that can be used is to create a C wrapper for each
3007 different profile and then interface to this C wrapper. For
3008 example, to print an @code{int} value using @code{printf},
3009 create a C function @code{printfi} that takes two arguments, a
3010 pointer to a string and an int, and calls @code{printf}.
3011 Then in the Ada program, use pragma @code{Import} to
3012 interface to @code{printfi}.
3013
3014 @item
3015 It may work on some platforms to directly interface to
3016 a @code{varargs} function by providing a specific Ada profile
3017 for a particular call. However, this does not work on
3018 all platforms, since there is no guarantee that the
3019 calling sequence for a two argument normal C function
3020 is the same as for calling a @code{varargs} C function with
3021 the same two arguments.
3022 @end itemize
3023
3024 @cindex Convention Default
3025 @findex Default
3026 @item Default
3027 Equivalent to C.
3028
3029 @cindex Convention External
3030 @findex External
3031 @item External
3032 Equivalent to C.
3033
3034 @ifclear vms
3035 @findex C++
3036 @cindex Interfacing to C++
3037 @cindex Convention C++
3038 @item CPP
3039 This stands for C++. For most purposes this is identical to C.
3040 See the separate description of the specialized GNAT pragmas relating to
3041 C++ interfacing for further details.
3042 @end ifclear
3043
3044 @findex Fortran
3045 @cindex Interfacing to Fortran
3046 @cindex Convention Fortran
3047 @item Fortran
3048 Data will be passed according to the conventions described
3049 in section B.5 of the Ada 95 Reference Manual.
3050
3051 @item Intrinsic
3052 This applies to an intrinsic operation, as defined in the Ada 95
3053 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
3054 this means that the body of the subprogram is provided by the compiler itself,
3055 usually by means of an efficient code sequence, and that the user does not
3056 supply an explicit body for it. In an application program, the pragma can
3057 only be applied to the following two sets of names, which the GNAT compiler
3058 recognizes.
3059
3060 @itemize @bullet
3061 @item
3062 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
3063 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
3064 two formal parameters. The
3065 first one must be a signed integer type or a modular type with a binary
3066 modulus, and the second parameter must be of type Natural.
3067 The return type must be the same as the type of the first argument. The size
3068 of this type can only be 8, 16, 32, or 64.
3069 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3070 The corresponding operator declaration must have parameters and result type
3071 that have the same root numeric type (for example, all three are long_float
3072 types). This simplifies the definition of operations that use type checking
3073 to perform dimensional checks:
3074
3075 @smallexample @c ada
3076 type Distance is new Long_Float;
3077 type Time     is new Long_Float;
3078 type Velocity is new Long_Float;
3079 function "/" (D : Distance; T : Time)
3080   return Velocity;
3081 pragma Import (Intrinsic, "/");
3082 @end smallexample
3083
3084 @noindent
3085 This common idiom is often programmed with a generic definition and an
3086 explicit body. The pragma makes it simpler to introduce such declarations.
3087 It incurs no overhead in compilation time or code size, because it is
3088 implemented as a single machine instruction.
3089 @end itemize
3090 @noindent
3091
3092 @ifset unw
3093 @findex Stdcall
3094 @cindex Convention Stdcall
3095 @item Stdcall
3096 This is relevant only to Windows XP/2000/NT/95 implementations of GNAT,
3097 and specifies that the @code{Stdcall} calling sequence will be used,
3098 as defined by the NT API. Nevertheless, to ease building
3099 cross-platform bindings this convention will be handled as a @code{C} calling
3100 convention on non Windows platforms.
3101
3102 @findex DLL
3103 @cindex Convention DLL
3104 @item DLL
3105 This is equivalent to @code{Stdcall}.
3106
3107 @findex Win32
3108 @cindex Convention Win32
3109 @item Win32
3110 This is equivalent to @code{Stdcall}.
3111 @end ifset
3112
3113 @findex Stubbed
3114 @cindex Convention Stubbed
3115 @item Stubbed
3116 This is a special convention that indicates that the compiler
3117 should provide a stub body that raises @code{Program_Error}.
3118 @end table
3119
3120 @noindent
3121 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3122 that can be used to parametrize conventions and allow additional synonyms
3123 to be specified. For example if you have legacy code in which the convention
3124 identifier Fortran77 was used for Fortran, you can use the configuration
3125 pragma:
3126
3127 @smallexample @c ada
3128 pragma Convention_Identifier (Fortran77, Fortran);
3129 @end smallexample
3130
3131 @noindent
3132 And from now on the identifier Fortran77 may be used as a convention
3133 identifier (for example in an @code{Import} pragma) with the same
3134 meaning as Fortran.
3135
3136 @ifclear vms
3137 @node Building Mixed Ada & C++ Programs
3138 @section Building Mixed Ada and C++ Programs
3139
3140 @noindent
3141 A programmer inexperienced with mixed-language development may find that
3142 building an application containing both Ada and C++ code can be a
3143 challenge. As a matter of fact, interfacing with C++ has not been
3144 standardized in the Ada 95 Reference Manual due to the immaturity of --
3145 and lack of standards for -- C++ at the time. This section gives a few
3146 hints that should make this task easier. The first section addresses
3147 the differences regarding interfacing with C. The second section
3148 looks into the delicate problem of linking the complete application from
3149 its Ada and C++ parts. The last section gives some hints on how the GNAT
3150 run time can be adapted in order to allow inter-language dispatching
3151 with a new C++ compiler.
3152
3153 @menu
3154 * Interfacing to C++::
3155 * Linking a Mixed C++ & Ada Program::
3156 * A Simple Example::
3157 * Adapting the Run Time to a New C++ Compiler::
3158 @end menu
3159
3160 @node Interfacing to C++
3161 @subsection Interfacing to C++
3162
3163 @noindent
3164 GNAT supports interfacing with C++ compilers generating code that is
3165 compatible with the standard Application Binary Interface of the given
3166 platform.
3167
3168 @noindent
3169 Interfacing can be done at 3 levels: simple data, subprograms, and
3170 classes. In the first two cases, GNAT offers a specific @var{Convention
3171 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3172 the names of subprograms, and currently, GNAT does not provide any help
3173 to solve the demangling problem. This problem can be addressed in two
3174 ways:
3175 @itemize @bullet
3176 @item
3177 by modifying the C++ code in order to force a C convention using
3178 the @code{extern "C"} syntax.
3179
3180 @item
3181 by figuring out the mangled name and use it as the Link_Name argument of
3182 the pragma import.
3183 @end itemize
3184
3185 @noindent
3186 Interfacing at the class level can be achieved by using the GNAT specific
3187 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3188 Reference Manual for additional information.
3189
3190 @node Linking a Mixed C++ & Ada Program
3191 @subsection Linking a Mixed C++ & Ada Program
3192
3193 @noindent
3194 Usually the linker of the C++ development system must be used to link
3195 mixed applications because most C++ systems will resolve elaboration
3196 issues (such as calling constructors on global class instances)
3197 transparently during the link phase. GNAT has been adapted to ease the
3198 use of a foreign linker for the last phase. Three cases can be
3199 considered:
3200 @enumerate
3201
3202 @item
3203 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3204 The C++ linker can simply be called by using the C++ specific driver
3205 called @code{c++}. Note that this setup is not very common because it
3206 may involve recompiling the whole GCC tree from sources, which makes it
3207 harder to upgrade the compilation system for one language without
3208 destabilizing the other.
3209
3210 @smallexample
3211 $ c++ -c file1.C
3212 $ c++ -c file2.C
3213 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3214 @end smallexample
3215
3216 @item
3217 Using GNAT and G++ from two different GCC installations: If both
3218 compilers are on the PATH, the previous method may be used. It is
3219 important to note that environment variables such as C_INCLUDE_PATH,
3220 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3221 at the same time and may make one of the two compilers operate
3222 improperly if set during invocation of the wrong compiler.  It is also
3223 very important that the linker uses the proper @file{libgcc.a} GCC
3224 library -- that is, the one from the C++ compiler installation. The
3225 implicit link command as suggested in the gnatmake command from the
3226 former example can be replaced by an explicit link command with the
3227 full-verbosity option in order to verify which library is used:
3228 @smallexample
3229 $ gnatbind ada_unit
3230 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3231 @end smallexample
3232 If there is a problem due to interfering environment variables, it can
3233 be worked around by using an intermediate script. The following example
3234 shows the proper script to use when GNAT has not been installed at its
3235 default location and g++ has been installed at its default location:
3236
3237 @smallexample
3238 $ cat ./my_script
3239 #!/bin/sh
3240 unset BINUTILS_ROOT
3241 unset GCC_ROOT
3242 c++ $*
3243 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3244 @end smallexample
3245
3246 @item
3247 Using a non-GNU C++ compiler: The commands previously described can be
3248 used to insure that the C++ linker is used. Nonetheless, you need to add
3249 a few more parameters to the link command line, depending on the exception
3250 mechanism used.
3251
3252 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3253 to the libgcc libraries are required:
3254
3255 @smallexample
3256 $ cat ./my_script
3257 #!/bin/sh
3258 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3259 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3260 @end smallexample
3261
3262 Where CC is the name of the non-GNU C++ compiler.
3263
3264 If the @code{zero cost} exception mechanism is used, and the platform
3265 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3266 paths to more objects are required:
3267
3268 @smallexample
3269 $ cat ./my_script
3270 #!/bin/sh
3271 CC `gcc -print-file-name=crtbegin.o` $* \
3272 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3273 `gcc -print-file-name=crtend.o`
3274 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3275 @end smallexample
3276
3277 If the @code{zero cost} exception mechanism is used, and the platform
3278 doesn't support automatic registration of exception tables (e.g. HP-UX,
3279 Tru64 or AIX), the simple approach described above will not work and
3280 a pre-linking phase using GNAT will be necessary.
3281
3282 @end enumerate
3283
3284 @node A Simple Example
3285 @subsection  A Simple Example
3286 @noindent
3287 The following example, provided as part of the GNAT examples, shows how
3288 to achieve procedural interfacing between Ada and C++ in both
3289 directions. The C++ class A has two methods. The first method is exported
3290 to Ada by the means of an extern C wrapper function. The second method
3291 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3292 a limited record with a layout comparable to the C++ class. The Ada
3293 subprogram, in turn, calls the C++ method. So, starting from the C++
3294 main program, the process passes back and forth between the two
3295 languages.
3296
3297 @noindent
3298 Here are the compilation commands:
3299 @smallexample
3300 $ gnatmake -c simple_cpp_interface
3301 $ c++ -c cpp_main.C
3302 $ c++ -c ex7.C
3303 $ gnatbind -n simple_cpp_interface
3304 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3305       -lstdc++ ex7.o cpp_main.o
3306 @end smallexample
3307
3308 @noindent
3309 Here are the corresponding sources:
3310 @smallexample
3311
3312 //cpp_main.C
3313
3314 #include "ex7.h"
3315
3316 extern "C" @{
3317   void adainit (void);
3318   void adafinal (void);
3319   void method1 (A *t);
3320 @}
3321
3322 void method1 (A *t)
3323 @{
3324   t->method1 ();
3325 @}
3326
3327 int main ()
3328 @{
3329   A obj;
3330   adainit ();
3331   obj.method2 (3030);
3332   adafinal ();
3333 @}
3334
3335 //ex7.h
3336
3337 class Origin @{
3338  public:
3339   int o_value;
3340 @};
3341 class A : public Origin @{
3342  public:
3343   void method1 (void);
3344   void method2 (int v);
3345   A();
3346   int   a_value;
3347 @};
3348
3349 //ex7.C
3350
3351 #include "ex7.h"
3352 #include <stdio.h>
3353
3354 extern "C" @{ void ada_method2 (A *t, int v);@}
3355
3356 void A::method1 (void)
3357 @{
3358   a_value = 2020;
3359   printf ("in A::method1, a_value = %d \n",a_value);
3360
3361 @}
3362
3363 void A::method2 (int v)
3364 @{
3365    ada_method2 (this, v);
3366    printf ("in A::method2, a_value = %d \n",a_value);
3367
3368 @}
3369
3370 A::A(void)
3371 @{
3372    a_value = 1010;
3373   printf ("in A::A, a_value = %d \n",a_value);
3374 @}
3375
3376 -- Ada sources
3377 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3378
3379    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3380    @b{begin}
3381       Method1 (This);
3382       This.A_Value := V;
3383    @b{end} Ada_Method2;
3384
3385 @b{end} Simple_Cpp_Interface;
3386
3387 @b{package} Simple_Cpp_Interface @b{is}
3388    @b{type} A @b{is} @b{limited}
3389       @b{record}
3390          O_Value : Integer;
3391          A_Value : Integer;
3392       @b{end} @b{record};
3393    @b{pragma} Convention (C, A);
3394
3395    @b{procedure} Method1 (This : @b{in} @b{out} A);
3396    @b{pragma} Import (C, Method1);
3397
3398    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3399    @b{pragma} Export (C, Ada_Method2);
3400
3401 @b{end} Simple_Cpp_Interface;
3402 @end smallexample
3403
3404 @node Adapting the Run Time to a New C++ Compiler
3405 @subsection Adapting the Run Time to a New C++ Compiler
3406 @noindent
3407 GNAT offers the capability to derive Ada 95 tagged types directly from
3408 preexisting C++ classes and . See ``Interfacing with C++'' in the
3409 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3410 such a goal
3411 has been made user configurable through a GNAT library unit
3412 @code{Interfaces.CPP}. The default version of this file is adapted to
3413 the GNU C++ compiler. Internal knowledge of the virtual
3414 table layout used by the new C++ compiler is needed to configure
3415 properly this unit. The Interface of this unit is known by the compiler
3416 and cannot be changed except for the value of the constants defining the
3417 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3418 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3419 of this unit for more details.
3420
3421 @node Comparison between GNAT and C/C++ Compilation Models
3422 @section Comparison between GNAT and C/C++ Compilation Models
3423
3424 @noindent
3425 The GNAT model of compilation is close to the C and C++ models. You can
3426 think of Ada specs as corresponding to header files in C. As in C, you
3427 don't need to compile specs; they are compiled when they are used. The
3428 Ada @code{with} is similar in effect to the @code{#include} of a C
3429 header.
3430
3431 One notable difference is that, in Ada, you may compile specs separately
3432 to check them for semantic and syntactic accuracy. This is not always
3433 possible with C headers because they are fragments of programs that have
3434 less specific syntactic or semantic rules.
3435
3436 The other major difference is the requirement for running the binder,
3437 which performs two important functions. First, it checks for
3438 consistency. In C or C++, the only defense against assembling
3439 inconsistent programs lies outside the compiler, in a makefile, for
3440 example. The binder satisfies the Ada requirement that it be impossible
3441 to construct an inconsistent program when the compiler is used in normal
3442 mode.
3443
3444 @cindex Elaboration order control
3445 The other important function of the binder is to deal with elaboration
3446 issues. There are also elaboration issues in C++ that are handled
3447 automatically. This automatic handling has the advantage of being
3448 simpler to use, but the C++ programmer has no control over elaboration.
3449 Where @code{gnatbind} might complain there was no valid order of
3450 elaboration, a C++ compiler would simply construct a program that
3451 malfunctioned at run time.
3452 @end ifclear
3453
3454 @node Comparison between GNAT and Conventional Ada Library Models
3455 @section Comparison between GNAT and Conventional Ada Library Models
3456
3457 @noindent
3458 This section is intended for Ada programmers who have
3459 used an Ada compiler implementing the traditional Ada library
3460 model, as described in the Ada 95 Language Reference Manual.
3461
3462 @cindex GNAT library
3463 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3464 source files themselves acts as the library. Compiling Ada programs does
3465 not generate any centralized information, but rather an object file and
3466 a ALI file, which are of interest only to the binder and linker.
3467 In a traditional system, the compiler reads information not only from
3468 the source file being compiled, but also from the centralized library.
3469 This means that the effect of a compilation depends on what has been
3470 previously compiled. In particular:
3471
3472 @itemize @bullet
3473 @item
3474 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3475 to the version of the unit most recently compiled into the library.
3476
3477 @item
3478 Inlining is effective only if the necessary body has already been
3479 compiled into the library.
3480
3481 @item
3482 Compiling a unit may obsolete other units in the library.
3483 @end itemize
3484
3485 @noindent
3486 In GNAT, compiling one unit never affects the compilation of any other
3487 units because the compiler reads only source files. Only changes to source
3488 files can affect the results of a compilation. In particular:
3489
3490 @itemize @bullet
3491 @item
3492 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3493 to the source version of the unit that is currently accessible to the
3494 compiler.
3495
3496 @item
3497 @cindex Inlining
3498 Inlining requires the appropriate source files for the package or
3499 subprogram bodies to be available to the compiler. Inlining is always
3500 effective, independent of the order in which units are complied.
3501
3502 @item
3503 Compiling a unit never affects any other compilations. The editing of
3504 sources may cause previous compilations to be out of date if they
3505 depended on the source file being modified.
3506 @end itemize
3507
3508 @noindent
3509 The most important result of these differences is that order of compilation
3510 is never significant in GNAT. There is no situation in which one is
3511 required to do one compilation before another. What shows up as order of
3512 compilation requirements in the traditional Ada library becomes, in
3513 GNAT, simple source dependencies; in other words, there is only a set
3514 of rules saying what source files must be present when a file is
3515 compiled.
3516
3517 @ifset vms
3518 @node Placement of temporary files
3519 @section Placement of temporary files
3520 @cindex Temporary files (user control over placement)
3521
3522 @noindent
3523 GNAT creates temporary files in the directory designated by the environment
3524 variable @env{TMPDIR}.
3525 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3526 for detailed information on how environment variables are resolved.
3527 For most users the easiest way to make use of this feature is to simply
3528 define @env{TMPDIR} as a job level logical name).
3529 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3530 for compiler temporary files, then you can include something like the
3531 following command in your @file{LOGIN.COM} file:
3532
3533 @smallexample
3534 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3535 @end smallexample
3536
3537 @noindent
3538 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3539 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3540 designated by @env{TEMP}.
3541 If none of these environment variables are defined then GNAT uses the
3542 directory designated by the logical name @code{SYS$SCRATCH:}
3543 (by default the user's home directory). If all else fails
3544 GNAT uses the current directory for temporary files.
3545 @end ifset
3546
3547 @c *************************
3548 @node Compiling Using gcc
3549 @chapter Compiling Using @command{gcc}
3550
3551 @noindent
3552 This chapter discusses how to compile Ada programs using the @command{gcc}
3553 command. It also describes the set of switches
3554 that can be used to control the behavior of the compiler.
3555 @menu
3556 * Compiling Programs::
3557 * Switches for gcc::
3558 * Search Paths and the Run-Time Library (RTL)::
3559 * Order of Compilation Issues::
3560 * Examples::
3561 @end menu
3562
3563 @node Compiling Programs
3564 @section Compiling Programs
3565
3566 @noindent
3567 The first step in creating an executable program is to compile the units
3568 of the program using the @command{gcc} command. You must compile the
3569 following files:
3570
3571 @itemize @bullet
3572 @item
3573 the body file (@file{.adb}) for a library level subprogram or generic
3574 subprogram
3575
3576 @item
3577 the spec file (@file{.ads}) for a library level package or generic
3578 package that has no body
3579
3580 @item
3581 the body file (@file{.adb}) for a library level package
3582 or generic package that has a body
3583
3584 @end itemize
3585
3586 @noindent
3587 You need @emph{not} compile the following files
3588
3589 @itemize @bullet
3590
3591 @item
3592 the spec of a library unit which has a body
3593
3594 @item
3595 subunits
3596 @end itemize
3597
3598 @noindent
3599 because they are compiled as part of compiling related units. GNAT
3600 package specs
3601 when the corresponding body is compiled, and subunits when the parent is
3602 compiled.
3603
3604 @cindex cannot generate code
3605 If you attempt to compile any of these files, you will get one of the
3606 following error messages (where fff is the name of the file you compiled):
3607
3608 @smallexample
3609 cannot generate code for file @var{fff} (package spec)
3610 to check package spec, use -gnatc
3611
3612 cannot generate code for file @var{fff} (missing subunits)
3613 to check parent unit, use -gnatc
3614
3615 cannot generate code for file @var{fff} (subprogram spec)
3616 to check subprogram spec, use -gnatc
3617
3618 cannot generate code for file @var{fff} (subunit)
3619 to check subunit, use -gnatc
3620 @end smallexample
3621
3622 @noindent
3623 As indicated by the above error messages, if you want to submit
3624 one of these files to the compiler to check for correct semantics
3625 without generating code, then use the @option{-gnatc} switch.
3626
3627 The basic command for compiling a file containing an Ada unit is
3628
3629 @smallexample
3630 $ gcc -c [@var{switches}] @file{file name}
3631 @end smallexample
3632
3633 @noindent
3634 where @var{file name} is the name of the Ada file (usually
3635 having an extension
3636 @file{.ads} for a spec or @file{.adb} for a body).
3637 @ifclear vms
3638 You specify the
3639 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3640 @end ifclear
3641 The result of a successful compilation is an object file, which has the
3642 same name as the source file but an extension of @file{.o} and an Ada
3643 Library Information (ALI) file, which also has the same name as the
3644 source file, but with @file{.ali} as the extension. GNAT creates these
3645 two output files in the current directory, but you may specify a source
3646 file in any directory using an absolute or relative path specification
3647 containing the directory information.
3648
3649 @findex gnat1
3650 @command{gcc} is actually a driver program that looks at the extensions of
3651 the file arguments and loads the appropriate compiler. For example, the
3652 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3653 These programs are in directories known to the driver program (in some
3654 configurations via environment variables you set), but need not be in
3655 your path. The @command{gcc} driver also calls the assembler and any other
3656 utilities needed to complete the generation of the required object
3657 files.
3658
3659 It is possible to supply several file names on the same @command{gcc}
3660 command. This causes @command{gcc} to call the appropriate compiler for
3661 each file. For example, the following command lists three separate
3662 files to be compiled:
3663
3664 @smallexample
3665 $ gcc -c x.adb y.adb z.c
3666 @end smallexample
3667
3668 @noindent
3669 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3670 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3671 The compiler generates three object files @file{x.o}, @file{y.o} and
3672 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3673 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3674 @ifclear vms
3675 except for
3676 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3677 @end ifclear
3678
3679 @node Switches for gcc
3680 @section Switches for @command{gcc}
3681
3682 @noindent
3683 The @command{gcc} command accepts switches that control the
3684 compilation process. These switches are fully described in this section.
3685 First we briefly list all the switches, in alphabetical order, then we
3686 describe the switches in more detail in functionally grouped sections.
3687
3688 More switches exist for GCC than those documented here, especially
3689 for specific targets. However, their use is not recommended as
3690 they may change code generation in ways that are incompatible with
3691 the Ada run-time library, or can cause inconsistencies between
3692 compilation units.
3693
3694 @menu
3695 * Output and Error Message Control::
3696 * Warning Message Control::
3697 * Debugging and Assertion Control::
3698 * Validity Checking::
3699 * Style Checking::
3700 * Run-Time Checks::
3701 * Using gcc for Syntax Checking::
3702 * Using gcc for Semantic Checking::
3703 * Compiling Different Versions of Ada::
3704 * Character Set Control::
3705 * File Naming Control::
3706 * Subprogram Inlining Control::
3707 * Auxiliary Output Control::
3708 * Debugging Control::
3709 * Exception Handling Control::
3710 * Units to Sources Mapping Files::
3711 * Integrated Preprocessing::
3712 * Code Generation Control::
3713 @ifset vms
3714 * Return Codes::
3715 @end ifset
3716 @end menu
3717
3718 @table @option
3719 @c !sort!
3720 @ifclear vms
3721 @cindex @option{-b} (@command{gcc})
3722 @item -b @var{target}
3723 Compile your program to run on @var{target}, which is the name of a
3724 system configuration. You must have a GNAT cross-compiler built if
3725 @var{target} is not the same as your host system.
3726
3727 @item -B@var{dir}
3728 @cindex @option{-B} (@command{gcc})
3729 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3730 from @var{dir} instead of the default location. Only use this switch
3731 when multiple versions of the GNAT compiler are available. See the
3732 @command{gcc} manual page for further details. You would normally use the
3733 @option{-b} or @option{-V} switch instead.
3734
3735 @item -c
3736 @cindex @option{-c} (@command{gcc})
3737 Compile. Always use this switch when compiling Ada programs.
3738
3739 Note: for some other languages when using @command{gcc}, notably in
3740 the case of C and C++, it is possible to use
3741 use @command{gcc} without a @option{-c} switch to
3742 compile and link in one step. In the case of GNAT, you
3743 cannot use this approach, because the binder must be run
3744 and @command{gcc} cannot be used to run the GNAT binder.
3745 @end ifclear
3746
3747 @item -fno-inline
3748 @cindex @option{-fno-inline} (@command{gcc})
3749 Suppresses all back-end inlining, even if other optimization or inlining
3750 switches are set.
3751 This includes suppression of inlining that results
3752 from the use of the pragma @code{Inline_Always}.
3753 See also @option{-gnatn} and @option{-gnatN}.
3754
3755 @item -fno-strict-aliasing
3756 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3757 Causes the compiler to avoid assumptions regarding non-aliasing
3758 of objects of different types. See
3759 @ref{Optimization and Strict Aliasing} for details.
3760
3761 @item -fstack-check
3762 @cindex @option{-fstack-check} (@command{gcc})
3763 Activates stack checking.
3764 See @ref{Stack Overflow Checking} for details.
3765
3766 @item -fstack-usage
3767 @cindex @option{-fstack-usage} (@command{gcc})
3768 Makes the compiler output stack usage information for the program, on a
3769 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3770
3771 @item -fcallgraph-info[=su]
3772 @cindex @option{-fcallgraph-info} (@command{gcc})
3773 Makes the compiler output callgraph information for the program, on a
3774 per-file basis.  The information is generated in the VCG format.  It can
3775 be decorated with stack-usage per-node information.
3776
3777 @item ^-g^/DEBUG^
3778 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3779 Generate debugging information. This information is stored in the object
3780 file and copied from there to the final executable file by the linker,
3781 where it can be read by the debugger. You must use the
3782 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3783
3784 @item -gnat83
3785 @cindex @option{-gnat83} (@command{gcc})
3786 Enforce Ada 83 restrictions.
3787
3788 @item -gnat95
3789 @cindex @option{-gnat95} (@command{gcc})
3790 Enforce Ada 95 restrictions.
3791
3792 @item -gnat05
3793 @cindex @option{-gnat05} (@command{gcc})
3794 Allow full Ada 2005 features.
3795
3796 @item -gnata
3797 @cindex @option{-gnata} (@command{gcc})
3798 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3799 activated. Note that these pragmas can also be controlled using the
3800 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3801
3802 @item -gnatA
3803 @cindex @option{-gnatA} (@command{gcc})
3804 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3805 it will be ignored.
3806
3807 @item -gnatb
3808 @cindex @option{-gnatb} (@command{gcc})
3809 Generate brief messages to @file{stderr} even if verbose mode set.
3810
3811 @item -gnatc
3812 @cindex @option{-gnatc} (@command{gcc})
3813 Check syntax and semantics only (no code generation attempted).
3814
3815 @item -gnatd
3816 @cindex @option{-gnatd} (@command{gcc})
3817 Specify debug options for the compiler. The string of characters after
3818 the @option{-gnatd} specify the specific debug options. The possible
3819 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3820 compiler source file @file{debug.adb} for details of the implemented
3821 debug options. Certain debug options are relevant to applications
3822 programmers, and these are documented at appropriate points in this
3823 users guide.
3824
3825 @item -gnatD
3826 @cindex @option{-gnatD} (@command{gcc})
3827 Create expanded source files for source level debugging. This switch
3828 also suppress generation of cross-reference information
3829 (see @option{-gnatx}).
3830
3831 @item -gnatec=@var{path}
3832 @cindex @option{-gnatec} (@command{gcc})
3833 Specify a configuration pragma file
3834 @ifclear vms
3835 (the equal sign is optional)
3836 @end ifclear
3837 (@pxref{The Configuration Pragmas Files}).
3838
3839 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3840 @cindex @option{-gnateD} (@command{gcc})
3841 Defines a symbol, associated with value, for preprocessing.
3842 (@pxref{Integrated Preprocessing}).
3843
3844 @item -gnatef
3845 @cindex @option{-gnatef} (@command{gcc})
3846 Display full source path name in brief error messages.
3847
3848 @item -gnatem=@var{path}
3849 @cindex @option{-gnatem} (@command{gcc})
3850 Specify a mapping file
3851 @ifclear vms
3852 (the equal sign is optional)
3853 @end ifclear
3854 (@pxref{Units to Sources Mapping Files}).
3855
3856 @item -gnatep=@var{file}
3857 @cindex @option{-gnatep} (@command{gcc})
3858 Specify a preprocessing data file
3859 @ifclear vms
3860 (the equal sign is optional)
3861 @end ifclear
3862 (@pxref{Integrated Preprocessing}).
3863
3864 @item -gnatE
3865 @cindex @option{-gnatE} (@command{gcc})
3866 Full dynamic elaboration checks.
3867
3868 @item -gnatf
3869 @cindex @option{-gnatf} (@command{gcc})
3870 Full errors. Multiple errors per line, all undefined references, do not
3871 attempt to suppress cascaded errors.
3872
3873 @item -gnatF
3874 @cindex @option{-gnatF} (@command{gcc})
3875 Externals names are folded to all uppercase.
3876
3877 @item -gnatg
3878 @cindex @option{-gnatg} (@command{gcc})
3879 Internal GNAT implementation mode. This should not be used for
3880 applications programs, it is intended only for use by the compiler
3881 and its run-time library. For documentation, see the GNAT sources.
3882 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3883 are generated on unreferenced entities, and all warnings are treated
3884 as errors.
3885
3886 @item -gnatG
3887 @cindex @option{-gnatG} (@command{gcc})
3888 List generated expanded code in source form.
3889
3890 @item ^-gnath^/HELP^
3891 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3892 Output usage information. The output is written to @file{stdout}.
3893
3894 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3895 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3896 Identifier character set
3897 @ifclear vms
3898 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3899 @end ifclear
3900 @ifset vms
3901 For details of the possible selections for @var{c},
3902 see @ref{Character Set Control}.
3903 @end ifset
3904
3905 @item -gnatjnn
3906 @cindex @option{-gnatjnn} (@command{gcc})
3907 Reformat error messages to fit on nn character lines
3908
3909 @item -gnatk=@var{n}
3910 @cindex @option{-gnatk} (@command{gcc})
3911 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3912
3913 @item -gnatl
3914 @cindex @option{-gnatl} (@command{gcc})
3915 Output full source listing with embedded error messages.
3916
3917 @item -gnatL
3918 @cindex @option{-gnatL} (@command{gcc})
3919 Used in conjunction with -gnatG or -gnatD to intersperse original
3920 source lines (as comment lines with line numbers) in the expanded
3921 source output.
3922
3923 @item -gnatm=@var{n}
3924 @cindex @option{-gnatm} (@command{gcc})
3925 Limit number of detected error or warning messages to @var{n}
3926 where @var{n} is in the range 1..999_999. The default setting if
3927 no switch is given is 9999. Compilation is terminated if this
3928 limit is exceeded. The equal sign here is optional.
3929
3930 @item -gnatn
3931 @cindex @option{-gnatn} (@command{gcc})
3932 Activate inlining for subprograms for which
3933 pragma @code{inline} is specified. This inlining is performed
3934 by the GCC back-end.
3935
3936 @item -gnatN
3937 @cindex @option{-gnatN} (@command{gcc})
3938 Activate front end inlining for subprograms for which
3939 pragma @code{Inline} is specified. This inlining is performed
3940 by the front end and will be visible in the
3941 @option{-gnatG} output.
3942 In some cases, this has proved more effective than the back end
3943 inlining resulting from the use of
3944 @option{-gnatn}.
3945 Note that
3946 @option{-gnatN} automatically implies
3947 @option{-gnatn} so it is not necessary
3948 to specify both options. There are a few cases that the back-end inlining
3949 catches that cannot be dealt with in the front-end.
3950
3951 @item -gnato
3952 @cindex @option{-gnato} (@command{gcc})
3953 Enable numeric overflow checking (which is not normally enabled by
3954 default). Not that division by zero is a separate check that is not
3955 controlled by this switch (division by zero checking is on by default).
3956
3957 @item -gnatp
3958 @cindex @option{-gnatp} (@command{gcc})
3959 Suppress all checks.
3960
3961 @item -gnatP
3962 @cindex @option{-gnatP} (@command{gcc})
3963 Enable polling. This is required on some systems (notably Windows NT) to
3964 obtain asynchronous abort and asynchronous transfer of control capability.
3965 See the description of pragma Polling in the GNAT Reference Manual for
3966 full details.
3967
3968 @item -gnatq
3969 @cindex @option{-gnatq} (@command{gcc})
3970 Don't quit; try semantics, even if parse errors.
3971
3972 @item -gnatQ
3973 @cindex @option{-gnatQ} (@command{gcc})
3974 Don't quit; generate @file{ALI} and tree files even if illegalities.
3975
3976 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3977 @cindex @option{-gnatR} (@command{gcc})
3978 Output representation information for declared types and objects.
3979
3980 @item -gnats
3981 @cindex @option{-gnats} (@command{gcc})
3982 Syntax check only.
3983
3984 @item -gnatS
3985 @cindex @option{-gnatS} (@command{gcc})
3986 Print package Standard.
3987
3988 @item -gnatt
3989 @cindex @option{-gnatt} (@command{gcc})
3990 Generate tree output file.
3991
3992 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3993 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3994 All compiler tables start at @var{nnn} times usual starting size.
3995
3996 @item -gnatu
3997 @cindex @option{-gnatu} (@command{gcc})
3998 List units for this compilation.
3999
4000 @item -gnatU
4001 @cindex @option{-gnatU} (@command{gcc})
4002 Tag all error messages with the unique string ``error:''
4003
4004 @item -gnatv
4005 @cindex @option{-gnatv} (@command{gcc})
4006 Verbose mode. Full error output with source lines to @file{stdout}.
4007
4008 @item -gnatV
4009 @cindex @option{-gnatV} (@command{gcc})
4010 Control level of validity checking. See separate section describing
4011 this feature.
4012
4013 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
4014 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4015 Warning mode where
4016 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4017 the exact warnings that
4018 are enabled or disabled (@pxref{Warning Message Control}).
4019
4020 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4021 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4022 Wide character encoding method
4023 @ifclear vms
4024 (@var{e}=n/h/u/s/e/8).
4025 @end ifclear
4026 @ifset vms
4027 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4028 @end ifset
4029
4030 @item -gnatx
4031 @cindex @option{-gnatx} (@command{gcc})
4032 Suppress generation of cross-reference information.
4033
4034 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
4035 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4036 Enable built-in style checks (@pxref{Style Checking}).
4037
4038 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4039 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4040 Distribution stub generation and compilation
4041 @ifclear vms
4042 (@var{m}=r/c for receiver/caller stubs).
4043 @end ifclear
4044 @ifset vms
4045 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4046 to be generated and compiled).
4047 @end ifset
4048
4049 @item ^-I^/SEARCH=^@var{dir}
4050 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4051 @cindex RTL
4052 Direct GNAT to search the @var{dir} directory for source files needed by
4053 the current compilation
4054 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4055
4056 @item ^-I-^/NOCURRENT_DIRECTORY^
4057 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4058 @cindex RTL
4059 Except for the source file named in the command line, do not look for source
4060 files in the directory containing the source file named in the command line
4061 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4062
4063 @ifclear vms
4064 @item -mbig-switch
4065 @cindex @option{-mbig-switch} (@command{gcc})
4066 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4067 This standard gcc switch causes the compiler to use larger offsets in its
4068 jump table representation for @code{case} statements.
4069 This may result in less efficient code, but is sometimes necessary
4070 (for example on HP-UX targets)
4071 @cindex HP-UX and @option{-mbig-switch} option
4072 in order to compile large and/or nested @code{case} statements.
4073
4074 @item -o @var{file}
4075 @cindex @option{-o} (@command{gcc})
4076 This switch is used in @command{gcc} to redirect the generated object file
4077 and its associated ALI file. Beware of this switch with GNAT, because it may
4078 cause the object file and ALI file to have different names which in turn
4079 may confuse the binder and the linker.
4080 @end ifclear
4081
4082 @item -nostdinc
4083 @cindex @option{-nostdinc} (@command{gcc})
4084 Inhibit the search of the default location for the GNAT Run Time
4085 Library (RTL) source files.
4086
4087 @item -nostdlib
4088 @cindex @option{-nostdlib} (@command{gcc})
4089 Inhibit the search of the default location for the GNAT Run Time
4090 Library (RTL) ALI files.
4091
4092 @ifclear vms
4093 @item -O[@var{n}]
4094 @cindex @option{-O} (@command{gcc})
4095 @var{n} controls the optimization level.
4096
4097 @table @asis
4098 @item n = 0
4099 No optimization, the default setting if no @option{-O} appears
4100
4101 @item n = 1
4102 Normal optimization, the default if you specify @option{-O} without
4103 an operand. A good compromise between code quality and compilation
4104 time.
4105
4106 @item n = 2
4107 Extensive optimization, may improve execution time, possibly at the cost of
4108 substantially increased compilation time.
4109
4110 @end table
4111 @end ifclear
4112
4113 @ifset vms
4114 @item  /NOOPTIMIZE
4115 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4116 Equivalent to @option{/OPTIMIZE=NONE}.
4117 This is the default behavior in the absence of an @option{/OPTMIZE}
4118 qualifier.
4119
4120 @item /OPTIMIZE[=(keyword[,...])]
4121 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4122 Selects the level of optimization for your program. The supported
4123 keywords are as follows:
4124 @table @code
4125 @item   ALL
4126 Perform most optimizations, including those that
4127 are expensive.
4128 This is the default if the @option{/OPTMIZE} qualifier is supplied
4129 without keyword options.
4130
4131 @item   NONE
4132 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4133
4134 @item SOME
4135 Perform some optimizations, but omit ones that are costly.
4136
4137 @item   DEVELOPMENT
4138 Same as @code{SOME}.
4139
4140 @item   UNROLL_LOOPS
4141 Try to unroll loops. This keyword may be specified together with
4142 any keyword above other than @code{NONE}. Loop unrolling
4143 usually, but not always, improves the performance of programs.
4144 @end table
4145 @end ifset
4146
4147 @ifclear vms
4148 @item -pass-exit-codes
4149 @cindex @option{-pass-exit-codes} (@command{gcc})
4150 Catch exit codes from the compiler and use the most meaningful as
4151 exit status.
4152 @end ifclear
4153
4154 @item --RTS=@var{rts-path}
4155 @cindex @option{--RTS} (@command{gcc})
4156 Specifies the default location of the runtime library. Same meaning as the
4157 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4158
4159 @item ^-S^/ASM^
4160 @cindex @option{^-S^/ASM^} (@command{gcc})
4161 ^Used in place of @option{-c} to^Used to^
4162 cause the assembler source file to be
4163 generated, using @file{^.s^.S^} as the extension,
4164 instead of the object file.
4165 This may be useful if you need to examine the generated assembly code.
4166
4167 @item ^-fverbose-asm^/VERBOSE_ASM^
4168 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4169 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4170 to cause the generated assembly code file to be annotated with variable
4171 names, making it significantly easier to follow.
4172
4173 @item ^-v^/VERBOSE^
4174 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4175 Show commands generated by the @command{gcc} driver. Normally used only for
4176 debugging purposes or if you need to be sure what version of the
4177 compiler you are executing.
4178
4179 @ifclear vms
4180 @item -V @var{ver}
4181 @cindex @option{-V} (@command{gcc})
4182 Execute @var{ver} version of the compiler. This is the @command{gcc}
4183 version, not the GNAT version.
4184 @end ifclear
4185
4186 @item ^-w^NO_BACK_END_WARNINGS^
4187 @cindex @option{-w} (@command{gcc})
4188 Turn off warnings generated by the back end of the compiler. Use of
4189 this switch also causes the default for front end warnings to be set
4190 to suppress (as though @option{-gnatws} had appeared at the start of
4191 the options.
4192
4193 @end table
4194
4195 @ifclear vms
4196 @c Combining qualifiers does not work on VMS
4197 You may combine a sequence of GNAT switches into a single switch. For
4198 example, the combined switch
4199
4200 @cindex Combining GNAT switches
4201 @smallexample
4202 -gnatofi3
4203 @end smallexample
4204
4205 @noindent
4206 is equivalent to specifying the following sequence of switches:
4207
4208 @smallexample
4209 -gnato -gnatf -gnati3
4210 @end smallexample
4211 @end ifclear
4212
4213 @noindent
4214 The following restrictions apply to the combination of switches
4215 in this manner:
4216
4217 @itemize @bullet
4218 @item
4219 The switch @option{-gnatc} if combined with other switches must come
4220 first in the string.
4221
4222 @item
4223 The switch @option{-gnats} if combined with other switches must come
4224 first in the string.
4225
4226 @item
4227 The switches
4228 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4229 may not be combined with any other switches.
4230
4231 @ifclear vms
4232 @item
4233 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4234 switch), then all further characters in the switch are interpreted
4235 as style modifiers (see description of @option{-gnaty}).
4236
4237 @item
4238 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4239 switch), then all further characters in the switch are interpreted
4240 as debug flags (see description of @option{-gnatd}).
4241
4242 @item
4243 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4244 switch), then all further characters in the switch are interpreted
4245 as warning mode modifiers (see description of @option{-gnatw}).
4246
4247 @item
4248 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4249 switch), then all further characters in the switch are interpreted
4250 as validity checking options (see description of @option{-gnatV}).
4251 @end ifclear
4252 @end itemize
4253
4254 @node Output and Error Message Control
4255 @subsection Output and Error Message Control
4256 @findex stderr
4257
4258 @noindent
4259 The standard default format for error messages is called ``brief format''.
4260 Brief format messages are written to @file{stderr} (the standard error
4261 file) and have the following form:
4262
4263 @smallexample
4264 e.adb:3:04: Incorrect spelling of keyword "function"
4265 e.adb:4:20: ";" should be "is"
4266 @end smallexample
4267
4268 @noindent
4269 The first integer after the file name is the line number in the file,
4270 and the second integer is the column number within the line.
4271 @code{glide} can parse the error messages
4272 and point to the referenced character.
4273 The following switches provide control over the error message
4274 format:
4275
4276 @table @option
4277 @c !sort!
4278 @item -gnatv
4279 @cindex @option{-gnatv} (@command{gcc})
4280 @findex stdout
4281 @ifclear vms
4282 The v stands for verbose.
4283 @end ifclear
4284 The effect of this setting is to write long-format error
4285 messages to @file{stdout} (the standard output file.
4286 The same program compiled with the
4287 @option{-gnatv} switch would generate:
4288
4289 @smallexample
4290 @cartouche
4291 3. funcion X (Q : Integer)
4292    |
4293 >>> Incorrect spelling of keyword "function"
4294 4. return Integer;
4295                  |
4296 >>> ";" should be "is"
4297 @end cartouche
4298 @end smallexample
4299
4300 @noindent
4301 The vertical bar indicates the location of the error, and the @samp{>>>}
4302 prefix can be used to search for error messages. When this switch is
4303 used the only source lines output are those with errors.
4304
4305 @item -gnatl
4306 @cindex @option{-gnatl} (@command{gcc})
4307 @ifclear vms
4308 The @code{l} stands for list.
4309 @end ifclear
4310 This switch causes a full listing of
4311 the file to be generated. In the case where a body is
4312 compiled, the corresponding spec is also listed, along
4313 with any subunits. Typical output from compiling a package
4314 body @file{p.adb} might look like:
4315
4316 @smallexample @c ada
4317 @cartouche
4318  Compiling: p.adb
4319
4320      1. package body p is
4321      2.    procedure a;
4322      3.    procedure a is separate;
4323      4. begin
4324      5.    null
4325                |
4326         >>> missing ";"
4327
4328      6. end;
4329
4330 Compiling: p.ads
4331
4332      1. package p is
4333      2.    pragma Elaborate_Body
4334                                 |
4335         >>> missing ";"
4336
4337      3. end p;
4338
4339 Compiling: p-a.adb
4340
4341      1. separate p
4342                 |
4343         >>> missing "("
4344
4345      2. procedure a is
4346      3. begin
4347      4.    null
4348                |
4349         >>> missing ";"
4350
4351      5. end;
4352 @end cartouche
4353 @end smallexample
4354
4355 @noindent
4356 @findex stderr
4357 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4358 standard output is redirected, a brief summary is written to
4359 @file{stderr} (standard error) giving the number of error messages and
4360 warning messages generated.
4361
4362 @item -^gnatl^OUTPUT_FILE^=file
4363 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4364 This has the same effect as @code{-gnatl} except that the output is
4365 written to a file instead of to standard output. If the given name
4366 @file{fname} does not start with a period, then it is the full name
4367 of the file to be written. If @file{fname} is an extension, it is
4368 appended to the name of the file being compiled. For example, if
4369 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4370 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4371
4372 @item -gnatU
4373 @cindex @option{-gnatU} (@command{gcc})
4374 This switch forces all error messages to be preceded by the unique
4375 string ``error:''. This means that error messages take a few more
4376 characters in space, but allows easy searching for and identification
4377 of error messages.
4378
4379 @item -gnatb
4380 @cindex @option{-gnatb} (@command{gcc})
4381 @ifclear vms
4382 The @code{b} stands for brief.
4383 @end ifclear
4384 This switch causes GNAT to generate the
4385 brief format error messages to @file{stderr} (the standard error
4386 file) as well as the verbose
4387 format message or full listing (which as usual is written to
4388 @file{stdout} (the standard output file).
4389
4390 @item -gnatm=@var{n}
4391 @cindex @option{-gnatm} (@command{gcc})
4392 @ifclear vms
4393 The @code{m} stands for maximum.
4394 @end ifclear
4395 @var{n} is a decimal integer in the
4396 range of 1 to 999 and limits the number of error messages to be
4397 generated. For example, using @option{-gnatm2} might yield
4398
4399 @smallexample
4400 e.adb:3:04: Incorrect spelling of keyword "function"
4401 e.adb:5:35: missing ".."
4402 fatal error: maximum errors reached
4403 compilation abandoned
4404 @end smallexample
4405
4406 @noindent
4407 Note that the equal sign is optional, so the switches
4408 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4409
4410 @item -gnatf
4411 @cindex @option{-gnatf} (@command{gcc})
4412 @cindex Error messages, suppressing
4413 @ifclear vms
4414 The @code{f} stands for full.
4415 @end ifclear
4416 Normally, the compiler suppresses error messages that are likely to be
4417 redundant. This switch causes all error
4418 messages to be generated. In particular, in the case of
4419 references to undefined variables. If a given variable is referenced
4420 several times, the normal format of messages is
4421 @smallexample
4422 e.adb:7:07: "V" is undefined (more references follow)
4423 @end smallexample
4424
4425 @noindent
4426 where the parenthetical comment warns that there are additional
4427 references to the variable @code{V}. Compiling the same program with the
4428 @option{-gnatf} switch yields
4429
4430 @smallexample
4431 e.adb:7:07: "V" is undefined
4432 e.adb:8:07: "V" is undefined
4433 e.adb:8:12: "V" is undefined
4434 e.adb:8:16: "V" is undefined
4435 e.adb:9:07: "V" is undefined
4436 e.adb:9:12: "V" is undefined
4437 @end smallexample
4438
4439 @noindent
4440 The @option{-gnatf} switch also generates additional information for
4441 some error messages.  Some examples are:
4442
4443 @itemize @bullet
4444 @item
4445 Full details on entities not available in high integrity mode
4446 @item
4447 Details on possibly non-portable unchecked conversion
4448 @item
4449 List possible interpretations for ambiguous calls
4450 @item
4451 Additional details on incorrect parameters
4452 @end itemize
4453
4454 @item -gnatjnn
4455 @cindex @option{-gnatjnn} (@command{gcc})
4456 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4457 with continuation lines are treated as though the continuation lines were
4458 separate messages (and so a warning with two continuation lines counts as
4459 three warnings, and is listed as three separate messages).
4460
4461 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4462 messages are output in a different manner. A message and all its continuation
4463 lines are treated as a unit, and count as only one warning or message in the
4464 statistics totals. Furthermore, the message is reformatted so that no line
4465 is longer than nn characters.
4466
4467 @item -gnatq
4468 @cindex @option{-gnatq} (@command{gcc})
4469 @ifclear vms
4470 The @code{q} stands for quit (really ``don't quit'').
4471 @end ifclear
4472 In normal operation mode, the compiler first parses the program and
4473 determines if there are any syntax errors. If there are, appropriate
4474 error messages are generated and compilation is immediately terminated.
4475 This switch tells
4476 GNAT to continue with semantic analysis even if syntax errors have been
4477 found. This may enable the detection of more errors in a single run. On
4478 the other hand, the semantic analyzer is more likely to encounter some
4479 internal fatal error when given a syntactically invalid tree.
4480
4481 @item -gnatQ
4482 @cindex @option{-gnatQ} (@command{gcc})
4483 In normal operation mode, the @file{ALI} file is not generated if any
4484 illegalities are detected in the program. The use of @option{-gnatQ} forces
4485 generation of the @file{ALI} file. This file is marked as being in
4486 error, so it cannot be used for binding purposes, but it does contain
4487 reasonably complete cross-reference information, and thus may be useful
4488 for use by tools (e.g. semantic browsing tools or integrated development
4489 environments) that are driven from the @file{ALI} file. This switch
4490 implies @option{-gnatq}, since the semantic phase must be run to get a
4491 meaningful ALI file.
4492
4493 In addition, if @option{-gnatt} is also specified, then the tree file is
4494 generated even if there are illegalities. It may be useful in this case
4495 to also specify @option{-gnatq} to ensure that full semantic processing
4496 occurs. The resulting tree file can be processed by ASIS, for the purpose
4497 of providing partial information about illegal units, but if the error
4498 causes the tree to be badly malformed, then ASIS may crash during the
4499 analysis.
4500
4501 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4502 being in error, @command{gnatmake} will attempt to recompile the source when it
4503 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4504
4505 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4506 since ALI files are never generated if @option{-gnats} is set.
4507
4508 @end table
4509
4510 @node Warning Message Control
4511 @subsection Warning Message Control
4512 @cindex Warning messages
4513 @noindent
4514 In addition to error messages, which correspond to illegalities as defined
4515 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4516 situations.
4517
4518 First, the compiler considers some constructs suspicious and generates a
4519 warning message to alert you to a possible error. Second, if the
4520 compiler detects a situation that is sure to raise an exception at
4521 run time, it generates a warning message. The following shows an example
4522 of warning messages:
4523 @smallexample
4524 e.adb:4:24: warning: creation of object may raise Storage_Error
4525 e.adb:10:17: warning: static value out of range
4526 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4527 @end smallexample
4528
4529 @noindent
4530 GNAT considers a large number of situations as appropriate
4531 for the generation of warning messages. As always, warnings are not
4532 definite indications of errors. For example, if you do an out-of-range
4533 assignment with the deliberate intention of raising a
4534 @code{Constraint_Error} exception, then the warning that may be
4535 issued does not indicate an error. Some of the situations for which GNAT
4536 issues warnings (at least some of the time) are given in the following
4537 list. This list is not complete, and new warnings are often added to
4538 subsequent versions of GNAT. The list is intended to give a general idea
4539 of the kinds of warnings that are generated.
4540
4541 @itemize @bullet
4542 @item
4543 Possible infinitely recursive calls
4544
4545 @item
4546 Out-of-range values being assigned
4547
4548 @item
4549 Possible order of elaboration problems
4550
4551 @item
4552 Unreachable code
4553
4554 @item
4555 Address clauses with possibly unaligned values, or where an attempt is
4556 made to overlay a smaller variable with a larger one.
4557
4558 @item
4559 Fixed-point type declarations with a null range
4560
4561 @item
4562 Direct_IO or Sequential_IO instantiated with a type that has access values
4563
4564 @item
4565 Variables that are never assigned a value
4566
4567 @item
4568 Variables that are referenced before being initialized
4569
4570 @item
4571 Task entries with no corresponding @code{accept} statement
4572
4573 @item
4574 Duplicate accepts for the same task entry in a @code{select}
4575
4576 @item
4577 Objects that take too much storage
4578
4579 @item
4580 Unchecked conversion between types of differing sizes
4581
4582 @item
4583 Missing @code{return} statement along some execution path in a function
4584
4585 @item
4586 Incorrect (unrecognized) pragmas
4587
4588 @item
4589 Incorrect external names
4590
4591 @item
4592 Allocation from empty storage pool
4593
4594 @item
4595 Potentially blocking operation in protected type
4596
4597 @item
4598 Suspicious parenthesization of expressions
4599
4600 @item
4601 Mismatching bounds in an aggregate
4602
4603 @item
4604 Attempt to return local value by reference
4605
4606 @item
4607 Premature instantiation of a generic body
4608
4609 @item
4610 Attempt to pack aliased components
4611
4612 @item
4613 Out of bounds array subscripts
4614
4615 @item
4616 Wrong length on string assignment
4617
4618 @item
4619 Violations of style rules if style checking is enabled
4620
4621 @item
4622 Unused @code{with} clauses
4623
4624 @item
4625 @code{Bit_Order} usage that does not have any effect
4626
4627 @item
4628 @code{Standard.Duration} used to resolve universal fixed expression
4629
4630 @item
4631 Dereference of possibly null value
4632
4633 @item
4634 Declaration that is likely to cause storage error
4635
4636 @item
4637 Internal GNAT unit @code{with}'ed by application unit
4638
4639 @item
4640 Values known to be out of range at compile time
4641
4642 @item
4643 Unreferenced labels and variables
4644
4645 @item
4646 Address overlays that could clobber memory
4647
4648 @item
4649 Unexpected initialization when address clause present
4650
4651 @item
4652 Bad alignment for address clause
4653
4654 @item
4655 Useless type conversions
4656
4657 @item
4658 Redundant assignment statements and other redundant constructs
4659
4660 @item
4661 Useless exception handlers
4662
4663 @item
4664 Accidental hiding of name by child unit
4665
4666 @item
4667 Access before elaboration detected at compile time
4668
4669 @item
4670 A range in a @code{for} loop that is known to be null or might be null
4671
4672 @end itemize
4673
4674 @noindent
4675 The following section lists compiler switches that are available
4676 to control the handling of warning messages. It is also possible
4677 to excercise much finer control over what warnings are issued and
4678 suppressed using the GNAT pragma Warnings, which is documented
4679 in the GNAT Reference manual.
4680
4681 @table @option
4682 @c !sort!
4683 @item -gnatwa
4684 @emph{Activate all optional errors.}
4685 @cindex @option{-gnatwa} (@command{gcc})
4686 This switch activates most optional warning messages, see remaining list
4687 in this section for details on optional warning messages that can be
4688 individually controlled.  The warnings that are not turned on by this
4689 switch are
4690 @option{-gnatwd} (implicit dereferencing),
4691 @option{-gnatwh} (hiding),
4692 @option{-gnatwl} (elaboration warnings),
4693 and @option{-gnatwt} (tracking of deleted conditional code).
4694 All other optional warnings are turned on.
4695
4696 @item -gnatwA
4697 @emph{Suppress all optional errors.}
4698 @cindex @option{-gnatwA} (@command{gcc})
4699 This switch suppresses all optional warning messages, see remaining list
4700 in this section for details on optional warning messages that can be
4701 individually controlled.
4702
4703 @item -gnatwb
4704 @emph{Activate warnings on bad fixed values.}
4705 @cindex @option{-gnatwb} (@command{gcc})
4706 @cindex Bad fixed values
4707 @cindex Fixed-point Small value
4708 @cindex Small value
4709 This switch activates warnings for static fixed-point expressions whose
4710 value is not an exact multiple of Small. Such values are implementation
4711 dependent, since an implementation is free to choose either of the multiples
4712 that surround the value. GNAT always chooses the closer one, but this is not
4713 required behavior, and it is better to specify a value that is an exact
4714 multiple, ensuring predictable execution. The default is that such warnings
4715 are not generated.
4716
4717 @item -gnatwB
4718 @emph{Suppress warnings on bad fixed values.}
4719 @cindex @option{-gnatwB} (@command{gcc})
4720 This switch suppresses warnings for static fixed-point expressions whose
4721 value is not an exact multiple of Small.
4722
4723 @item -gnatwc
4724 @emph{Activate warnings on conditionals.}
4725 @cindex @option{-gnatwc} (@command{gcc})
4726 @cindex Conditionals, constant
4727 This switch activates warnings for conditional expressions used in
4728 tests that are known to be True or False at compile time. The default
4729 is that such warnings are not generated.
4730 Note that this warning does
4731 not get issued for the use of boolean variables or constants whose
4732 values are known at compile time, since this is a standard technique
4733 for conditional compilation in Ada, and this would generate too many
4734 false positive warnings.
4735
4736 This warning option also activates a special test for comparisons using
4737 the operators ``>='' and`` <=''.
4738 If the compiler can tell that only the equality condition is possible,
4739 then it will warn that the ``>'' or ``<'' part of the test
4740 is useless and that the operator could be replaced by ``=''.
4741 An example would be comparing a @code{Natural} variable <= 0.
4742
4743 This warning can also be turned on using @option{-gnatwa}.
4744
4745 @item -gnatwC
4746 @emph{Suppress warnings on conditionals.}
4747 @cindex @option{-gnatwC} (@command{gcc})
4748 This switch suppresses warnings for conditional expressions used in
4749 tests that are known to be True or False at compile time.
4750
4751 @item -gnatwd
4752 @emph{Activate warnings on implicit dereferencing.}
4753 @cindex @option{-gnatwd} (@command{gcc})
4754 If this switch is set, then the use of a prefix of an access type
4755 in an indexed component, slice, or selected component without an
4756 explicit @code{.all} will generate a warning. With this warning
4757 enabled, access checks occur only at points where an explicit
4758 @code{.all} appears in the source code (assuming no warnings are
4759 generated as a result of this switch). The default is that such
4760 warnings are not generated.
4761 Note that @option{-gnatwa} does not affect the setting of
4762 this warning option.
4763
4764 @item -gnatwD
4765 @emph{Suppress warnings on implicit dereferencing.}
4766 @cindex @option{-gnatwD} (@command{gcc})
4767 @cindex Implicit dereferencing
4768 @cindex Dereferencing, implicit
4769 This switch suppresses warnings for implicit dereferences in
4770 indexed components, slices, and selected components.
4771
4772 @item -gnatwe
4773 @emph{Treat warnings as errors.}
4774 @cindex @option{-gnatwe} (@command{gcc})
4775 @cindex Warnings, treat as error
4776 This switch causes warning messages to be treated as errors.
4777 The warning string still appears, but the warning messages are counted
4778 as errors, and prevent the generation of an object file.
4779
4780 @item -gnatwf
4781 @emph{Activate warnings on unreferenced formals.}
4782 @cindex @option{-gnatwf} (@command{gcc})
4783 @cindex Formals, unreferenced
4784 This switch causes a warning to be generated if a formal parameter
4785 is not referenced in the body of the subprogram. This warning can
4786 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4787 default is that these warnings are not generated.
4788
4789 @item -gnatwF
4790 @emph{Suppress warnings on unreferenced formals.}
4791 @cindex @option{-gnatwF} (@command{gcc})
4792 This switch suppresses warnings for unreferenced formal
4793 parameters. Note that the
4794 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4795 effect of warning on unreferenced entities other than subprogram
4796 formals.
4797
4798 @item -gnatwg
4799 @emph{Activate warnings on unrecognized pragmas.}
4800 @cindex @option{-gnatwg} (@command{gcc})
4801 @cindex Pragmas, unrecognized
4802 This switch causes a warning to be generated if an unrecognized
4803 pragma is encountered. Apart from issuing this warning, the
4804 pragma is ignored and has no effect. This warning can
4805 also be turned on using @option{-gnatwa}. The default
4806 is that such warnings are issued (satisfying the Ada Reference
4807 Manual requirement that such warnings appear).
4808
4809 @item -gnatwG
4810 @emph{Suppress warnings on unrecognized pragmas.}
4811 @cindex @option{-gnatwG} (@command{gcc})
4812 This switch suppresses warnings for unrecognized pragmas.
4813
4814 @item -gnatwh
4815 @emph{Activate warnings on hiding.}
4816 @cindex @option{-gnatwh} (@command{gcc})
4817 @cindex Hiding of Declarations
4818 This switch activates warnings on hiding declarations.
4819 A declaration is considered hiding
4820 if it is for a non-overloadable entity, and it declares an entity with the
4821 same name as some other entity that is directly or use-visible. The default
4822 is that such warnings are not generated.
4823 Note that @option{-gnatwa} does not affect the setting of this warning option.
4824
4825 @item -gnatwH
4826 @emph{Suppress warnings on hiding.}
4827 @cindex @option{-gnatwH} (@command{gcc})
4828 This switch suppresses warnings on hiding declarations.
4829
4830 @item -gnatwi
4831 @emph{Activate warnings on implementation units.}
4832 @cindex @option{-gnatwi} (@command{gcc})
4833 This switch activates warnings for a @code{with} of an internal GNAT
4834 implementation unit, defined as any unit from the @code{Ada},
4835 @code{Interfaces}, @code{GNAT},
4836 ^^@code{DEC},^ or @code{System}
4837 hierarchies that is not
4838 documented in either the Ada Reference Manual or the GNAT
4839 Programmer's Reference Manual. Such units are intended only
4840 for internal implementation purposes and should not be @code{with}'ed
4841 by user programs. The default is that such warnings are generated
4842 This warning can also be turned on using @option{-gnatwa}.
4843
4844 @item -gnatwI
4845 @emph{Disable warnings on implementation units.}
4846 @cindex @option{-gnatwI} (@command{gcc})
4847 This switch disables warnings for a @code{with} of an internal GNAT
4848 implementation unit.
4849
4850 @item -gnatwj
4851 @emph{Activate warnings on obsolescent features (Annex J).}
4852 @cindex @option{-gnatwj} (@command{gcc})
4853 @cindex Features, obsolescent
4854 @cindex Obsolescent features
4855 If this warning option is activated, then warnings are generated for
4856 calls to subprograms marked with @code{pragma Obsolescent} and
4857 for use of features in Annex J of the Ada Reference Manual. In the
4858 case of Annex J, not all features are flagged. In particular use
4859 of the renamed packages (like @code{Text_IO}) and use of package
4860 @code{ASCII} are not flagged, since these are very common and
4861 would generate many annoying positive warnings. The default is that
4862 such warnings are not generated. This warning is also turned on by
4863 the use of @option{-gnatwa}.
4864
4865 In addition to the above cases, warnings are also generated for
4866 GNAT features that have been provided in past versions but which
4867 have been superseded (typically by features in the new Ada standard).
4868 For example, @code{pragma Ravenscar} will be flagged since its
4869 function is replaced by @code{pragma Profile(Ravenscar)}.
4870
4871 Note that this warning option functions differently from the
4872 restriction @code{No_Obsolescent_Features} in two respects.
4873 First, the restriction applies only to annex J features.
4874 Second, the restriction does flag uses of package @code{ASCII}.
4875
4876 @item -gnatwJ
4877 @emph{Suppress warnings on obsolescent features (Annex J).}
4878 @cindex @option{-gnatwJ} (@command{gcc})
4879 This switch disables warnings on use of obsolescent features.
4880
4881 @item -gnatwk
4882 @emph{Activate warnings on variables that could be constants.}
4883 @cindex @option{-gnatwk} (@command{gcc})
4884 This switch activates warnings for variables that are initialized but
4885 never modified, and then could be declared constants. The default is that
4886 such warnings are not given.
4887 This warning can also be turned on using @option{-gnatwa}.
4888
4889 @item -gnatwK
4890 @emph{Suppress warnings on variables that could be constants.}
4891 @cindex @option{-gnatwK} (@command{gcc})
4892 This switch disables warnings on variables that could be declared constants.
4893
4894 @item -gnatwl
4895 @emph{Activate warnings for missing elaboration pragmas.}
4896 @cindex @option{-gnatwl} (@command{gcc})
4897 @cindex Elaboration, warnings
4898 This switch activates warnings on missing
4899 @code{Elaborate_All} and @code{Elaborate} pragmas.
4900 See the section in this guide on elaboration checking for details on
4901 when such pragmas should be used. Warnings are also generated if you
4902 are using the static mode of elaboration, and a @code{pragma Elaborate}
4903 is encountered. The default is that such warnings
4904 are not generated.
4905 This warning is not automatically turned on by the use of @option{-gnatwa}.
4906
4907 @item -gnatwL
4908 @emph{Suppress warnings for missing elaboration pragmas.}
4909 @cindex @option{-gnatwL} (@command{gcc})
4910 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4911 See the section in this guide on elaboration checking for details on
4912 when such pragmas should be used.
4913
4914 @item -gnatwm
4915 @emph{Activate warnings on modified but unreferenced variables.}
4916 @cindex @option{-gnatwm} (@command{gcc})
4917 This switch activates warnings for variables that are assigned (using
4918 an initialization value or with one or more assignment statements) but
4919 whose value is never read. The warning is suppressed for volatile
4920 variables and also for variables that are renamings of other variables
4921 or for which an address clause is given.
4922 This warning can also be turned on using @option{-gnatwa}.
4923 The default is that these warnings are not given.
4924
4925 @item -gnatwM
4926 @emph{Disable warnings on modified but unreferenced variables.}
4927 @cindex @option{-gnatwM} (@command{gcc})
4928 This switch disables warnings for variables that are assigned or
4929 initialized, but never read.
4930
4931 @item -gnatwn
4932 @emph{Set normal warnings mode.}
4933 @cindex @option{-gnatwn} (@command{gcc})
4934 This switch sets normal warning mode, in which enabled warnings are
4935 issued and treated as warnings rather than errors. This is the default
4936 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4937 an explicit @option{-gnatws} or
4938 @option{-gnatwe}. It also cancels the effect of the
4939 implicit @option{-gnatwe} that is activated by the
4940 use of @option{-gnatg}.
4941
4942 @item -gnatwo
4943 @emph{Activate warnings on address clause overlays.}
4944 @cindex @option{-gnatwo} (@command{gcc})
4945 @cindex Address Clauses, warnings
4946 This switch activates warnings for possibly unintended initialization
4947 effects of defining address clauses that cause one variable to overlap
4948 another. The default is that such warnings are generated.
4949 This warning can also be turned on using @option{-gnatwa}.
4950
4951 @item -gnatwO
4952 @emph{Suppress warnings on address clause overlays.}
4953 @cindex @option{-gnatwO} (@command{gcc})
4954 This switch suppresses warnings on possibly unintended initialization
4955 effects of defining address clauses that cause one variable to overlap
4956 another.
4957
4958 @item -gnatwp
4959 @emph{Activate warnings on ineffective pragma Inlines.}
4960 @cindex @option{-gnatwp} (@command{gcc})
4961 @cindex Inlining, warnings
4962 This switch activates warnings for failure of front end inlining
4963 (activated by @option{-gnatN}) to inline a particular call. There are
4964 many reasons for not being able to inline a call, including most
4965 commonly that the call is too complex to inline. The default is
4966 that such warnings are not given.
4967 This warning can also be turned on using @option{-gnatwa}.
4968
4969 @item -gnatwP
4970 @emph{Suppress warnings on ineffective pragma Inlines.}
4971 @cindex @option{-gnatwP} (@command{gcc})
4972 This switch suppresses warnings on ineffective pragma Inlines. If the
4973 inlining mechanism cannot inline a call, it will simply ignore the
4974 request silently.
4975
4976 @item -gnatwq
4977 @emph{Activate warnings on questionable missing parentheses.}
4978 @cindex @option{-gnatwq} (@command{gcc})
4979 @cindex Parentheses, warnings
4980 This switch activates warnings for cases where parentheses are not used and
4981 the result is potential ambiguity from a readers point of view. For example
4982 (not a > b) when a and b are modular means (not (a) > b) and very likely the
4983 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
4984 quite likely ((-x) mod 5) was intended. In such situations it seems best to
4985 follow the rule of always parenthesizing to make the association clear, and
4986 this warning switch warns if such parentheses are not present. The default
4987 is that these warnings are not given.
4988 This warning can also be turned on using @option{-gnatwa}.
4989
4990 @item -gnatwQ
4991 @emph{Suppress warnings on questionable missing parentheses.}
4992 @cindex @option{-gnatwQ} (@command{gcc})
4993 This switch suppresses warnings for cases where the association is not
4994 clear and the use of parentheses is preferred.
4995
4996 @item -gnatwr
4997 @emph{Activate warnings on redundant constructs.}
4998 @cindex @option{-gnatwr} (@command{gcc})
4999 This switch activates warnings for redundant constructs. The following
5000 is the current list of constructs regarded as redundant:
5001
5002 @itemize @bullet
5003 @item
5004 Assignment of an item to itself.
5005 @item
5006 Type conversion that converts an expression to its own type.
5007 @item
5008 Use of the attribute @code{Base} where @code{typ'Base} is the same
5009 as @code{typ}.
5010 @item
5011 Use of pragma @code{Pack} when all components are placed by a record
5012 representation clause.
5013 @item
5014 Exception handler containing only a reraise statement (raise with no
5015 operand) which has no effect.
5016 @item
5017 Use of the operator abs on an operand that is known at compile time
5018 to be non-negative
5019 @item
5020 Comparison of boolean expressions to an explicit True value.
5021 @end itemize
5022
5023 This warning can also be turned on using @option{-gnatwa}.
5024 The default is that warnings for redundant constructs are not given.
5025
5026 @item -gnatwR
5027 @emph{Suppress warnings on redundant constructs.}
5028 @cindex @option{-gnatwR} (@command{gcc})
5029 This switch suppresses warnings for redundant constructs.
5030
5031 @item -gnatws
5032 @emph{Suppress all warnings.}
5033 @cindex @option{-gnatws} (@command{gcc})
5034 This switch completely suppresses the
5035 output of all warning messages from the GNAT front end.
5036 Note that it does not suppress warnings from the @command{gcc} back end.
5037 To suppress these back end warnings as well, use the switch @option{-w}
5038 in addition to @option{-gnatws}.
5039
5040 @item -gnatwt
5041 @emph{Activate warnings for tracking of deleted conditional code.}
5042 @cindex @option{-gnatwt} (@command{gcc})
5043 @cindex Deactivated code, warnings
5044 @cindex Deleted code, warnings
5045 This switch activates warnings for tracking of code in conditionals (IF and
5046 CASE statements) that is detected to be dead code which cannot be executed, and
5047 which is removed by the front end. This warning is off by default, and is not
5048 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5049 useful for detecting deactivated code in certified applications.
5050
5051 @item -gnatwT
5052 @emph{Suppress warnings for tracking of deleted conditional code.}
5053 @cindex @option{-gnatwT} (@command{gcc})
5054 This switch suppresses warnings for tracking of deleted conditional code.
5055
5056 @item -gnatwu
5057 @emph{Activate warnings on unused entities.}
5058 @cindex @option{-gnatwu} (@command{gcc})
5059 This switch activates warnings to be generated for entities that
5060 are declared but not referenced, and for units that are @code{with}'ed
5061 and not
5062 referenced. In the case of packages, a warning is also generated if
5063 no entities in the package are referenced. This means that if the package
5064 is referenced but the only references are in @code{use}
5065 clauses or @code{renames}
5066 declarations, a warning is still generated. A warning is also generated
5067 for a generic package that is @code{with}'ed but never instantiated.
5068 In the case where a package or subprogram body is compiled, and there
5069 is a @code{with} on the corresponding spec
5070 that is only referenced in the body,
5071 a warning is also generated, noting that the
5072 @code{with} can be moved to the body. The default is that
5073 such warnings are not generated.
5074 This switch also activates warnings on unreferenced formals
5075 (it includes the effect of @option{-gnatwf}).
5076 This warning can also be turned on using @option{-gnatwa}.
5077
5078 @item -gnatwU
5079 @emph{Suppress warnings on unused entities.}
5080 @cindex @option{-gnatwU} (@command{gcc})
5081 This switch suppresses warnings for unused entities and packages.
5082 It also turns off warnings on unreferenced formals (and thus includes
5083 the effect of @option{-gnatwF}).
5084
5085 @item -gnatwv
5086 @emph{Activate warnings on unassigned variables.}
5087 @cindex @option{-gnatwv} (@command{gcc})
5088 @cindex Unassigned variable warnings
5089 This switch activates warnings for access to variables which
5090 may not be properly initialized. The default is that
5091 such warnings are generated.
5092 This warning can also be turned on using @option{-gnatwa}.
5093
5094 @item -gnatwV
5095 @emph{Suppress warnings on unassigned variables.}
5096 @cindex @option{-gnatwV} (@command{gcc})
5097 This switch suppresses warnings for access to variables which
5098 may not be properly initialized.
5099
5100 @item -gnatww
5101 @emph{Activate warnings on wrong low bound assumption.}
5102 @cindex @option{-gnatww} (@command{gcc})
5103 @cindex String indexing warnings
5104 This switch activates warnings for indexing an unconstrained string parameter
5105 with a literal or S'Length. This is a case where the code is assuming that the
5106 low bound is one, which is in general not true (for example when a slice is
5107 passed). The default is that such warnings are generated.
5108 This warning can also be turned on using @option{-gnatwa}.
5109 F
5110
5111 @item -gnatwW
5112 @emph{Suppress warnings on wrong low bound assumption.}
5113 @cindex @option{-gnatwW} (@command{gcc})
5114 This switch activates warnings for indexing an unconstrained string parameter
5115 with a literal or S'Length. This warning can also be suppressed by providing
5116 an Assert pragma that checks the low bound, for example:
5117
5118 @smallexample @c ada
5119    procedure K (S : String) is
5120       pragma Assert (S'First = 1);
5121       ...
5122 @end smallexample
5123
5124 @item -gnatwx
5125 @emph{Activate warnings on Export/Import pragmas.}
5126 @cindex @option{-gnatwx} (@command{gcc})
5127 @cindex Export/Import pragma warnings
5128 This switch activates warnings on Export/Import pragmas when
5129 the compiler detects a possible conflict between the Ada and
5130 foreign language calling sequences. For example, the use of
5131 default parameters in a convention C procedure is dubious
5132 because the C compiler cannot supply the proper default, so
5133 a warning is issued. The default is that such warnings are
5134 generated.
5135 This warning can also be turned on using @option{-gnatwa}.
5136
5137 @item -gnatwX
5138 @emph{Suppress warnings on Export/Import pragmas.}
5139 @cindex @option{-gnatwX} (@command{gcc})
5140 This switch suppresses warnings on Export/Import pragmas.
5141 The sense of this is that you are telling the compiler that
5142 you know what you are doing in writing the pragma, and it
5143 should not complain at you.
5144
5145 @item -gnatwy
5146 @emph{Activate warnings for Ada 2005 compatibility issues.}
5147 @cindex @option{-gnatwy} (@command{gcc})
5148 @cindex Ada 2005 compatibility issues warnings
5149 For the most part Ada 2005 is upwards compatible with Ada 95,
5150 but there are some exceptions (for example the fact that
5151 @code{interface} is now a reserved word in Ada 2005). This
5152 switch activates several warnings to help in identifying
5153 and correcting such incompatibilities. The default is that
5154 these warnings are generated. Note that at one point Ada 2005
5155 was called Ada 0Y, hence the choice of character.
5156 This warning can also be turned on using @option{-gnatwa}.
5157
5158 @item -gnatwY
5159 @emph{Disable warnings for Ada 2005 compatibility issues.}
5160 @cindex @option{-gnatwY} (@command{gcc})
5161 @cindex Ada 2005 compatibility issues warnings
5162 This switch suppresses several warnings intended to help in identifying
5163 incompatibilities between Ada 95 and Ada 2005.
5164
5165 @item -gnatwz
5166 @emph{Activate warnings on unchecked conversions.}
5167 @cindex @option{-gnatwz} (@command{gcc})
5168 @cindex Unchecked_Conversion warnings
5169 This switch activates warnings for unchecked conversions
5170 where the types are known at compile time to have different
5171 sizes. The default
5172 is that such warnings are generated.
5173 This warning can also be turned on using @option{-gnatwa}.
5174
5175 @item -gnatwZ
5176 @emph{Suppress warnings on unchecked conversions.}
5177 @cindex @option{-gnatwZ} (@command{gcc})
5178 This switch suppresses warnings for unchecked conversions
5179 where the types are known at compile time to have different
5180 sizes.
5181
5182 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5183 @cindex @option{-Wuninitialized}
5184 The warnings controlled by the @option{-gnatw} switch are generated by the
5185 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5186 can provide additional warnings. One such useful warning is provided by
5187 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5188 conjunction with turning on optimization mode. This causes the flow
5189 analysis circuits of the back end optimizer to output additional
5190 warnings about uninitialized variables.
5191
5192 @item ^-w^/NO_BACK_END_WARNINGS^
5193 @cindex @option{-w}
5194 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5195 code generator detects a number of warning situations that are missed
5196 by the @option{GNAT} front end, and this switch can be used to suppress them.
5197 The use of this switch also sets the default front end warning mode to
5198 @option{-gnatws}, that is, front end warnings suppressed as well.
5199
5200 @end table
5201
5202 @noindent
5203 @ifclear vms
5204 A string of warning parameters can be used in the same parameter. For example:
5205
5206 @smallexample
5207 -gnatwaLe
5208 @end smallexample
5209
5210 @noindent
5211 will turn on all optional warnings except for elaboration pragma warnings,
5212 and also specify that warnings should be treated as errors.
5213 @end ifclear
5214 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5215
5216 @table @option
5217 @c !sort!
5218 @item -gnatwC
5219 @item -gnatwD
5220 @item -gnatwF
5221 @item -gnatwg
5222 @item -gnatwH
5223 @item -gnatwi
5224 @item -gnatwJ
5225 @item -gnatwK
5226 @item -gnatwL
5227 @item -gnatwM
5228 @item -gnatwn
5229 @item -gnatwo
5230 @item -gnatwP
5231 @item -gnatwR
5232 @item -gnatwU
5233 @item -gnatwv
5234 @item -gnatwz
5235 @item -gnatwx
5236
5237 @end table
5238
5239 @node Debugging and Assertion Control
5240 @subsection Debugging and Assertion Control
5241
5242 @table @option
5243 @item -gnata
5244 @cindex @option{-gnata} (@command{gcc})
5245 @findex Assert
5246 @findex Debug
5247 @cindex Assertions
5248
5249 @noindent
5250 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5251 are ignored. This switch, where @samp{a} stands for assert, causes
5252 @code{Assert} and @code{Debug} pragmas to be activated.
5253
5254 The pragmas have the form:
5255
5256 @smallexample
5257 @cartouche
5258    @b{pragma} Assert (@var{Boolean-expression} [,
5259                       @var{static-string-expression}])
5260    @b{pragma} Debug (@var{procedure call})
5261 @end cartouche
5262 @end smallexample
5263
5264 @noindent
5265 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5266 If the result is @code{True}, the pragma has no effect (other than
5267 possible side effects from evaluating the expression). If the result is
5268 @code{False}, the exception @code{Assert_Failure} declared in the package
5269 @code{System.Assertions} is
5270 raised (passing @var{static-string-expression}, if present, as the
5271 message associated with the exception). If no string expression is
5272 given the default is a string giving the file name and line number
5273 of the pragma.
5274
5275 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5276 @code{pragma Debug} may appear within a declaration sequence, allowing
5277 debugging procedures to be called between declarations.
5278
5279 @ifset vms
5280 @item /DEBUG[=debug-level]
5281 @itemx  /NODEBUG
5282 Specifies how much debugging information is to be included in
5283 the resulting object file where 'debug-level' is one of the following:
5284 @table @code
5285 @item   TRACEBACK
5286 Include both debugger symbol records and traceback
5287 the object file.
5288 This is the default setting.
5289 @item   ALL
5290 Include both debugger symbol records and traceback in
5291 object file.
5292 @item   NONE
5293 Excludes both debugger symbol records and traceback
5294 the object file. Same as /NODEBUG.
5295 @item   SYMBOLS
5296 Includes only debugger symbol records in the object
5297 file. Note that this doesn't include traceback information.
5298 @end table
5299 @end ifset
5300 @end table
5301
5302 @node Validity Checking
5303 @subsection Validity Checking
5304 @findex Validity Checking
5305
5306 @noindent
5307 The Ada 95 Reference Manual has specific requirements for checking
5308 for invalid values. In particular, RM 13.9.1 requires that the
5309 evaluation of invalid values (for example from unchecked conversions),
5310 not result in erroneous execution. In GNAT, the result of such an
5311 evaluation in normal default mode is to either use the value
5312 unmodified, or to raise Constraint_Error in those cases where use
5313 of the unmodified value would cause erroneous execution. The cases
5314 where unmodified values might lead to erroneous execution are case
5315 statements (where a wild jump might result from an invalid value),
5316 and subscripts on the left hand side (where memory corruption could
5317 occur as a result of an invalid value).
5318
5319 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5320 checking mode.
5321 @ifclear vms
5322 The @code{x} argument is a string of letters that
5323 indicate validity checks that are performed or not performed in addition
5324 to the default checks described above.
5325 @end ifclear
5326 @ifset vms
5327 The options allowed for this qualifier
5328 indicate validity checks that are performed or not performed in addition
5329 to the default checks described above.
5330 @end ifset
5331
5332 @table @option
5333 @c !sort!
5334 @item -gnatVa
5335 @emph{All validity checks.}
5336 @cindex @option{-gnatVa} (@command{gcc})
5337 All validity checks are turned on.
5338 @ifclear vms
5339 That is, @option{-gnatVa} is
5340 equivalent to @option{gnatVcdfimorst}.
5341 @end ifclear
5342
5343 @item -gnatVc
5344 @emph{Validity checks for copies.}
5345 @cindex @option{-gnatVc} (@command{gcc})
5346 The right hand side of assignments, and the initializing values of
5347 object declarations are validity checked.
5348
5349 @item -gnatVd
5350 @emph{Default (RM) validity checks.}
5351 @cindex @option{-gnatVd} (@command{gcc})
5352 Some validity checks are done by default following normal Ada semantics
5353 (RM 13.9.1 (9-11)).
5354 A check is done in case statements that the expression is within the range
5355 of the subtype. If it is not, Constraint_Error is raised.
5356 For assignments to array components, a check is done that the expression used
5357 as index is within the range. If it is not, Constraint_Error is raised.
5358 Both these validity checks may be turned off using switch @option{-gnatVD}.
5359 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5360 switch @option{-gnatVd} will leave the checks turned on.
5361 Switch @option{-gnatVD} should be used only if you are sure that all such
5362 expressions have valid values. If you use this switch and invalid values
5363 are present, then the program is erroneous, and wild jumps or memory
5364 overwriting may occur.
5365
5366 @item -gnatVe
5367 @emph{Validity checks for elementary components.}
5368 @cindex @option{-gnatVe} (@command{gcc})
5369 In the absence of this switch, assignments to record or array components are
5370 not validity checked, even if validity checks for assignments generally
5371 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5372 require valid data, but assignment of individual components does. So for
5373 example, there is a difference between copying the elements of an array with a
5374 slice assignment, compared to assigning element by element in a loop. This
5375 switch allows you to turn off validity checking for components, even when they
5376 are assigned component by component.
5377
5378 @item -gnatVf
5379 @emph{Validity checks for floating-point values.}
5380 @cindex @option{-gnatVf} (@command{gcc})
5381 In the absence of this switch, validity checking occurs only for discrete
5382 values. If @option{-gnatVf} is specified, then validity checking also applies
5383 for floating-point values, and NaN's and infinities are considered invalid,
5384 as well as out of range values for constrained types. Note that this means
5385 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5386 in which floating-point values are checked depends on the setting of other
5387 options. For example,
5388 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5389 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5390 (the order does not matter) specifies that floating-point parameters of mode
5391 @code{in} should be validity checked.
5392
5393 @item -gnatVi
5394 @emph{Validity checks for @code{in} mode parameters}
5395 @cindex @option{-gnatVi} (@command{gcc})
5396 Arguments for parameters of mode @code{in} are validity checked in function
5397 and procedure calls at the point of call.
5398
5399 @item -gnatVm
5400 @emph{Validity checks for @code{in out} mode parameters.}
5401 @cindex @option{-gnatVm} (@command{gcc})
5402 Arguments for parameters of mode @code{in out} are validity checked in
5403 procedure calls at the point of call. The @code{'m'} here stands for
5404 modify, since this concerns parameters that can be modified by the call.
5405 Note that there is no specific option to test @code{out} parameters,
5406 but any reference within the subprogram will be tested in the usual
5407 manner, and if an invalid value is copied back, any reference to it
5408 will be subject to validity checking.
5409
5410 @item -gnatVn
5411 @emph{No validity checks.}
5412 @cindex @option{-gnatVn} (@command{gcc})
5413 This switch turns off all validity checking, including the default checking
5414 for case statements and left hand side subscripts. Note that the use of
5415 the switch @option{-gnatp} suppresses all run-time checks, including
5416 validity checks, and thus implies @option{-gnatVn}. When this switch
5417 is used, it cancels any other @option{-gnatV} previously issued.
5418
5419 @item -gnatVo
5420 @emph{Validity checks for operator and attribute operands.}
5421 @cindex @option{-gnatVo} (@command{gcc})
5422 Arguments for predefined operators and attributes are validity checked.
5423 This includes all operators in package @code{Standard},
5424 the shift operators defined as intrinsic in package @code{Interfaces}
5425 and operands for attributes such as @code{Pos}. Checks are also made
5426 on individual component values for composite comparisons, and on the
5427 expressions in type conversions and qualified expressions. Checks are
5428 also made on explicit ranges using .. (e.g. slices, loops etc).
5429
5430 @item -gnatVp
5431 @emph{Validity checks for parameters.}
5432 @cindex @option{-gnatVp} (@command{gcc})
5433 This controls the treatment of parameters within a subprogram (as opposed
5434 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5435 of parameters on a call. If either of these call options is used, then
5436 normally an assumption is made within a subprogram that the input arguments
5437 have been validity checking at the point of call, and do not need checking
5438 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5439 is not made, and parameters are not assumed to be valid, so their validity
5440 will be checked (or rechecked) within the subprogram.
5441
5442 @item -gnatVr
5443 @emph{Validity checks for function returns.}
5444 @cindex @option{-gnatVr} (@command{gcc})
5445 The expression in @code{return} statements in functions is validity
5446 checked.
5447
5448 @item -gnatVs
5449 @emph{Validity checks for subscripts.}
5450 @cindex @option{-gnatVs} (@command{gcc})
5451 All subscripts expressions are checked for validity, whether they appear
5452 on the right side or left side (in default mode only left side subscripts
5453 are validity checked).
5454
5455 @item -gnatVt
5456 @emph{Validity checks for tests.}
5457 @cindex @option{-gnatVt} (@command{gcc})
5458 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5459 statements are checked, as well as guard expressions in entry calls.
5460
5461 @end table
5462
5463 @noindent
5464 The @option{-gnatV} switch may be followed by
5465 ^a string of letters^a list of options^
5466 to turn on a series of validity checking options.
5467 For example,
5468 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5469 specifies that in addition to the default validity checking, copies and
5470 function return expressions are to be validity checked.
5471 In order to make it easier
5472 to specify the desired combination of effects,
5473 @ifclear vms
5474 the upper case letters @code{CDFIMORST} may
5475 be used to turn off the corresponding lower case option.
5476 @end ifclear
5477 @ifset vms
5478 the prefix @code{NO} on an option turns off the corresponding validity
5479 checking:
5480 @itemize @bullet
5481 @item @code{NOCOPIES}
5482 @item @code{NODEFAULT}
5483 @item @code{NOFLOATS}
5484 @item @code{NOIN_PARAMS}
5485 @item @code{NOMOD_PARAMS}
5486 @item @code{NOOPERANDS}
5487 @item @code{NORETURNS}
5488 @item @code{NOSUBSCRIPTS}
5489 @item @code{NOTESTS}
5490 @end itemize
5491 @end ifset
5492 Thus
5493 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5494 turns on all validity checking options except for
5495 checking of @code{@b{in out}} procedure arguments.
5496
5497 The specification of additional validity checking generates extra code (and
5498 in the case of @option{-gnatVa} the code expansion can be substantial.
5499 However, these additional checks can be very useful in detecting
5500 uninitialized variables, incorrect use of unchecked conversion, and other
5501 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5502 is useful in conjunction with the extra validity checking, since this
5503 ensures that wherever possible uninitialized variables have invalid values.
5504
5505 See also the pragma @code{Validity_Checks} which allows modification of
5506 the validity checking mode at the program source level, and also allows for
5507 temporary disabling of validity checks.
5508
5509 @node Style Checking
5510 @subsection Style Checking
5511 @findex Style checking
5512
5513 @noindent
5514 The @option{-gnaty^x^(option,option,...)^} switch
5515 @cindex @option{-gnaty} (@command{gcc})
5516 causes the compiler to
5517 enforce specified style rules. A limited set of style rules has been used
5518 in writing the GNAT sources themselves. This switch allows user programs
5519 to activate all or some of these checks. If the source program fails a
5520 specified style check, an appropriate warning message is given, preceded by
5521 the character sequence ``(style)''.
5522 @ifset vms
5523 @code{(option,option,...)} is a sequence of keywords
5524 @end ifset
5525 @ifclear vms
5526 The string @var{x} is a sequence of letters or digits
5527 @end ifclear
5528 indicating the particular style
5529 checks to be performed. The following checks are defined:
5530
5531 @table @option
5532 @c !sort!
5533 @item 1-9
5534 @emph{Specify indentation level.}
5535 If a digit from 1-9 appears
5536 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5537 then proper indentation is checked, with the digit indicating the
5538 indentation level required.
5539 The general style of required indentation is as specified by
5540 the examples in the Ada Reference Manual. Full line comments must be
5541 aligned with the @code{--} starting on a column that is a multiple of
5542 the alignment level.
5543
5544 @item ^a^ATTRIBUTE^
5545 @emph{Check attribute casing.}
5546 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5547 then attribute names, including the case of keywords such as @code{digits}
5548 used as attributes names, must be written in mixed case, that is, the
5549 initial letter and any letter following an underscore must be uppercase.
5550 All other letters must be lowercase.
5551
5552 @item ^b^BLANKS^
5553 @emph{Blanks not allowed at statement end.}
5554 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5555 trailing blanks are not allowed at the end of statements. The purpose of this
5556 rule, together with h (no horizontal tabs), is to enforce a canonical format
5557 for the use of blanks to separate source tokens.
5558
5559 @item ^c^COMMENTS^
5560 @emph{Check comments.}
5561 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5562 then comments must meet the following set of rules:
5563
5564 @itemize @bullet
5565
5566 @item
5567 The ``@code{--}'' that starts the column must either start in column one,
5568 or else at least one blank must precede this sequence.
5569
5570 @item
5571 Comments that follow other tokens on a line must have at least one blank
5572 following the ``@code{--}'' at the start of the comment.
5573
5574 @item
5575 Full line comments must have two blanks following the ``@code{--}'' that
5576 starts the comment, with the following exceptions.
5577
5578 @item
5579 A line consisting only of the ``@code{--}'' characters, possibly preceded
5580 by blanks is permitted.
5581
5582 @item
5583 A comment starting with ``@code{--x}'' where @code{x} is a special character
5584 is permitted.
5585 This allows proper processing of the output generated by specialized tools
5586 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5587 annotation
5588 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5589 special character is defined as being in one of the ASCII ranges
5590 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5591 Note that this usage is not permitted
5592 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5593
5594 @item
5595 A line consisting entirely of minus signs, possibly preceded by blanks, is
5596 permitted. This allows the construction of box comments where lines of minus
5597 signs are used to form the top and bottom of the box.
5598
5599 @item
5600 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5601 least one blank follows the initial ``@code{--}''. Together with the preceding
5602 rule, this allows the construction of box comments, as shown in the following
5603 example:
5604 @smallexample
5605 ---------------------------
5606 -- This is a box comment --
5607 -- with two text lines.  --
5608 ---------------------------
5609 @end smallexample
5610 @end itemize
5611
5612 @item ^d^DOS_LINE_ENDINGS^
5613 @emph{Check no DOS line terminators present.}
5614 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5615 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5616 character (in particular the DOS line terminator sequence CR/LF is not
5617 allowed).
5618
5619 @item ^e^END^
5620 @emph{Check end/exit labels.}
5621 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5622 optional labels on @code{end} statements ending subprograms and on
5623 @code{exit} statements exiting named loops, are required to be present.
5624
5625 @item ^f^VTABS^
5626 @emph{No form feeds or vertical tabs.}
5627 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5628 neither form feeds nor vertical tab characters are permitted
5629 in the source text.
5630
5631 @item ^h^HTABS^
5632 @emph{No horizontal tabs.}
5633 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5634 horizontal tab characters are not permitted in the source text.
5635 Together with the b (no blanks at end of line) check, this
5636 enforces a canonical form for the use of blanks to separate
5637 source tokens.
5638
5639 @item ^i^IF_THEN^
5640 @emph{Check if-then layout.}
5641 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5642 then the keyword @code{then} must appear either on the same
5643 line as corresponding @code{if}, or on a line on its own, lined
5644 up under the @code{if} with at least one non-blank line in between
5645 containing all or part of the condition to be tested.
5646
5647 @item ^I^IN_MODE^
5648 @emph{check mode IN keywords}
5649 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5650 after @option{-gnaty} then mode @code{in} (the default mode) is not
5651 allowed to be given explicitly. @code{in out} is fine,
5652 but not @code{in} on its own.
5653
5654 @item ^k^KEYWORD^
5655 @emph{Check keyword casing.}
5656 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5657 all keywords must be in lower case (with the exception of keywords
5658 such as @code{digits} used as attribute names to which this check
5659 does not apply).
5660
5661 @item ^l^LAYOUT^
5662 @emph{Check layout.}
5663 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5664 layout of statement and declaration constructs must follow the
5665 recommendations in the Ada Reference Manual, as indicated by the
5666 form of the syntax rules. For example an @code{else} keyword must
5667 be lined up with the corresponding @code{if} keyword.
5668
5669 There are two respects in which the style rule enforced by this check
5670 option are more liberal than those in the Ada Reference Manual. First
5671 in the case of record declarations, it is permissible to put the
5672 @code{record} keyword on the same line as the @code{type} keyword, and
5673 then the @code{end} in @code{end record} must line up under @code{type}.
5674 For example, either of the following two layouts is acceptable:
5675
5676 @smallexample @c ada
5677 @cartouche
5678 type q is record
5679    a : integer;
5680    b : integer;
5681 end record;
5682
5683 type q is
5684    record
5685       a : integer;
5686       b : integer;
5687    end record;
5688 @end cartouche
5689 @end smallexample
5690
5691 @noindent
5692 Second, in the case of a block statement, a permitted alternative
5693 is to put the block label on the same line as the @code{declare} or
5694 @code{begin} keyword, and then line the @code{end} keyword up under
5695 the block label. For example both the following are permitted:
5696
5697 @smallexample @c ada
5698 @cartouche
5699 Block : declare
5700    A : Integer := 3;
5701 begin
5702    Proc (A, A);
5703 end Block;
5704
5705 Block :
5706    declare
5707       A : Integer := 3;
5708    begin
5709       Proc (A, A);
5710    end Block;
5711 @end cartouche
5712 @end smallexample
5713
5714 @noindent
5715 The same alternative format is allowed for loops. For example, both of
5716 the following are permitted:
5717
5718 @smallexample @c ada
5719 @cartouche
5720 Clear : while J < 10 loop
5721    A (J) := 0;
5722 end loop Clear;
5723
5724 Clear :
5725    while J < 10 loop
5726       A (J) := 0;
5727    end loop Clear;
5728 @end cartouche
5729 @end smallexample
5730
5731 @item ^Lnnn^MAX_NESTING=nnn^
5732 @emph{Set maximum nesting level}
5733 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5734 the range 0-999, appears in the string after @option{-gnaty} then the
5735 maximum level of nesting of constructs (including subprograms, loops,
5736 blocks, packages, and conditionals) may not exceed the given value. A
5737 value of zero disconnects this style check.
5738
5739 @item ^m^LINE_LENGTH^
5740 @emph{Check maximum line length.}
5741 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5742 then the length of source lines must not exceed 79 characters, including
5743 any trailing blanks. The value of 79 allows convenient display on an
5744 80 character wide device or window, allowing for possible special
5745 treatment of 80 character lines. Note that this count is of
5746 characters in the source text. This means that a tab character counts
5747 as one character in this count but a wide character sequence counts as
5748 a single character (however many bytes are needed in the encoding).
5749
5750 @item ^Mnnn^MAX_LENGTH=nnn^
5751 @emph{Set maximum line length.}
5752 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5753 the string after @option{-gnaty} then the length of lines must not exceed the
5754 given value. The maximum value that can be specified is 32767.
5755
5756 @item ^n^STANDARD_CASING^
5757 @emph{Check casing of entities in Standard.}
5758 If the ^letter n^word STANDARD_CASING^ appears in the string
5759 after @option{-gnaty} then any identifier from Standard must be cased
5760 to match the presentation in the Ada Reference Manual (for example,
5761 @code{Integer} and @code{ASCII.NUL}).
5762
5763 @item ^o^ORDERED_SUBPROGRAMS^
5764 @emph{Check order of subprogram bodies.}
5765 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5766 after @option{-gnaty} then all subprogram bodies in a given scope
5767 (e.g. a package body) must be in alphabetical order. The ordering
5768 rule uses normal Ada rules for comparing strings, ignoring casing
5769 of letters, except that if there is a trailing numeric suffix, then
5770 the value of this suffix is used in the ordering (e.g. Junk2 comes
5771 before Junk10).
5772
5773 @item ^p^PRAGMA^
5774 @emph{Check pragma casing.}
5775 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5776 pragma names must be written in mixed case, that is, the
5777 initial letter and any letter following an underscore must be uppercase.
5778 All other letters must be lowercase.
5779
5780 @item ^r^REFERENCES^
5781 @emph{Check references.}
5782 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5783 then all identifier references must be cased in the same way as the
5784 corresponding declaration. No specific casing style is imposed on
5785 identifiers. The only requirement is for consistency of references
5786 with declarations.
5787
5788 @item ^s^SPECS^
5789 @emph{Check separate specs.}
5790 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5791 separate declarations (``specs'') are required for subprograms (a
5792 body is not allowed to serve as its own declaration). The only
5793 exception is that parameterless library level procedures are
5794 not required to have a separate declaration. This exception covers
5795 the most frequent form of main program procedures.
5796
5797 @item ^t^TOKEN^
5798 @emph{Check token spacing.}
5799 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5800 the following token spacing rules are enforced:
5801
5802 @itemize @bullet
5803
5804 @item
5805 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5806
5807 @item
5808 The token @code{=>} must be surrounded by spaces.
5809
5810 @item
5811 The token @code{<>} must be preceded by a space or a left parenthesis.
5812
5813 @item
5814 Binary operators other than @code{**} must be surrounded by spaces.
5815 There is no restriction on the layout of the @code{**} binary operator.
5816
5817 @item
5818 Colon must be surrounded by spaces.
5819
5820 @item
5821 Colon-equal (assignment, initialization) must be surrounded by spaces.
5822
5823 @item
5824 Comma must be the first non-blank character on the line, or be
5825 immediately preceded by a non-blank character, and must be followed
5826 by a space.
5827
5828 @item
5829 If the token preceding a left parenthesis ends with a letter or digit, then
5830 a space must separate the two tokens.
5831
5832 @item
5833 A right parenthesis must either be the first non-blank character on
5834 a line, or it must be preceded by a non-blank character.
5835
5836 @item
5837 A semicolon must not be preceded by a space, and must not be followed by
5838 a non-blank character.
5839
5840 @item
5841 A unary plus or minus may not be followed by a space.
5842
5843 @item
5844 A vertical bar must be surrounded by spaces.
5845 @end itemize
5846
5847 @item ^u^UNNECESSARY_BLANK_LINES^
5848 @emph{Check unnecessary blank lines.}
5849 Check for unnecessary blank lines. A blank line is considered
5850 unnecessary if it appears at the end of the file, or if more than
5851 one blank line occurs in sequence.
5852
5853 @item ^x^XTRA_PARENS^
5854 @emph{Check extra parentheses.}
5855 Check for the use of an unnecessary extra level of parentheses (C-style)
5856 around conditions in @code{if} statements, @code{while} statements and
5857 @code{exit} statements.
5858
5859 @end table
5860
5861 @noindent
5862 In the above rules, appearing in column one is always permitted, that is,
5863 counts as meeting either a requirement for a required preceding space,
5864 or as meeting a requirement for no preceding space.
5865
5866 Appearing at the end of a line is also always permitted, that is, counts
5867 as meeting either a requirement for a following space, or as meeting
5868 a requirement for no following space.
5869
5870 @noindent
5871 If any of these style rules is violated, a message is generated giving
5872 details on the violation. The initial characters of such messages are
5873 always ``@code{(style)}''. Note that these messages are treated as warning
5874 messages, so they normally do not prevent the generation of an object
5875 file. The @option{-gnatwe} switch can be used to treat warning messages,
5876 including style messages, as fatal errors.
5877
5878 The switch
5879 @ifclear vms
5880 @option{-gnaty} on its own (that is not
5881 followed by any letters or digits),
5882 is equivalent to @code{gnaty3abcefhiklmnprst}, that is all checking
5883 options enabled with the exception of @option{-gnatyo},
5884 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
5885 @end ifclear
5886 @ifset vms
5887 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5888 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
5889 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
5890 @end ifset
5891 an indentation level of 3 is set. This is similar to the standard
5892 checking option that is used for the GNAT sources.
5893
5894 The switch
5895 @ifclear vms
5896 @option{-gnatyN}
5897 @end ifclear
5898 @ifset vms
5899 /STYLE_CHECKS=NONE
5900 @end ifset
5901 clears any previously set style checks.
5902
5903 @node Run-Time Checks
5904 @subsection Run-Time Checks
5905 @cindex Division by zero
5906 @cindex Access before elaboration
5907 @cindex Checks, division by zero
5908 @cindex Checks, access before elaboration
5909 @cindex Checks, stack overflow checking
5910
5911 @noindent
5912 If you compile with the default options, GNAT will insert many run-time
5913 checks into the compiled code, including code that performs range
5914 checking against constraints, but not arithmetic overflow checking for
5915 integer operations (including division by zero), checks for access
5916 before elaboration on subprogram calls, or stack overflow checking. All
5917 other run-time checks, as required by the Ada 95 Reference Manual, are
5918 generated by default. The following @command{gcc} switches refine this
5919 default behavior:
5920
5921 @table @option
5922 @c !sort!
5923 @item -gnatp
5924 @cindex @option{-gnatp} (@command{gcc})
5925 @cindex Suppressing checks
5926 @cindex Checks, suppressing
5927 @findex Suppress
5928 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5929 had been present in the source. Validity checks are also suppressed (in
5930 other words @option{-gnatp} also implies @option{-gnatVn}.
5931 Use this switch to improve the performance
5932 of the code at the expense of safety in the presence of invalid data or
5933 program bugs.
5934
5935 @item -gnato
5936 @cindex @option{-gnato} (@command{gcc})
5937 @cindex Overflow checks
5938 @cindex Check, overflow
5939 Enables overflow checking for integer operations.
5940 This causes GNAT to generate slower and larger executable
5941 programs by adding code to check for overflow (resulting in raising
5942 @code{Constraint_Error} as required by standard Ada
5943 semantics). These overflow checks correspond to situations in which
5944 the true value of the result of an operation may be outside the base
5945 range of the result type. The following example shows the distinction:
5946
5947 @smallexample @c ada
5948 X1 : Integer := Integer'Last;
5949 X2 : Integer range 1 .. 5 := 5;
5950 X3 : Integer := Integer'Last;
5951 X4 : Integer range 1 .. 5 := 5;
5952 F  : Float := 2.0E+20;
5953 ...
5954 X1 := X1 + 1;
5955 X2 := X2 + 1;
5956 X3 := Integer (F);
5957 X4 := Integer (F);
5958 @end smallexample
5959
5960 @noindent
5961 Here the first addition results in a value that is outside the base range
5962 of Integer, and hence requires an overflow check for detection of the
5963 constraint error. Thus the first assignment to @code{X1} raises a
5964 @code{Constraint_Error} exception only if @option{-gnato} is set.
5965
5966 The second increment operation results in a violation
5967 of the explicit range constraint, and such range checks are always
5968 performed (unless specifically suppressed with a pragma @code{suppress}
5969 or the use of @option{-gnatp}).
5970
5971 The two conversions of @code{F} both result in values that are outside
5972 the base range of type @code{Integer} and thus will raise
5973 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5974 The fact that the result of the second conversion is assigned to
5975 variable @code{X4} with a restricted range is irrelevant, since the problem
5976 is in the conversion, not the assignment.
5977
5978 Basically the rule is that in the default mode (@option{-gnato} not
5979 used), the generated code assures that all integer variables stay
5980 within their declared ranges, or within the base range if there is
5981 no declared range. This prevents any serious problems like indexes
5982 out of range for array operations.
5983
5984 What is not checked in default mode is an overflow that results in
5985 an in-range, but incorrect value. In the above example, the assignments
5986 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5987 range of the target variable, but the result is wrong in the sense that
5988 it is too large to be represented correctly. Typically the assignment
5989 to @code{X1} will result in wrap around to the largest negative number.
5990 The conversions of @code{F} will result in some @code{Integer} value
5991 and if that integer value is out of the @code{X4} range then the
5992 subsequent assignment would generate an exception.
5993
5994 @findex Machine_Overflows
5995 Note that the @option{-gnato} switch does not affect the code generated
5996 for any floating-point operations; it applies only to integer
5997 semantics).
5998 For floating-point, GNAT has the @code{Machine_Overflows}
5999 attribute set to @code{False} and the normal mode of operation is to
6000 generate IEEE NaN and infinite values on overflow or invalid operations
6001 (such as dividing 0.0 by 0.0).
6002
6003 The reason that we distinguish overflow checking from other kinds of
6004 range constraint checking is that a failure of an overflow check can
6005 generate an incorrect value, but cannot cause erroneous behavior. This
6006 is unlike the situation with a constraint check on an array subscript,
6007 where failure to perform the check can result in random memory description,
6008 or the range check on a case statement, where failure to perform the check
6009 can cause a wild jump.
6010
6011 Note again that @option{-gnato} is off by default, so overflow checking is
6012 not performed in default mode. This means that out of the box, with the
6013 default settings, GNAT does not do all the checks expected from the
6014 language description in the Ada Reference Manual. If you want all constraint
6015 checks to be performed, as described in this Manual, then you must
6016 explicitly use the -gnato switch either on the @command{gnatmake} or
6017 @command{gcc} command.
6018
6019 @item -gnatE
6020 @cindex @option{-gnatE} (@command{gcc})
6021 @cindex Elaboration checks
6022 @cindex Check, elaboration
6023 Enables dynamic checks for access-before-elaboration
6024 on subprogram calls and generic instantiations.
6025 For full details of the effect and use of this switch,
6026 @xref{Compiling Using gcc}.
6027
6028 @item -fstack-check
6029 @cindex @option{-fstack-check} (@command{gcc})
6030 @cindex Stack Overflow Checking
6031 @cindex Checks, stack overflow checking
6032 Activates stack overflow checking. For full details of the effect and use of
6033 this switch see @ref{Stack Overflow Checking}.
6034 @end table
6035
6036 @findex Unsuppress
6037 @noindent
6038 The setting of these switches only controls the default setting of the
6039 checks. You may modify them using either @code{Suppress} (to remove
6040 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6041 the program source.
6042
6043 @node Using gcc for Syntax Checking
6044 @subsection Using @command{gcc} for Syntax Checking
6045 @table @option
6046 @item -gnats
6047 @cindex @option{-gnats} (@command{gcc})
6048 @ifclear vms
6049
6050 @noindent
6051 The @code{s} stands for ``syntax''.
6052 @end ifclear
6053
6054 Run GNAT in syntax checking only mode. For
6055 example, the command
6056
6057 @smallexample
6058 $ gcc -c -gnats x.adb
6059 @end smallexample
6060
6061 @noindent
6062 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6063 series of files in a single command
6064 @ifclear vms
6065 , and can use wild cards to specify such a group of files.
6066 Note that you must specify the @option{-c} (compile
6067 only) flag in addition to the @option{-gnats} flag.
6068 @end ifclear
6069 .
6070 You may use other switches in conjunction with @option{-gnats}. In
6071 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6072 format of any generated error messages.
6073
6074 When the source file is empty or contains only empty lines and/or comments,
6075 the output is a warning:
6076
6077 @smallexample
6078 $ gcc -c -gnats -x ada toto.txt
6079 toto.txt:1:01: warning: empty file, contains no compilation units
6080 $
6081 @end smallexample
6082
6083 Otherwise, the output is simply the error messages, if any. No object file or
6084 ALI file is generated by a syntax-only compilation. Also, no units other
6085 than the one specified are accessed. For example, if a unit @code{X}
6086 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6087 check only mode does not access the source file containing unit
6088 @code{Y}.
6089
6090 @cindex Multiple units, syntax checking
6091 Normally, GNAT allows only a single unit in a source file. However, this
6092 restriction does not apply in syntax-check-only mode, and it is possible
6093 to check a file containing multiple compilation units concatenated
6094 together. This is primarily used by the @code{gnatchop} utility
6095 (@pxref{Renaming Files Using gnatchop}).
6096 @end table
6097
6098 @node Using gcc for Semantic Checking
6099 @subsection Using @command{gcc} for Semantic Checking
6100 @table @option
6101 @item -gnatc
6102 @cindex @option{-gnatc} (@command{gcc})
6103
6104 @ifclear vms
6105 @noindent
6106 The @code{c} stands for ``check''.
6107 @end ifclear
6108 Causes the compiler to operate in semantic check mode,
6109 with full checking for all illegalities specified in the
6110 Ada 95 Reference Manual, but without generation of any object code
6111 (no object file is generated).
6112
6113 Because dependent files must be accessed, you must follow the GNAT
6114 semantic restrictions on file structuring to operate in this mode:
6115
6116 @itemize @bullet
6117 @item
6118 The needed source files must be accessible
6119 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6120
6121 @item
6122 Each file must contain only one compilation unit.
6123
6124 @item
6125 The file name and unit name must match (@pxref{File Naming Rules}).
6126 @end itemize
6127
6128 The output consists of error messages as appropriate. No object file is
6129 generated. An @file{ALI} file is generated for use in the context of
6130 cross-reference tools, but this file is marked as not being suitable
6131 for binding (since no object file is generated).
6132 The checking corresponds exactly to the notion of
6133 legality in the Ada 95 Reference Manual.
6134
6135 Any unit can be compiled in semantics-checking-only mode, including
6136 units that would not normally be compiled (subunits,
6137 and specifications where a separate body is present).
6138 @end table
6139
6140 @node Compiling Different Versions of Ada
6141 @subsection Compiling Different Versions of Ada
6142 @table @option
6143 @cindex Compatibility with Ada 83
6144 @cindex Ada 83 mode
6145 @cindex Ada 95 mode
6146 @cindex Ada 2005 mode
6147
6148 GNAT is primarily an Ada 95 compiler, but the switches described in
6149 this section allow operation in Ada 83 compatibility mode, and also
6150 allow the use of a preliminary implementation of many of the expected
6151 new features in Ada 2005, the forthcoming new version of the standard.
6152
6153 @item -gnat83 (Ada 83 Compatibility Mode)
6154 @cindex @option{-gnat83} (@command{gcc})
6155 @cindex ACVC, Ada 83 tests
6156
6157 @noindent
6158 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
6159 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
6160 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
6161 where this can be done easily.
6162 It is not possible to guarantee this switch does a perfect
6163 job; for example, some subtle tests, such as are
6164 found in earlier ACVC tests (and that have been removed from the ACATS suite
6165 for Ada 95), might not compile correctly.
6166 Nevertheless, this switch may be useful in some circumstances, for example
6167 where, due to contractual reasons, legacy code needs to be maintained
6168 using only Ada 83 features.
6169
6170 With few exceptions (most notably the need to use @code{<>} on
6171 @cindex Generic formal parameters
6172 unconstrained generic formal parameters, the use of the new Ada 95
6173 reserved words, and the use of packages
6174 with optional bodies), it is not necessary to use the
6175 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6176 exceptions, Ada 95 is upwardly compatible with Ada 83. This
6177 means that a correct Ada 83 program is usually also a correct Ada 95
6178 program.
6179 For further information, please refer to @ref{Compatibility and Porting Guide}.
6180
6181 @item -gnat95 (Ada 95 mode)
6182 @cindex @option{-gnat95} (@command{gcc})
6183
6184 @noindent
6185 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
6186 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
6187 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
6188 this default Ada95 mode without problems (see section above describing the
6189 use of @option{-gnat83} to run in Ada 83 mode).
6190
6191 In Ada 95 mode, the use of Ada 2005 features will in general cause error
6192 messages or warnings. Some specialized releases of GNAT (notably the GPL
6193 edition) operate in Ada 2005 mode by default (see section below
6194 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
6195 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
6196 This option also can be used to cancel the effect of a previous
6197 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6198
6199 @item -gnat05 (Ada 2005 mode)
6200 @cindex @option{-gnat05} (@command{gcc})
6201
6202 @noindent
6203 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
6204 in Ada 2005 mode using this option. Although the new standard has not
6205 yet been issued (as of early 2005), many features have been discussed and
6206 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
6207 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
6208 releases is a file @file{features-ada0y} that describes the current set
6209 of implemented Ada 2005 features.
6210
6211 If these features are used in Ada 95 mode (which is the normal default),
6212 then error messages or warnings may be
6213 generated, reflecting the fact that these new features are otherwise
6214 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
6215 switch (or an equivalent pragma) causes these messages to be suppressed.
6216
6217 Note that some specialized releases of GNAT (notably the GPL edition)
6218 have Ada 2005 mode on by default, and in such environments,
6219 the Ada 2005 features can be used freely without the use of switches.
6220
6221 @end table
6222
6223 @node Character Set Control
6224 @subsection Character Set Control
6225 @table @option
6226 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6227 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6228
6229 @noindent
6230 Normally GNAT recognizes the Latin-1 character set in source program
6231 identifiers, as described in the Ada 95 Reference Manual.
6232 This switch causes
6233 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6234 single character ^^or word^ indicating the character set, as follows:
6235
6236 @table @code
6237 @item 1
6238 ISO 8859-1 (Latin-1) identifiers
6239
6240 @item 2
6241 ISO 8859-2 (Latin-2) letters allowed in identifiers
6242
6243 @item 3
6244 ISO 8859-3 (Latin-3) letters allowed in identifiers
6245
6246 @item 4
6247 ISO 8859-4 (Latin-4) letters allowed in identifiers
6248
6249 @item 5
6250 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6251
6252 @item 9
6253 ISO 8859-15 (Latin-9) letters allowed in identifiers
6254
6255 @item ^p^PC^
6256 IBM PC letters (code page 437) allowed in identifiers
6257
6258 @item ^8^PC850^
6259 IBM PC letters (code page 850) allowed in identifiers
6260
6261 @item ^f^FULL_UPPER^
6262 Full upper-half codes allowed in identifiers
6263
6264 @item ^n^NO_UPPER^
6265 No upper-half codes allowed in identifiers
6266
6267 @item ^w^WIDE^
6268 Wide-character codes (that is, codes greater than 255)
6269 allowed in identifiers
6270 @end table
6271
6272 @xref{Foreign Language Representation}, for full details on the
6273 implementation of these character sets.
6274
6275 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6276 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6277 Specify the method of encoding for wide characters.
6278 @var{e} is one of the following:
6279
6280 @table @code
6281
6282 @item ^h^HEX^
6283 Hex encoding (brackets coding also recognized)
6284
6285 @item ^u^UPPER^
6286 Upper half encoding (brackets encoding also recognized)
6287
6288 @item ^s^SHIFT_JIS^
6289 Shift/JIS encoding (brackets encoding also recognized)
6290
6291 @item ^e^EUC^
6292 EUC encoding (brackets encoding also recognized)
6293
6294 @item ^8^UTF8^
6295 UTF-8 encoding (brackets encoding also recognized)
6296
6297 @item ^b^BRACKETS^
6298 Brackets encoding only (default value)
6299 @end table
6300 For full details on these encoding
6301 methods see @ref{Wide Character Encodings}.
6302 Note that brackets coding is always accepted, even if one of the other
6303 options is specified, so for example @option{-gnatW8} specifies that both
6304 brackets and @code{UTF-8} encodings will be recognized. The units that are
6305 with'ed directly or indirectly will be scanned using the specified
6306 representation scheme, and so if one of the non-brackets scheme is
6307 used, it must be used consistently throughout the program. However,
6308 since brackets encoding is always recognized, it may be conveniently
6309 used in standard libraries, allowing these libraries to be used with
6310 any of the available coding schemes.
6311 scheme. If no @option{-gnatW?} parameter is present, then the default
6312 representation is Brackets encoding only.
6313
6314 Note that the wide character representation that is specified (explicitly
6315 or by default) for the main program also acts as the default encoding used
6316 for Wide_Text_IO files if not specifically overridden by a WCEM form
6317 parameter.
6318
6319 @end table
6320 @node File Naming Control
6321 @subsection File Naming Control
6322
6323 @table @option
6324 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6325 @cindex @option{-gnatk} (@command{gcc})
6326 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6327 1-999, indicates the maximum allowable length of a file name (not
6328 including the @file{.ads} or @file{.adb} extension). The default is not
6329 to enable file name krunching.
6330
6331 For the source file naming rules, @xref{File Naming Rules}.
6332 @end table
6333
6334 @node Subprogram Inlining Control
6335 @subsection Subprogram Inlining Control
6336
6337 @table @option
6338 @c !sort!
6339 @item -gnatn
6340 @cindex @option{-gnatn} (@command{gcc})
6341 @ifclear vms
6342 The @code{n} here is intended to suggest the first syllable of the
6343 word ``inline''.
6344 @end ifclear
6345 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6346 inlining to actually occur, optimization must be enabled. To enable
6347 inlining of subprograms specified by pragma @code{Inline},
6348 you must also specify this switch.
6349 In the absence of this switch, GNAT does not attempt
6350 inlining and does not need to access the bodies of
6351 subprograms for which @code{pragma Inline} is specified if they are not
6352 in the current unit.
6353
6354 If you specify this switch the compiler will access these bodies,
6355 creating an extra source dependency for the resulting object file, and
6356 where possible, the call will be inlined.
6357 For further details on when inlining is possible
6358 see @ref{Inlining of Subprograms}.
6359
6360 @item -gnatN
6361 @cindex @option{-gnatN} (@command{gcc})
6362 The front end inlining activated by this switch is generally more extensive,
6363 and quite often more effective than the standard @option{-gnatn} inlining mode.
6364 It will also generate additional dependencies.
6365 Note that
6366 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6367 to specify both options.
6368 @end table
6369
6370 @node Auxiliary Output Control
6371 @subsection Auxiliary Output Control
6372
6373 @table @option
6374 @item -gnatt
6375 @cindex @option{-gnatt} (@command{gcc})
6376 @cindex Writing internal trees
6377 @cindex Internal trees, writing to file
6378 Causes GNAT to write the internal tree for a unit to a file (with the
6379 extension @file{.adt}.
6380 This not normally required, but is used by separate analysis tools.
6381 Typically
6382 these tools do the necessary compilations automatically, so you should
6383 not have to specify this switch in normal operation.
6384
6385 @item -gnatu
6386 @cindex @option{-gnatu} (@command{gcc})
6387 Print a list of units required by this compilation on @file{stdout}.
6388 The listing includes all units on which the unit being compiled depends
6389 either directly or indirectly.
6390
6391 @ifclear vms
6392 @item -pass-exit-codes
6393 @cindex @option{-pass-exit-codes} (@command{gcc})
6394 If this switch is not used, the exit code returned by @command{gcc} when
6395 compiling multiple files indicates whether all source files have
6396 been successfully used to generate object files or not.
6397
6398 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6399 exit status and allows an integrated development environment to better
6400 react to a compilation failure. Those exit status are:
6401
6402 @table @asis
6403 @item 5
6404 There was an error in at least one source file.
6405 @item 3
6406 At least one source file did not generate an object file.
6407 @item 2
6408 The compiler died unexpectedly (internal error for example).
6409 @item 0
6410 An object file has been generated for every source file.
6411 @end table
6412 @end ifclear
6413 @end table
6414
6415 @node Debugging Control
6416 @subsection Debugging Control
6417
6418 @table @option
6419 @c !sort!
6420 @cindex Debugging options
6421 @ifclear vms
6422 @item -gnatd@var{x}
6423 @cindex @option{-gnatd} (@command{gcc})
6424 Activate internal debugging switches. @var{x} is a letter or digit, or
6425 string of letters or digits, which specifies the type of debugging
6426 outputs desired. Normally these are used only for internal development
6427 or system debugging purposes. You can find full documentation for these
6428 switches in the body of the @code{Debug} unit in the compiler source
6429 file @file{debug.adb}.
6430 @end ifclear
6431
6432 @item -gnatG
6433 @cindex @option{-gnatG} (@command{gcc})
6434 This switch causes the compiler to generate auxiliary output containing
6435 a pseudo-source listing of the generated expanded code. Like most Ada
6436 compilers, GNAT works by first transforming the high level Ada code into
6437 lower level constructs. For example, tasking operations are transformed
6438 into calls to the tasking run-time routines. A unique capability of GNAT
6439 is to list this expanded code in a form very close to normal Ada source.
6440 This is very useful in understanding the implications of various Ada
6441 usage on the efficiency of the generated code. There are many cases in
6442 Ada (e.g. the use of controlled types), where simple Ada statements can
6443 generate a lot of run-time code. By using @option{-gnatG} you can identify
6444 these cases, and consider whether it may be desirable to modify the coding
6445 approach to improve efficiency.
6446
6447 The format of the output is very similar to standard Ada source, and is
6448 easily understood by an Ada programmer. The following special syntactic
6449 additions correspond to low level features used in the generated code that
6450 do not have any exact analogies in pure Ada source form. The following
6451 is a partial list of these special constructions. See the specification
6452 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6453
6454 If the switch @option{-gnatL} is used in conjunction with
6455 @cindex @option{-gnatL} (@command{gcc})
6456 @option{-gnatG}, then the original source lines are interspersed
6457 in the expanded source (as comment lines with the original line number).
6458
6459 @table @code
6460 @item new @var{xxx} [storage_pool = @var{yyy}]
6461 Shows the storage pool being used for an allocator.
6462
6463 @item at end @var{procedure-name};
6464 Shows the finalization (cleanup) procedure for a scope.
6465
6466 @item (if @var{expr} then @var{expr} else @var{expr})
6467 Conditional expression equivalent to the @code{x?y:z} construction in C.
6468
6469 @item @var{target}^^^(@var{source})
6470 A conversion with floating-point truncation instead of rounding.
6471
6472 @item @var{target}?(@var{source})
6473 A conversion that bypasses normal Ada semantic checking. In particular
6474 enumeration types and fixed-point types are treated simply as integers.
6475
6476 @item @var{target}?^^^(@var{source})
6477 Combines the above two cases.
6478
6479 @item @var{x} #/ @var{y}
6480 @itemx @var{x} #mod @var{y}
6481 @itemx @var{x} #* @var{y}
6482 @itemx @var{x} #rem @var{y}
6483 A division or multiplication of fixed-point values which are treated as
6484 integers without any kind of scaling.
6485
6486 @item free @var{expr} [storage_pool = @var{xxx}]
6487 Shows the storage pool associated with a @code{free} statement.
6488
6489 @item [subtype or type declaration]
6490 Used to list an equivalent declaration for an internally generated
6491 type that is referenced elsewhere in the listing.
6492
6493 @item freeze @var{type-name} [@var{actions}]
6494 Shows the point at which @var{type-name} is frozen, with possible
6495 associated actions to be performed at the freeze point.
6496
6497 @item reference @var{itype}
6498 Reference (and hence definition) to internal type @var{itype}.
6499
6500 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6501 Intrinsic function call.
6502
6503 @item @var{label-name} : label
6504 Declaration of label @var{labelname}.
6505
6506 @item #$ @var{subprogram-name}
6507 An implicit call to a run-time support routine
6508 (to meet the requirement of H.3.1(9) in a
6509 convenient manner).
6510
6511 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6512 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6513 @var{expr}, but handled more efficiently).
6514
6515 @item [constraint_error]
6516 Raise the @code{Constraint_Error} exception.
6517
6518 @item @var{expression}'reference
6519 A pointer to the result of evaluating @var{expression}.
6520
6521 @item @var{target-type}!(@var{source-expression})
6522 An unchecked conversion of @var{source-expression} to @var{target-type}.
6523
6524 @item [@var{numerator}/@var{denominator}]
6525 Used to represent internal real literals (that) have no exact
6526 representation in base 2-16 (for example, the result of compile time
6527 evaluation of the expression 1.0/27.0).
6528 @end table
6529
6530 @item -gnatD
6531 @cindex @option{-gnatD} (@command{gcc})
6532 When used in conjunction with @option{-gnatG}, this switch causes
6533 the expanded source, as described above for
6534 @option{-gnatG} to be written to files with names
6535 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6536 instead of to the standard output file. For
6537 example, if the source file name is @file{hello.adb}, then a file
6538 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6539 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6540 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6541 you to do source level debugging using the generated code which is
6542 sometimes useful for complex code, for example to find out exactly
6543 which part of a complex construction raised an exception. This switch
6544 also suppress generation of cross-reference information (see
6545 @option{-gnatx}) since otherwise the cross-reference information
6546 would refer to the @file{^.dg^.DG^} file, which would cause
6547 confusion since this is not the original source file.
6548
6549 Note that @option{-gnatD} actually implies @option{-gnatG}
6550 automatically, so it is not necessary to give both options.
6551 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6552
6553 If the switch @option{-gnatL} is used in conjunction with
6554 @cindex @option{-gnatL} (@command{gcc})
6555 @option{-gnatDG}, then the original source lines are interspersed
6556 in the expanded source (as comment lines with the original line number).
6557
6558 @ifclear vms
6559 @item -gnatR[0|1|2|3[s]]
6560 @cindex @option{-gnatR} (@command{gcc})
6561 This switch controls output from the compiler of a listing showing
6562 representation information for declared types and objects. For
6563 @option{-gnatR0}, no information is output (equivalent to omitting
6564 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6565 so @option{-gnatR} with no parameter has the same effect), size and alignment
6566 information is listed for declared array and record types. For
6567 @option{-gnatR2}, size and alignment information is listed for all
6568 expressions for values that are computed at run time for
6569 variant records. These symbolic expressions have a mostly obvious
6570 format with #n being used to represent the value of the n'th
6571 discriminant. See source files @file{repinfo.ads/adb} in the
6572 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6573 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6574 the output is to a file with the name @file{^file.rep^file_REP^} where
6575 file is the name of the corresponding source file.
6576 @end ifclear
6577 @ifset vms
6578 @item /REPRESENTATION_INFO
6579 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6580 This qualifier controls output from the compiler of a listing showing
6581 representation information for declared types and objects. For
6582 @option{/REPRESENTATION_INFO=NONE}, no information is output
6583 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6584 @option{/REPRESENTATION_INFO} without option is equivalent to
6585 @option{/REPRESENTATION_INFO=ARRAYS}.
6586 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6587 information is listed for declared array and record types. For
6588 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6589 is listed for all expression information for values that are computed
6590 at run time for variant records. These symbolic expressions have a mostly
6591 obvious format with #n being used to represent the value of the n'th
6592 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6593 @code{GNAT} sources for full details on the format of
6594 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6595 If _FILE is added at the end of an option
6596 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6597 then the output is to a file with the name @file{file_REP} where
6598 file is the name of the corresponding source file.
6599 @end ifset
6600 Note that it is possible for record components to have zero size. In
6601 this case, the component clause uses an obvious extension of permitted
6602 Ada syntax, for example @code{at 0 range 0 .. -1}.
6603
6604 @item -gnatS
6605 @cindex @option{-gnatS} (@command{gcc})
6606 The use of the switch @option{-gnatS} for an
6607 Ada compilation will cause the compiler to output a
6608 representation of package Standard in a form very
6609 close to standard Ada. It is not quite possible to
6610 do this entirely in standard Ada (since new
6611 numeric base types cannot be created in standard
6612 Ada), but the output is easily
6613 readable to any Ada programmer, and is useful to
6614 determine the characteristics of target dependent
6615 types in package Standard.
6616
6617 @item -gnatx
6618 @cindex @option{-gnatx} (@command{gcc})
6619 Normally the compiler generates full cross-referencing information in
6620 the @file{ALI} file. This information is used by a number of tools,
6621 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6622 suppresses this information. This saves some space and may slightly
6623 speed up compilation, but means that these tools cannot be used.
6624 @end table
6625
6626 @node Exception Handling Control
6627 @subsection Exception Handling Control
6628
6629 @noindent
6630 GNAT uses two methods for handling exceptions at run-time. The
6631 @code{setjmp/longjmp} method saves the context when entering
6632 a frame with an exception handler. Then when an exception is
6633 raised, the context can be restored immediately, without the
6634 need for tracing stack frames. This method provides very fast
6635 exception propagation, but introduces significant overhead for
6636 the use of exception handlers, even if no exception is raised.
6637
6638 The other approach is called ``zero cost'' exception handling.
6639 With this method, the compiler builds static tables to describe
6640 the exception ranges. No dynamic code is required when entering
6641 a frame containing an exception handler. When an exception is
6642 raised, the tables are used to control a back trace of the
6643 subprogram invocation stack to locate the required exception
6644 handler. This method has considerably poorer performance for
6645 the propagation of exceptions, but there is no overhead for
6646 exception handlers if no exception is raised. Note that in this
6647 mode and in the context of mixed Ada and C/C++ programming,
6648 to propagate an exception through a C/C++ code, the C/C++ code
6649 must be compiled with the @option{-funwind-tables} GCC's
6650 option.
6651
6652 The following switches can be used to control which of the
6653 two exception handling methods is used.
6654
6655 @table @option
6656 @c !sort!
6657
6658 @item --RTS=sjlj
6659 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6660 This switch causes the setjmp/longjmp run-time to be used
6661 for exception handling. If this is the default mechanism for the
6662 target (see below), then this has no effect. If the default
6663 mechanism for the target is zero cost exceptions, then
6664 this switch can be used to modify this default, and must be
6665 used for all units in the partition.
6666 This option is rarely used. One case in which it may be
6667 advantageous is if you have an application where exception
6668 raising is common and the overall performance of the
6669 application is improved by favoring exception propagation.
6670
6671 @item --RTS=zcx
6672 @cindex @option{--RTS=zcx} (@command{gnatmake})
6673 @cindex Zero Cost Exceptions
6674 This switch causes the zero cost approach to be used
6675 for exception handling. If this is the default mechanism for the
6676 target (see below), then this has no effect. If the default
6677 mechanism for the target is setjmp/longjmp exceptions, then
6678 this switch can be used to modify this default, and must be
6679 used for all units in the partition.
6680 This option can only be used if the zero cost approach
6681 is available for the target in use (see below).
6682 @end table
6683
6684 @noindent
6685 The same option @option{--RTS} must be used both for @command{gcc}
6686 and @command{gnatbind}. Passing this option to @command{gnatmake}
6687 (@pxref{Switches for gnatmake}) will ensure the required consistency
6688 through the compilation and binding steps.
6689
6690 The @code{setjmp/longjmp} approach is available on all targets, while
6691 the @code{zero cost} approach is available on selected targets.
6692 To determine whether zero cost exceptions can be used for a
6693 particular target, look at the private part of the file system.ads.
6694 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6695 be True to use the zero cost approach. If both of these switches
6696 are set to False, this means that zero cost exception handling
6697 is not yet available for that target. The switch
6698 @code{ZCX_By_Default} indicates the default approach. If this
6699 switch is set to True, then the @code{zero cost} approach is
6700 used by default.
6701
6702 @node Units to Sources Mapping Files
6703 @subsection Units to Sources Mapping Files
6704
6705 @table @option
6706
6707 @item -gnatem^^=^@var{path}
6708 @cindex @option{-gnatem} (@command{gcc})
6709 A mapping file is a way to communicate to the compiler two mappings:
6710 from unit names to file names (without any directory information) and from
6711 file names to path names (with full directory information). These mappings
6712 are used by the compiler to short-circuit the path search.
6713
6714 The use of mapping files is not required for correct operation of the
6715 compiler, but mapping files can improve efficiency, particularly when
6716 sources are read over a slow network connection. In normal operation,
6717 you need not be concerned with the format or use of mapping files,
6718 and the @option{-gnatem} switch is not a switch that you would use
6719 explicitly. it is intended only for use by automatic tools such as
6720 @command{gnatmake} running under the project file facility. The
6721 description here of the format of mapping files is provided
6722 for completeness and for possible use by other tools.
6723
6724 A mapping file is a sequence of sets of three lines. In each set,
6725 the first line is the unit name, in lower case, with ``@code{%s}''
6726 appended for
6727 specifications and ``@code{%b}'' appended for bodies; the second line is the
6728 file name; and the third line is the path name.
6729
6730 Example:
6731 @smallexample
6732    main%b
6733    main.2.ada
6734    /gnat/project1/sources/main.2.ada
6735 @end smallexample
6736
6737 When the switch @option{-gnatem} is specified, the compiler will create
6738 in memory the two mappings from the specified file. If there is any problem
6739 (non existent file, truncated file or duplicate entries), no mapping
6740 will be created.
6741
6742 Several @option{-gnatem} switches may be specified; however, only the last
6743 one on the command line will be taken into account.
6744
6745 When using a project file, @command{gnatmake} create a temporary mapping file
6746 and communicates it to the compiler using this switch.
6747
6748 @end table
6749
6750 @node Integrated Preprocessing
6751 @subsection Integrated Preprocessing
6752
6753 @noindent
6754 GNAT sources may be preprocessed immediately before compilation; the actual
6755 text of the source is not the text of the source file, but is derived from it
6756 through a process called preprocessing. Integrated preprocessing is specified
6757 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6758 indicates, through a text file, the preprocessing data to be used.
6759 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6760
6761 @noindent
6762 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6763 used when Integrated Preprocessing is used. The reason is that preprocessing
6764 with another Preprocessing Data file without changing the sources will
6765 not trigger recompilation without this switch.
6766
6767 @noindent
6768 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6769 always trigger recompilation for sources that are preprocessed,
6770 because @command{gnatmake} cannot compute the checksum of the source after
6771 preprocessing.
6772
6773 @noindent
6774 The actual preprocessing function is described in details in section
6775 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6776 preprocessing is triggered and parameterized.
6777
6778 @table @code
6779
6780 @item -gnatep=@var{file}
6781 @cindex @option{-gnatep} (@command{gcc})
6782 This switch indicates to the compiler the file name (without directory
6783 information) of the preprocessor data file to use. The preprocessor data file
6784 should be found in the source directories.
6785
6786 @noindent
6787 A preprocessing data file is a text file with significant lines indicating
6788 how should be preprocessed either a specific source or all sources not
6789 mentioned in other lines. A significant line is a non empty, non comment line.
6790 Comments are similar to Ada comments.
6791
6792 @noindent
6793 Each significant line starts with either a literal string or the character '*'.
6794 A literal string is the file name (without directory information) of the source
6795 to preprocess. A character '*' indicates the preprocessing for all the sources
6796 that are not specified explicitly on other lines (order of the lines is not
6797 significant). It is an error to have two lines with the same file name or two
6798 lines starting with the character '*'.
6799
6800 @noindent
6801 After the file name or the character '*', another optional literal string
6802 indicating the file name of the definition file to be used for preprocessing
6803 (@pxref{Form of Definitions File}). The definition files are found by the
6804 compiler in one of the source directories. In some cases, when compiling
6805 a source in a directory other than the current directory, if the definition
6806 file is in the current directory, it may be necessary to add the current
6807 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6808 the compiler would not find the definition file.
6809
6810 @noindent
6811 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6812 be found. Those ^switches^switches^ are:
6813
6814 @table @code
6815
6816 @item -b
6817 Causes both preprocessor lines and the lines deleted by
6818 preprocessing to be replaced by blank lines, preserving the line number.
6819 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6820 it cancels the effect of @option{-c}.
6821
6822 @item -c
6823 Causes both preprocessor lines and the lines deleted
6824 by preprocessing to be retained as comments marked
6825 with the special string ``@code{--! }''.
6826
6827 @item -Dsymbol=value
6828 Define or redefine a symbol, associated with value. A symbol is an Ada
6829 identifier, or an Ada reserved word, with the exception of @code{if},
6830 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6831 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6832 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6833 same name defined in a definition file.
6834
6835 @item -s
6836 Causes a sorted list of symbol names and values to be
6837 listed on the standard output file.
6838
6839 @item -u
6840 Causes undefined symbols to be treated as having the value @code{FALSE}
6841 in the context
6842 of a preprocessor test. In the absence of this option, an undefined symbol in
6843 a @code{#if} or @code{#elsif} test will be treated as an error.
6844
6845 @end table
6846
6847 @noindent
6848 Examples of valid lines in a preprocessor data file:
6849
6850 @smallexample
6851   "toto.adb"  "prep.def" -u
6852   --  preprocess "toto.adb", using definition file "prep.def",
6853   --  undefined symbol are False.
6854
6855   * -c -DVERSION=V101
6856   --  preprocess all other sources without a definition file;
6857   --  suppressed lined are commented; symbol VERSION has the value V101.
6858
6859   "titi.adb" "prep2.def" -s
6860   --  preprocess "titi.adb", using definition file "prep2.def";
6861   --  list all symbols with their values.
6862 @end smallexample
6863
6864 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6865 @cindex @option{-gnateD} (@command{gcc})
6866 Define or redefine a preprocessing symbol, associated with value. If no value
6867 is given on the command line, then the value of the symbol is @code{True}.
6868 A symbol is an identifier, following normal Ada (case-insensitive)
6869 rules for its syntax, and value is any sequence (including an empty sequence)
6870 of characters from the set (letters, digits, period, underline).
6871 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6872 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6873
6874 @noindent
6875 A symbol declared with this ^switch^switch^ on the command line replaces a
6876 symbol with the same name either in a definition file or specified with a
6877 ^switch^switch^ -D in the preprocessor data file.
6878
6879 @noindent
6880 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6881
6882 @end table
6883
6884 @node Code Generation Control
6885 @subsection Code Generation Control
6886
6887 @noindent
6888
6889 The GCC technology provides a wide range of target dependent
6890 @option{-m} switches for controlling
6891 details of code generation with respect to different versions of
6892 architectures. This includes variations in instruction sets (e.g.
6893 different members of the power pc family), and different requirements
6894 for optimal arrangement of instructions (e.g. different members of
6895 the x86 family). The list of available @option{-m} switches may be
6896 found in the GCC documentation.
6897
6898 Use of these @option{-m} switches may in some cases result in improved
6899 code performance.
6900
6901 The GNAT Pro technology is tested and qualified without any
6902 @option{-m} switches,
6903 so generally the most reliable approach is to avoid the use of these
6904 switches. However, we generally expect most of these switches to work
6905 successfully with GNAT Pro, and many customers have reported successful
6906 use of these options.
6907
6908 Our general advice is to avoid the use of @option{-m} switches unless
6909 special needs lead to requirements in this area. In particular,
6910 there is no point in using @option{-m} switches to improve performance
6911 unless you actually see a performance improvement.
6912
6913 @ifset vms
6914 @node Return Codes
6915 @subsection Return Codes
6916 @cindex Return Codes
6917 @cindex @option{/RETURN_CODES=VMS}
6918
6919 @noindent
6920 On VMS, GNAT compiled programs return POSIX-style codes by default,
6921 e.g. @option{/RETURN_CODES=POSIX}.
6922
6923 To enable VMS style return codes, use GNAT BIND and LINK with the option
6924 @option{/RETURN_CODES=VMS}. For example:
6925
6926 @smallexample
6927 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6928 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6929 @end smallexample
6930
6931 @noindent
6932 Programs built with /RETURN_CODES=VMS are suitable to be called in
6933 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6934 are suitable for spawning with appropriate GNAT RTL routines.
6935
6936 @end ifset
6937
6938 @node Search Paths and the Run-Time Library (RTL)
6939 @section Search Paths and the Run-Time Library (RTL)
6940
6941 @noindent
6942 With the GNAT source-based library system, the compiler must be able to
6943 find source files for units that are needed by the unit being compiled.
6944 Search paths are used to guide this process.
6945
6946 The compiler compiles one source file whose name must be given
6947 explicitly on the command line. In other words, no searching is done
6948 for this file. To find all other source files that are needed (the most
6949 common being the specs of units), the compiler examines the following
6950 directories, in the following order:
6951
6952 @enumerate
6953 @item
6954 The directory containing the source file of the main unit being compiled
6955 (the file name on the command line).
6956
6957 @item
6958 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6959 @command{gcc} command line, in the order given.
6960
6961 @item
6962 @findex ADA_PRJ_INCLUDE_FILE
6963 Each of the directories listed in the text file whose name is given
6964 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6965
6966 @noindent
6967 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6968 driver when project files are used. It should not normally be set
6969 by other means.
6970
6971 @item
6972 @findex ADA_INCLUDE_PATH
6973 Each of the directories listed in the value of the
6974 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6975 @ifclear vms
6976 Construct this value
6977 exactly as the @code{PATH} environment variable: a list of directory
6978 names separated by colons (semicolons when working with the NT version).
6979 @end ifclear
6980 @ifset vms
6981 Normally, define this value as a logical name containing a comma separated
6982 list of directory names.
6983
6984 This variable can also be defined by means of an environment string
6985 (an argument to the HP C exec* set of functions).
6986
6987 Logical Name:
6988 @smallexample
6989 DEFINE ANOTHER_PATH FOO:[BAG]
6990 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6991 @end smallexample
6992
6993 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6994 first, followed by the standard Ada 95
6995 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6996 If this is not redefined, the user will obtain the HP Ada 83 IO packages
6997 (Text_IO, Sequential_IO, etc)
6998 instead of the Ada95 packages. Thus, in order to get the Ada 95
6999 packages by default, ADA_INCLUDE_PATH must be redefined.
7000 @end ifset
7001
7002 @item
7003 The content of the @file{ada_source_path} file which is part of the GNAT
7004 installation tree and is used to store standard libraries such as the
7005 GNAT Run Time Library (RTL) source files.
7006 @ifclear vms
7007 @ref{Installing a library}
7008 @end ifclear
7009 @end enumerate
7010
7011 @noindent
7012 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7013 inhibits the use of the directory
7014 containing the source file named in the command line. You can still
7015 have this directory on your search path, but in this case it must be
7016 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7017
7018 Specifying the switch @option{-nostdinc}
7019 inhibits the search of the default location for the GNAT Run Time
7020 Library (RTL) source files.
7021
7022 The compiler outputs its object files and ALI files in the current
7023 working directory.
7024 @ifclear vms
7025 Caution: The object file can be redirected with the @option{-o} switch;
7026 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7027 so the @file{ALI} file will not go to the right place. Therefore, you should
7028 avoid using the @option{-o} switch.
7029 @end ifclear
7030
7031 @findex System.IO
7032 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7033 children make up the GNAT RTL, together with the simple @code{System.IO}
7034 package used in the @code{"Hello World"} example. The sources for these units
7035 are needed by the compiler and are kept together in one directory. Not
7036 all of the bodies are needed, but all of the sources are kept together
7037 anyway. In a normal installation, you need not specify these directory
7038 names when compiling or binding. Either the environment variables or
7039 the built-in defaults cause these files to be found.
7040
7041 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7042 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7043 consisting of child units of @code{GNAT}. This is a collection of generally
7044 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
7045 further details.
7046
7047 Besides simplifying access to the RTL, a major use of search paths is
7048 in compiling sources from multiple directories. This can make
7049 development environments much more flexible.
7050
7051 @node Order of Compilation Issues
7052 @section Order of Compilation Issues
7053
7054 @noindent
7055 If, in our earlier example, there was a spec for the @code{hello}
7056 procedure, it would be contained in the file @file{hello.ads}; yet this
7057 file would not have to be explicitly compiled. This is the result of the
7058 model we chose to implement library management. Some of the consequences
7059 of this model are as follows:
7060
7061 @itemize @bullet
7062 @item
7063 There is no point in compiling specs (except for package
7064 specs with no bodies) because these are compiled as needed by clients. If
7065 you attempt a useless compilation, you will receive an error message.
7066 It is also useless to compile subunits because they are compiled as needed
7067 by the parent.
7068
7069 @item
7070 There are no order of compilation requirements: performing a
7071 compilation never obsoletes anything. The only way you can obsolete
7072 something and require recompilations is to modify one of the
7073 source files on which it depends.
7074
7075 @item
7076 There is no library as such, apart from the ALI files
7077 (@pxref{The Ada Library Information Files}, for information on the format
7078 of these files). For now we find it convenient to create separate ALI files,
7079 but eventually the information therein may be incorporated into the object
7080 file directly.
7081
7082 @item
7083 When you compile a unit, the source files for the specs of all units
7084 that it @code{with}'s, all its subunits, and the bodies of any generics it
7085 instantiates must be available (reachable by the search-paths mechanism
7086 described above), or you will receive a fatal error message.
7087 @end itemize
7088
7089 @node Examples
7090 @section Examples
7091
7092 @noindent
7093 The following are some typical Ada compilation command line examples:
7094
7095 @table @code
7096 @item $ gcc -c xyz.adb
7097 Compile body in file @file{xyz.adb} with all default options.
7098
7099 @ifclear vms
7100 @item $ gcc -c -O2 -gnata xyz-def.adb
7101 @end ifclear
7102 @ifset vms
7103 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7104 @end ifset
7105
7106 Compile the child unit package in file @file{xyz-def.adb} with extensive
7107 optimizations, and pragma @code{Assert}/@code{Debug} statements
7108 enabled.
7109
7110 @item $ gcc -c -gnatc abc-def.adb
7111 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7112 mode.
7113 @end table
7114
7115 @node Binding Using gnatbind
7116 @chapter Binding Using @code{gnatbind}
7117 @findex gnatbind
7118
7119 @menu
7120 * Running gnatbind::
7121 * Switches for gnatbind::
7122 * Command-Line Access::
7123 * Search Paths for gnatbind::
7124 * Examples of gnatbind Usage::
7125 @end menu
7126
7127 @noindent
7128 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7129 to bind compiled GNAT objects. The @code{gnatbind} program performs
7130 four separate functions:
7131
7132 @enumerate
7133 @item
7134 Checks that a program is consistent, in accordance with the rules in
7135 Chapter 10 of the Ada 95 Reference Manual. In particular, error
7136 messages are generated if a program uses inconsistent versions of a
7137 given unit.
7138
7139 @item
7140 Checks that an acceptable order of elaboration exists for the program
7141 and issues an error message if it cannot find an order of elaboration
7142 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
7143
7144 @item
7145 Generates a main program incorporating the given elaboration order.
7146 This program is a small Ada package (body and spec) that
7147 must be subsequently compiled
7148 using the GNAT compiler. The necessary compilation step is usually
7149 performed automatically by @command{gnatlink}. The two most important
7150 functions of this program
7151 are to call the elaboration routines of units in an appropriate order
7152 and to call the main program.
7153
7154 @item
7155 Determines the set of object files required by the given main program.
7156 This information is output in the forms of comments in the generated program,
7157 to be read by the @command{gnatlink} utility used to link the Ada application.
7158 @end enumerate
7159
7160 @node Running gnatbind
7161 @section Running @code{gnatbind}
7162
7163 @noindent
7164 The form of the @code{gnatbind} command is
7165
7166 @smallexample
7167 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7168 @end smallexample
7169
7170 @noindent
7171 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7172 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7173 package in two files whose names are
7174 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7175 For example, if given the
7176 parameter @file{hello.ali}, for a main program contained in file
7177 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7178 and @file{b~hello.adb}.
7179
7180 When doing consistency checking, the binder takes into consideration
7181 any source files it can locate. For example, if the binder determines
7182 that the given main program requires the package @code{Pack}, whose
7183 @file{.ALI}
7184 file is @file{pack.ali} and whose corresponding source spec file is
7185 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7186 (using the same search path conventions as previously described for the
7187 @command{gcc} command). If it can locate this source file, it checks that
7188 the time stamps
7189 or source checksums of the source and its references to in @file{ALI} files
7190 match. In other words, any @file{ALI} files that mentions this spec must have
7191 resulted from compiling this version of the source file (or in the case
7192 where the source checksums match, a version close enough that the
7193 difference does not matter).
7194
7195 @cindex Source files, use by binder
7196 The effect of this consistency checking, which includes source files, is
7197 that the binder ensures that the program is consistent with the latest
7198 version of the source files that can be located at bind time. Editing a
7199 source file without compiling files that depend on the source file cause
7200 error messages to be generated by the binder.
7201
7202 For example, suppose you have a main program @file{hello.adb} and a
7203 package @code{P}, from file @file{p.ads} and you perform the following
7204 steps:
7205
7206 @enumerate
7207 @item
7208 Enter @code{gcc -c hello.adb} to compile the main program.
7209
7210 @item
7211 Enter @code{gcc -c p.ads} to compile package @code{P}.
7212
7213 @item
7214 Edit file @file{p.ads}.
7215
7216 @item
7217 Enter @code{gnatbind hello}.
7218 @end enumerate
7219
7220 @noindent
7221 At this point, the file @file{p.ali} contains an out-of-date time stamp
7222 because the file @file{p.ads} has been edited. The attempt at binding
7223 fails, and the binder generates the following error messages:
7224
7225 @smallexample
7226 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7227 error: "p.ads" has been modified and must be recompiled
7228 @end smallexample
7229
7230 @noindent
7231 Now both files must be recompiled as indicated, and then the bind can
7232 succeed, generating a main program. You need not normally be concerned
7233 with the contents of this file, but for reference purposes a sample
7234 binder output file is given in @ref{Example of Binder Output File}.
7235
7236 In most normal usage, the default mode of @command{gnatbind} which is to
7237 generate the main package in Ada, as described in the previous section.
7238 In particular, this means that any Ada programmer can read and understand
7239 the generated main program. It can also be debugged just like any other
7240 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7241 @command{gnatbind} and @command{gnatlink}.
7242
7243 However for some purposes it may be convenient to generate the main
7244 program in C rather than Ada. This may for example be helpful when you
7245 are generating a mixed language program with the main program in C. The
7246 GNAT compiler itself is an example.
7247 The use of the @option{^-C^/BIND_FILE=C^} switch
7248 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7249 be generated in C (and compiled using the gnu C compiler).
7250
7251 @node Switches for gnatbind
7252 @section Switches for @command{gnatbind}
7253
7254 @noindent
7255 The following switches are available with @code{gnatbind}; details will
7256 be presented in subsequent sections.
7257
7258 @menu
7259 * Consistency-Checking Modes::
7260 * Binder Error Message Control::
7261 * Elaboration Control::
7262 * Output Control::
7263 * Binding with Non-Ada Main Programs::
7264 * Binding Programs with No Main Subprogram::
7265 @end menu
7266
7267 @table @option
7268 @c !sort!
7269 @item ^-aO^/OBJECT_SEARCH^
7270 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7271 Specify directory to be searched for ALI files.
7272
7273 @item ^-aI^/SOURCE_SEARCH^
7274 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7275 Specify directory to be searched for source file.
7276
7277 @item ^-A^/BIND_FILE=ADA^
7278 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7279 Generate binder program in Ada (default)
7280
7281 @item ^-b^/REPORT_ERRORS=BRIEF^
7282 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7283 Generate brief messages to @file{stderr} even if verbose mode set.
7284
7285 @item ^-c^/NOOUTPUT^
7286 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7287 Check only, no generation of binder output file.
7288
7289 @item ^-C^/BIND_FILE=C^
7290 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7291 Generate binder program in C
7292
7293 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7294 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7295 This switch can be used to change the default task stack size value
7296 to a specified size @var{nn}, which is expressed in bytes by default, or
7297 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7298 with @var{m}.
7299 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7300 to completing all task specs with
7301 @smallexample @c ada
7302    pragma Storage_Size (nn);
7303 @end smallexample
7304 When they do not already have such a pragma.
7305
7306 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7307 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7308 This switch can be used to change the default secondary stack size value
7309 to a specified size @var{nn}, which is expressed in bytes by default, or
7310 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7311 with @var{m}.
7312
7313 The secondary stack is used to deal with functions that return a variable
7314 sized result, for example a function returning an unconstrained
7315 String. There are two ways in which this secondary stack is allocated.
7316
7317 For most targets, the secondary stack is growing on demand and is allocated
7318 as a chain of blocks in the heap. The -D option is not very
7319 relevant. It only give some control over the size of the allocated
7320 blocks (whose size is the minimum of the default secondary stack size value,
7321 and the actual size needed for the current allocation request).
7322
7323 For certain targets, notably VxWorks 653,
7324 the secondary stack is allocated by carving off a fixed ratio chunk of the
7325 primary task stack. The -D option is used to defined the
7326 size of the environment task's secondary stack.
7327
7328 @item ^-e^/ELABORATION_DEPENDENCIES^
7329 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7330 Output complete list of elaboration-order dependencies.
7331
7332 @item ^-E^/STORE_TRACEBACKS^
7333 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7334 Store tracebacks in exception occurrences when the target supports it.
7335 This is the default with the zero cost exception mechanism.
7336 @ignore
7337 @c The following may get moved to an appendix
7338 This option is currently supported on the following targets:
7339 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7340 @end ignore
7341 See also the packages @code{GNAT.Traceback} and
7342 @code{GNAT.Traceback.Symbolic} for more information.
7343 @ifclear vms
7344 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7345 @command{gcc} option.
7346 @end ifclear
7347
7348 @item ^-F^/FORCE_ELABS_FLAGS^
7349 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7350 Force the checks of elaboration flags. @command{gnatbind} does not normally
7351 generate checks of elaboration flags for the main executable, except when
7352 a Stand-Alone Library is used. However, there are cases when this cannot be
7353 detected by gnatbind. An example is importing an interface of a Stand-Alone
7354 Library through a pragma Import and only specifying through a linker switch
7355 this Stand-Alone Library. This switch is used to guarantee that elaboration
7356 flag checks are generated.
7357
7358 @item ^-h^/HELP^
7359 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7360 Output usage (help) information
7361
7362 @item ^-I^/SEARCH^
7363 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7364 Specify directory to be searched for source and ALI files.
7365
7366 @item ^-I-^/NOCURRENT_DIRECTORY^
7367 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7368 Do not look for sources in the current directory where @code{gnatbind} was
7369 invoked, and do not look for ALI files in the directory containing the
7370 ALI file named in the @code{gnatbind} command line.
7371
7372 @item ^-l^/ORDER_OF_ELABORATION^
7373 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7374 Output chosen elaboration order.
7375
7376 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7377 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7378 Bind the units for library building. In this case the adainit and
7379 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7380 are renamed to ^xxxinit^XXXINIT^ and
7381 ^xxxfinal^XXXFINAL^.
7382 Implies ^-n^/NOCOMPILE^.
7383 @ifclear vms
7384 (@xref{GNAT and Libraries}, for more details.)
7385 @end ifclear
7386 @ifset vms
7387 On OpenVMS, these init and final procedures are exported in uppercase
7388 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7389 the init procedure will be "TOTOINIT" and the exported name of the final
7390 procedure will be "TOTOFINAL".
7391 @end ifset
7392
7393 @item ^-Mxyz^/RENAME_MAIN=xyz^
7394 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7395 Rename generated main program from main to xyz. This option is
7396 supported on cross environments only.
7397
7398 @item ^-m^/ERROR_LIMIT=^@var{n}
7399 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7400 Limit number of detected errors to @var{n}, where @var{n} is
7401 in the range 1..999_999. The default value if no switch is
7402 given is 9999. Binding is terminated if the limit is exceeded.
7403 @ifset unw
7404 Furthermore, under Windows, the sources pointed to by the libraries path
7405 set in the registry are not searched for.
7406 @end ifset
7407
7408 @item ^-n^/NOMAIN^
7409 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7410 No main program.
7411
7412 @item -nostdinc
7413 @cindex @option{-nostdinc} (@command{gnatbind})
7414 Do not look for sources in the system default directory.
7415
7416 @item -nostdlib
7417 @cindex @option{-nostdlib} (@command{gnatbind})
7418 Do not look for library files in the system default directory.
7419
7420 @item --RTS=@var{rts-path}
7421 @cindex @option{--RTS} (@code{gnatbind})
7422 Specifies the default location of the runtime library. Same meaning as the
7423 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7424
7425 @item ^-o ^/OUTPUT=^@var{file}
7426 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7427 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7428 Note that if this option is used, then linking must be done manually,
7429 gnatlink cannot be used.
7430
7431 @item ^-O^/OBJECT_LIST^
7432 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7433 Output object list.
7434
7435 @item ^-p^/PESSIMISTIC_ELABORATION^
7436 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7437 Pessimistic (worst-case) elaboration order
7438
7439 @item ^-s^/READ_SOURCES=ALL^
7440 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7441 Require all source files to be present.
7442
7443 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7444 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7445 Specifies the value to be used when detecting uninitialized scalar
7446 objects with pragma Initialize_Scalars.
7447 The @var{xxx} ^string specified with the switch^option^ may be either
7448 @itemize @bullet
7449 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7450 @item ``@option{^lo^LOW^}'' for the lowest possible value
7451 @item ``@option{^hi^HIGH^}'' for the highest possible value
7452 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7453 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7454 @end itemize
7455
7456 In addition, you can specify @option{-Sev} to indicate that the value is
7457 to be set at run time. In this case, the program will look for an environment
7458 @cindex GNAT_INIT_SCALARS
7459 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7460 of @option{in/lo/hi/xx} with the same meanings as above.
7461 If no environment variable is found, or if it does not have a valid value,
7462 then the default is @option{in} (invalid values).
7463
7464 @ifclear vms
7465 @item -static
7466 @cindex @option{-static} (@code{gnatbind})
7467 Link against a static GNAT run time.
7468
7469 @item -shared
7470 @cindex @option{-shared} (@code{gnatbind})
7471 Link against a shared GNAT run time when available.
7472 @end ifclear
7473
7474 @item ^-t^/NOTIME_STAMP_CHECK^
7475 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7476 Tolerate time stamp and other consistency errors
7477
7478 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7479 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7480 Set the time slice value to @var{n} milliseconds. If the system supports
7481 the specification of a specific time slice value, then the indicated value
7482 is used. If the system does not support specific time slice values, but
7483 does support some general notion of round-robin scheduling, then any
7484 nonzero value will activate round-robin scheduling.
7485
7486 A value of zero is treated specially. It turns off time
7487 slicing, and in addition, indicates to the tasking run time that the
7488 semantics should match as closely as possible the Annex D
7489 requirements of the Ada RM, and in particular sets the default
7490 scheduling policy to @code{FIFO_Within_Priorities}.
7491
7492 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7493 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7494 Enable dynamic stack usage, with n result stored and displayed at program
7495 termination. Results that can't be stored are displayed on the fly, at task
7496 termination. This option is currently not supported on OpenVMS I64 platforms.
7497
7498 @item ^-v^/REPORT_ERRORS=VERBOSE^
7499 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7500 Verbose mode. Write error messages, header, summary output to
7501 @file{stdout}.
7502
7503 @ifclear vms
7504 @item -w@var{x}
7505 @cindex @option{-w} (@code{gnatbind})
7506 Warning mode (@var{x}=s/e for suppress/treat as error)
7507 @end ifclear
7508
7509 @ifset vms
7510 @item /WARNINGS=NORMAL
7511 @cindex @option{/WARNINGS} (@code{gnatbind})
7512 Normal warnings mode. Warnings are issued but ignored
7513
7514 @item /WARNINGS=SUPPRESS
7515 @cindex @option{/WARNINGS} (@code{gnatbind})
7516 All warning messages are suppressed
7517
7518 @item /WARNINGS=ERROR
7519 @cindex @option{/WARNINGS} (@code{gnatbind})
7520 Warning messages are treated as fatal errors
7521 @end ifset
7522
7523 @item ^-x^/READ_SOURCES=NONE^
7524 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7525 Exclude source files (check object consistency only).
7526
7527 @ifset vms
7528 @item /READ_SOURCES=AVAILABLE
7529 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7530 Default mode, in which sources are checked for consistency only if
7531 they are available.
7532 @end ifset
7533
7534 @item ^-z^/ZERO_MAIN^
7535 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7536 No main subprogram.
7537 @end table
7538
7539 @ifclear vms
7540 @noindent
7541 You may obtain this listing of switches by running @code{gnatbind} with
7542 no arguments.
7543 @end ifclear
7544
7545 @node Consistency-Checking Modes
7546 @subsection Consistency-Checking Modes
7547
7548 @noindent
7549 As described earlier, by default @code{gnatbind} checks
7550 that object files are consistent with one another and are consistent
7551 with any source files it can locate. The following switches control binder
7552 access to sources.
7553
7554 @table @option
7555 @c !sort!
7556 @item ^-s^/READ_SOURCES=ALL^
7557 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7558 Require source files to be present. In this mode, the binder must be
7559 able to locate all source files that are referenced, in order to check
7560 their consistency. In normal mode, if a source file cannot be located it
7561 is simply ignored. If you specify this switch, a missing source
7562 file is an error.
7563
7564 @item ^-x^/READ_SOURCES=NONE^
7565 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7566 Exclude source files. In this mode, the binder only checks that ALI
7567 files are consistent with one another. Source files are not accessed.
7568 The binder runs faster in this mode, and there is still a guarantee that
7569 the resulting program is self-consistent.
7570 If a source file has been edited since it was last compiled, and you
7571 specify this switch, the binder will not detect that the object
7572 file is out of date with respect to the source file. Note that this is the
7573 mode that is automatically used by @command{gnatmake} because in this
7574 case the checking against sources has already been performed by
7575 @command{gnatmake} in the course of compilation (i.e. before binding).
7576
7577 @ifset vms
7578 @item /READ_SOURCES=AVAILABLE
7579 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7580 This is the default mode in which source files are checked if they are
7581 available, and ignored if they are not available.
7582 @end ifset
7583 @end table
7584
7585 @node Binder Error Message Control
7586 @subsection Binder Error Message Control
7587
7588 @noindent
7589 The following switches provide control over the generation of error
7590 messages from the binder:
7591
7592 @table @option
7593 @c !sort!
7594 @item ^-v^/REPORT_ERRORS=VERBOSE^
7595 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7596 Verbose mode. In the normal mode, brief error messages are generated to
7597 @file{stderr}. If this switch is present, a header is written
7598 to @file{stdout} and any error messages are directed to @file{stdout}.
7599 All that is written to @file{stderr} is a brief summary message.
7600
7601 @item ^-b^/REPORT_ERRORS=BRIEF^
7602 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7603 Generate brief error messages to @file{stderr} even if verbose mode is
7604 specified. This is relevant only when used with the
7605 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7606
7607 @ifclear vms
7608 @item -m@var{n}
7609 @cindex @option{-m} (@code{gnatbind})
7610 Limits the number of error messages to @var{n}, a decimal integer in the
7611 range 1-999. The binder terminates immediately if this limit is reached.
7612
7613 @item -M@var{xxx}
7614 @cindex @option{-M} (@code{gnatbind})
7615 Renames the generated main program from @code{main} to @code{xxx}.
7616 This is useful in the case of some cross-building environments, where
7617 the actual main program is separate from the one generated
7618 by @code{gnatbind}.
7619 @end ifclear
7620
7621 @item ^-ws^/WARNINGS=SUPPRESS^
7622 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7623 @cindex Warnings
7624 Suppress all warning messages.
7625
7626 @item ^-we^/WARNINGS=ERROR^
7627 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7628 Treat any warning messages as fatal errors.
7629
7630 @ifset vms
7631 @item /WARNINGS=NORMAL
7632 Standard mode with warnings generated, but warnings do not get treated
7633 as errors.
7634 @end ifset
7635
7636 @item ^-t^/NOTIME_STAMP_CHECK^
7637 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7638 @cindex Time stamp checks, in binder
7639 @cindex Binder consistency checks
7640 @cindex Consistency checks, in binder
7641 The binder performs a number of consistency checks including:
7642
7643 @itemize @bullet
7644 @item
7645 Check that time stamps of a given source unit are consistent
7646 @item
7647 Check that checksums of a given source unit are consistent
7648 @item
7649 Check that consistent versions of @code{GNAT} were used for compilation
7650 @item
7651 Check consistency of configuration pragmas as required
7652 @end itemize
7653
7654 @noindent
7655 Normally failure of such checks, in accordance with the consistency
7656 requirements of the Ada Reference Manual, causes error messages to be
7657 generated which abort the binder and prevent the output of a binder
7658 file and subsequent link to obtain an executable.
7659
7660 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7661 into warnings, so that
7662 binding and linking can continue to completion even in the presence of such
7663 errors. The result may be a failed link (due to missing symbols), or a
7664 non-functional executable which has undefined semantics.
7665 @emph{This means that
7666 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7667 with extreme care.}
7668 @end table
7669
7670 @node Elaboration Control
7671 @subsection Elaboration Control
7672
7673 @noindent
7674 The following switches provide additional control over the elaboration
7675 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7676
7677 @table @option
7678 @item ^-p^/PESSIMISTIC_ELABORATION^
7679 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7680 Normally the binder attempts to choose an elaboration order that is
7681 likely to minimize the likelihood of an elaboration order error resulting
7682 in raising a @code{Program_Error} exception. This switch reverses the
7683 action of the binder, and requests that it deliberately choose an order
7684 that is likely to maximize the likelihood of an elaboration error.
7685 This is useful in ensuring portability and avoiding dependence on
7686 accidental fortuitous elaboration ordering.
7687
7688 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7689 switch if dynamic
7690 elaboration checking is used (@option{-gnatE} switch used for compilation).
7691 This is because in the default static elaboration mode, all necessary
7692 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7693 These implicit pragmas are still respected by the binder in
7694 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7695 safe elaboration order is assured.
7696 @end table
7697
7698 @node Output Control
7699 @subsection Output Control
7700
7701 @noindent
7702 The following switches allow additional control over the output
7703 generated by the binder.
7704
7705 @table @option
7706 @c !sort!
7707
7708 @item ^-A^/BIND_FILE=ADA^
7709 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7710 Generate binder program in Ada (default). The binder program is named
7711 @file{b~@var{mainprog}.adb} by default. This can be changed with
7712 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7713
7714 @item ^-c^/NOOUTPUT^
7715 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7716 Check only. Do not generate the binder output file. In this mode the
7717 binder performs all error checks but does not generate an output file.
7718
7719 @item ^-C^/BIND_FILE=C^
7720 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7721 Generate binder program in C. The binder program is named
7722 @file{b_@var{mainprog}.c}.
7723 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7724 option.
7725
7726 @item ^-e^/ELABORATION_DEPENDENCIES^
7727 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7728 Output complete list of elaboration-order dependencies, showing the
7729 reason for each dependency. This output can be rather extensive but may
7730 be useful in diagnosing problems with elaboration order. The output is
7731 written to @file{stdout}.
7732
7733 @item ^-h^/HELP^
7734 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7735 Output usage information. The output is written to @file{stdout}.
7736
7737 @item ^-K^/LINKER_OPTION_LIST^
7738 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7739 Output linker options to @file{stdout}. Includes library search paths,
7740 contents of pragmas Ident and Linker_Options, and libraries added
7741 by @code{gnatbind}.
7742
7743 @item ^-l^/ORDER_OF_ELABORATION^
7744 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7745 Output chosen elaboration order. The output is written to @file{stdout}.
7746
7747 @item ^-O^/OBJECT_LIST^
7748 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7749 Output full names of all the object files that must be linked to provide
7750 the Ada component of the program. The output is written to @file{stdout}.
7751 This list includes the files explicitly supplied and referenced by the user
7752 as well as implicitly referenced run-time unit files. The latter are
7753 omitted if the corresponding units reside in shared libraries. The
7754 directory names for the run-time units depend on the system configuration.
7755
7756 @item ^-o ^/OUTPUT=^@var{file}
7757 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7758 Set name of output file to @var{file} instead of the normal
7759 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7760 binder generated body filename. In C mode you would normally give
7761 @var{file} an extension of @file{.c} because it will be a C source program.
7762 Note that if this option is used, then linking must be done manually.
7763 It is not possible to use gnatlink in this case, since it cannot locate
7764 the binder file.
7765
7766 @item ^-r^/RESTRICTION_LIST^
7767 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7768 Generate list of @code{pragma Restrictions} that could be applied to
7769 the current unit. This is useful for code audit purposes, and also may
7770 be used to improve code generation in some cases.
7771
7772 @end table
7773
7774 @node Binding with Non-Ada Main Programs
7775 @subsection Binding with Non-Ada Main Programs
7776
7777 @noindent
7778 In our description so far we have assumed that the main
7779 program is in Ada, and that the task of the binder is to generate a
7780 corresponding function @code{main} that invokes this Ada main
7781 program. GNAT also supports the building of executable programs where
7782 the main program is not in Ada, but some of the called routines are
7783 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7784 The following switch is used in this situation:
7785
7786 @table @option
7787 @item ^-n^/NOMAIN^
7788 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7789 No main program. The main program is not in Ada.
7790 @end table
7791
7792 @noindent
7793 In this case, most of the functions of the binder are still required,
7794 but instead of generating a main program, the binder generates a file
7795 containing the following callable routines:
7796
7797 @table @code
7798 @item adainit
7799 @findex adainit
7800 You must call this routine to initialize the Ada part of the program by
7801 calling the necessary elaboration routines. A call to @code{adainit} is
7802 required before the first call to an Ada subprogram.
7803
7804 Note that it is assumed that the basic execution environment must be setup
7805 to be appropriate for Ada execution at the point where the first Ada
7806 subprogram is called. In particular, if the Ada code will do any
7807 floating-point operations, then the FPU must be setup in an appropriate
7808 manner. For the case of the x86, for example, full precision mode is
7809 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7810 that the FPU is in the right state.
7811
7812 @item adafinal
7813 @findex adafinal
7814 You must call this routine to perform any library-level finalization
7815 required by the Ada subprograms. A call to @code{adafinal} is required
7816 after the last call to an Ada subprogram, and before the program
7817 terminates.
7818 @end table
7819
7820 @noindent
7821 If the @option{^-n^/NOMAIN^} switch
7822 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7823 @cindex Binder, multiple input files
7824 is given, more than one ALI file may appear on
7825 the command line for @code{gnatbind}. The normal @dfn{closure}
7826 calculation is performed for each of the specified units. Calculating
7827 the closure means finding out the set of units involved by tracing
7828 @code{with} references. The reason it is necessary to be able to
7829 specify more than one ALI file is that a given program may invoke two or
7830 more quite separate groups of Ada units.
7831
7832 The binder takes the name of its output file from the last specified ALI
7833 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7834 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7835 The output is an Ada unit in source form that can
7836 be compiled with GNAT unless the -C switch is used in which case the
7837 output is a C source file, which must be compiled using the C compiler.
7838 This compilation occurs automatically as part of the @command{gnatlink}
7839 processing.
7840
7841 Currently the GNAT run time requires a FPU using 80 bits mode
7842 precision. Under targets where this is not the default it is required to
7843 call GNAT.Float_Control.Reset before using floating point numbers (this
7844 include float computation, float input and output) in the Ada code. A
7845 side effect is that this could be the wrong mode for the foreign code
7846 where floating point computation could be broken after this call.
7847
7848 @node Binding Programs with No Main Subprogram
7849 @subsection Binding Programs with No Main Subprogram
7850
7851 @noindent
7852 It is possible to have an Ada program which does not have a main
7853 subprogram. This program will call the elaboration routines of all the
7854 packages, then the finalization routines.
7855
7856 The following switch is used to bind programs organized in this manner:
7857
7858 @table @option
7859 @item ^-z^/ZERO_MAIN^
7860 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7861 Normally the binder checks that the unit name given on the command line
7862 corresponds to a suitable main subprogram. When this switch is used,
7863 a list of ALI files can be given, and the execution of the program
7864 consists of elaboration of these units in an appropriate order.
7865 @end table
7866
7867 @node Command-Line Access
7868 @section Command-Line Access
7869
7870 @noindent
7871 The package @code{Ada.Command_Line} provides access to the command-line
7872 arguments and program name. In order for this interface to operate
7873 correctly, the two variables
7874
7875 @smallexample
7876 @group
7877 int gnat_argc;
7878 char **gnat_argv;
7879 @end group
7880 @end smallexample
7881
7882 @noindent
7883 @findex gnat_argv
7884 @findex gnat_argc
7885 are declared in one of the GNAT library routines. These variables must
7886 be set from the actual @code{argc} and @code{argv} values passed to the
7887 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7888 generates the C main program to automatically set these variables.
7889 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7890 set these variables. If they are not set, the procedures in
7891 @code{Ada.Command_Line} will not be available, and any attempt to use
7892 them will raise @code{Constraint_Error}. If command line access is
7893 required, your main program must set @code{gnat_argc} and
7894 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7895 it.
7896
7897 @node Search Paths for gnatbind
7898 @section Search Paths for @code{gnatbind}
7899
7900 @noindent
7901 The binder takes the name of an ALI file as its argument and needs to
7902 locate source files as well as other ALI files to verify object consistency.
7903
7904 For source files, it follows exactly the same search rules as @command{gcc}
7905 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7906 directories searched are:
7907
7908 @enumerate
7909 @item
7910 The directory containing the ALI file named in the command line, unless
7911 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7912
7913 @item
7914 All directories specified by @option{^-I^/SEARCH^}
7915 switches on the @code{gnatbind}
7916 command line, in the order given.
7917
7918 @item
7919 @findex ADA_PRJ_OBJECTS_FILE
7920 Each of the directories listed in the text file whose name is given
7921 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7922
7923 @noindent
7924 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7925 driver when project files are used. It should not normally be set
7926 by other means.
7927
7928 @item
7929 @findex ADA_OBJECTS_PATH
7930 Each of the directories listed in the value of the
7931 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7932 @ifset unw
7933 Construct this value
7934 exactly as the @code{PATH} environment variable: a list of directory
7935 names separated by colons (semicolons when working with the NT version
7936 of GNAT).
7937 @end ifset
7938 @ifset vms
7939 Normally, define this value as a logical name containing a comma separated
7940 list of directory names.
7941
7942 This variable can also be defined by means of an environment string
7943 (an argument to the HP C exec* set of functions).
7944
7945 Logical Name:
7946 @smallexample
7947 DEFINE ANOTHER_PATH FOO:[BAG]
7948 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7949 @end smallexample
7950
7951 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7952 first, followed by the standard Ada 95
7953 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7954 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7955 (Text_IO, Sequential_IO, etc)
7956 instead of the Ada95 packages. Thus, in order to get the Ada 95
7957 packages by default, ADA_OBJECTS_PATH must be redefined.
7958 @end ifset
7959
7960 @item
7961 The content of the @file{ada_object_path} file which is part of the GNAT
7962 installation tree and is used to store standard libraries such as the
7963 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7964 specified.
7965 @ifclear vms
7966 @ref{Installing a library}
7967 @end ifclear
7968 @end enumerate
7969
7970 @noindent
7971 In the binder the switch @option{^-I^/SEARCH^}
7972 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7973 is used to specify both source and
7974 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7975 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7976 instead if you want to specify
7977 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7978 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7979 if you want to specify library paths
7980 only. This means that for the binder
7981 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7982 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7983 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7984 The binder generates the bind file (a C language source file) in the
7985 current working directory.
7986
7987 @findex Ada
7988 @findex System
7989 @findex Interfaces
7990 @findex GNAT
7991 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7992 children make up the GNAT Run-Time Library, together with the package
7993 GNAT and its children, which contain a set of useful additional
7994 library functions provided by GNAT. The sources for these units are
7995 needed by the compiler and are kept together in one directory. The ALI
7996 files and object files generated by compiling the RTL are needed by the
7997 binder and the linker and are kept together in one directory, typically
7998 different from the directory containing the sources. In a normal
7999 installation, you need not specify these directory names when compiling
8000 or binding. Either the environment variables or the built-in defaults
8001 cause these files to be found.
8002
8003 Besides simplifying access to the RTL, a major use of search paths is
8004 in compiling sources from multiple directories. This can make
8005 development environments much more flexible.
8006
8007 @node Examples of gnatbind Usage
8008 @section Examples of @code{gnatbind} Usage
8009
8010 @noindent
8011 This section contains a number of examples of using the GNAT binding
8012 utility @code{gnatbind}.
8013
8014 @table @code
8015 @item gnatbind hello
8016 The main program @code{Hello} (source program in @file{hello.adb}) is
8017 bound using the standard switch settings. The generated main program is
8018 @file{b~hello.adb}. This is the normal, default use of the binder.
8019
8020 @ifclear vms
8021 @item gnatbind hello -o mainprog.adb
8022 @end ifclear
8023 @ifset vms
8024 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8025 @end ifset
8026 The main program @code{Hello} (source program in @file{hello.adb}) is
8027 bound using the standard switch settings. The generated main program is
8028 @file{mainprog.adb} with the associated spec in
8029 @file{mainprog.ads}. Note that you must specify the body here not the
8030 spec, in the case where the output is in Ada. Note that if this option
8031 is used, then linking must be done manually, since gnatlink will not
8032 be able to find the generated file.
8033
8034 @ifclear vms
8035 @item gnatbind main -C -o mainprog.c -x
8036 @end ifclear
8037 @ifset vms
8038 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8039 @end ifset
8040 The main program @code{Main} (source program in
8041 @file{main.adb}) is bound, excluding source files from the
8042 consistency checking, generating
8043 the file @file{mainprog.c}.
8044
8045 @ifclear vms
8046 @item gnatbind -x main_program -C -o mainprog.c
8047 This command is exactly the same as the previous example. Switches may
8048 appear anywhere in the command line, and single letter switches may be
8049 combined into a single switch.
8050 @end ifclear
8051
8052 @ifclear vms
8053 @item gnatbind -n math dbase -C -o ada-control.c
8054 @end ifclear
8055 @ifset vms
8056 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8057 @end ifset
8058 The main program is in a language other than Ada, but calls to
8059 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8060 to @code{gnatbind} generates the file @file{ada-control.c} containing
8061 the @code{adainit} and @code{adafinal} routines to be called before and
8062 after accessing the Ada units.
8063 @end table
8064
8065 @c ------------------------------------
8066 @node Linking Using gnatlink
8067 @chapter Linking Using @command{gnatlink}
8068 @c ------------------------------------
8069 @findex gnatlink
8070
8071 @noindent
8072 This chapter discusses @command{gnatlink}, a tool that links
8073 an Ada program and builds an executable file. This utility
8074 invokes the system linker ^(via the @command{gcc} command)^^
8075 with a correct list of object files and library references.
8076 @command{gnatlink} automatically determines the list of files and
8077 references for the Ada part of a program. It uses the binder file
8078 generated by the @command{gnatbind} to determine this list.
8079
8080 @menu
8081 * Running gnatlink::
8082 * Switches for gnatlink::
8083 @end menu
8084
8085 @node Running gnatlink
8086 @section Running @command{gnatlink}
8087
8088 @noindent
8089 The form of the @command{gnatlink} command is
8090
8091 @smallexample
8092 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8093            [@var{non-Ada objects}] [@var{linker options}]
8094 @end smallexample
8095
8096 @noindent
8097 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8098 non-Ada objects
8099 or linker options) may be in any order, provided that no non-Ada object may
8100 be mistaken for a main @file{ALI} file.
8101 Any file name @file{F} without the @file{.ali}
8102 extension will be taken as the main @file{ALI} file if a file exists
8103 whose name is the concatenation of @file{F} and @file{.ali}.
8104
8105 @noindent
8106 @file{@var{mainprog}.ali} references the ALI file of the main program.
8107 The @file{.ali} extension of this file can be omitted. From this
8108 reference, @command{gnatlink} locates the corresponding binder file
8109 @file{b~@var{mainprog}.adb} and, using the information in this file along
8110 with the list of non-Ada objects and linker options, constructs a
8111 linker command file to create the executable.
8112
8113 The arguments other than the @command{gnatlink} switches and the main
8114 @file{ALI} file are passed to the linker uninterpreted.
8115 They typically include the names of
8116 object files for units written in other languages than Ada and any library
8117 references required to resolve references in any of these foreign language
8118 units, or in @code{Import} pragmas in any Ada units.
8119
8120 @var{linker options} is an optional list of linker specific
8121 switches.
8122 The default linker called by gnatlink is @var{gcc} which in
8123 turn calls the appropriate system linker.
8124 Standard options for the linker such as @option{-lmy_lib} or
8125 @option{-Ldir} can be added as is.
8126 For options that are not recognized by
8127 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
8128 @option{-Wl,}.
8129 Refer to the GCC documentation for
8130 details. Here is an example showing how to generate a linker map:
8131
8132 @smallexample
8133 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8134 @end smallexample
8135
8136 Using @var{linker options} it is possible to set the program stack and
8137 heap size.
8138 @ifclear vms
8139 See @ref{Setting Stack Size from gnatlink} and
8140 @ref{Setting Heap Size from gnatlink}.
8141 @end ifclear
8142
8143 @command{gnatlink} determines the list of objects required by the Ada
8144 program and prepends them to the list of objects passed to the linker.
8145 @command{gnatlink} also gathers any arguments set by the use of
8146 @code{pragma Linker_Options} and adds them to the list of arguments
8147 presented to the linker.
8148
8149 @ifset vms
8150 @command{gnatlink} accepts the following types of extra files on the command
8151 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
8152 options files (.OPT). These are recognized and handled according to their
8153 extension.
8154 @end ifset
8155
8156 @node Switches for gnatlink
8157 @section Switches for @command{gnatlink}
8158
8159 @noindent
8160 The following switches are available with the @command{gnatlink} utility:
8161
8162 @table @option
8163 @c !sort!
8164
8165 @item ^-A^/BIND_FILE=ADA^
8166 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8167 The binder has generated code in Ada. This is the default.
8168
8169 @item ^-C^/BIND_FILE=C^
8170 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8171 If instead of generating a file in Ada, the binder has generated one in
8172 C, then the linker needs to know about it. Use this switch to signal
8173 to @command{gnatlink} that the binder has generated C code rather than
8174 Ada code.
8175
8176 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8177 @cindex Command line length
8178 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8179 On some targets, the command line length is limited, and @command{gnatlink}
8180 will generate a separate file for the linker if the list of object files
8181 is too long.
8182 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8183 to be generated even if
8184 the limit is not exceeded. This is useful in some cases to deal with
8185 special situations where the command line length is exceeded.
8186
8187 @item ^-g^/DEBUG^
8188 @cindex Debugging information, including
8189 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8190 The option to include debugging information causes the Ada bind file (in
8191 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8192 @option{^-g^/DEBUG^}.
8193 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8194 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8195 Without @option{^-g^/DEBUG^}, the binder removes these files by
8196 default. The same procedure apply if a C bind file was generated using
8197 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8198 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8199
8200 @item ^-n^/NOCOMPILE^
8201 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8202 Do not compile the file generated by the binder. This may be used when
8203 a link is rerun with different options, but there is no need to recompile
8204 the binder file.
8205
8206 @item ^-v^/VERBOSE^
8207 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8208 Causes additional information to be output, including a full list of the
8209 included object files. This switch option is most useful when you want
8210 to see what set of object files are being used in the link step.
8211
8212 @item ^-v -v^/VERBOSE/VERBOSE^
8213 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8214 Very verbose mode. Requests that the compiler operate in verbose mode when
8215 it compiles the binder file, and that the system linker run in verbose mode.
8216
8217 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8218 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8219 @var{exec-name} specifies an alternate name for the generated
8220 executable program. If this switch is omitted, the executable has the same
8221 name as the main unit. For example, @code{gnatlink try.ali} creates
8222 an executable called @file{^try^TRY.EXE^}.
8223
8224 @ifclear vms
8225 @item -b @var{target}
8226 @cindex @option{-b} (@command{gnatlink})
8227 Compile your program to run on @var{target}, which is the name of a
8228 system configuration. You must have a GNAT cross-compiler built if
8229 @var{target} is not the same as your host system.
8230
8231 @item -B@var{dir}
8232 @cindex @option{-B} (@command{gnatlink})
8233 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8234 from @var{dir} instead of the default location. Only use this switch
8235 when multiple versions of the GNAT compiler are available. See the
8236 @command{gcc} manual page for further details. You would normally use the
8237 @option{-b} or @option{-V} switch instead.
8238
8239 @item --GCC=@var{compiler_name}
8240 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8241 Program used for compiling the binder file. The default is
8242 @command{gcc}. You need to use quotes around @var{compiler_name} if
8243 @code{compiler_name} contains spaces or other separator characters.
8244 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8245 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8246 inserted after your command name. Thus in the above example the compiler
8247 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8248 A limitation of this syntax is that the name and path name of the executable
8249 itself must not include any embedded spaces. If several
8250 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8251 is taken into account. However, all the additional switches are also taken
8252 into account. Thus,
8253 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8254 @option{--GCC="bar -x -y -z -t"}.
8255
8256 @item --LINK=@var{name}
8257 @cindex @option{--LINK=} (@command{gnatlink})
8258 @var{name} is the name of the linker to be invoked. This is especially
8259 useful in mixed language programs since languages such as C++ require
8260 their own linker to be used. When this switch is omitted, the default
8261 name for the linker is @command{gcc}. When this switch is used, the
8262 specified linker is called instead of @command{gcc} with exactly the same
8263 parameters that would have been passed to @command{gcc} so if the desired
8264 linker requires different parameters it is necessary to use a wrapper
8265 script that massages the parameters before invoking the real linker. It
8266 may be useful to control the exact invocation by using the verbose
8267 switch.
8268
8269 @end ifclear
8270
8271 @ifset vms
8272 @item /DEBUG=TRACEBACK
8273 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8274 This qualifier causes sufficient information to be included in the
8275 executable file to allow a traceback, but does not include the full
8276 symbol information needed by the debugger.
8277
8278 @item /IDENTIFICATION="<string>"
8279 @code{"<string>"} specifies the string to be stored in the image file
8280 identification field in the image header.
8281 It overrides any pragma @code{Ident} specified string.
8282
8283 @item /NOINHIBIT-EXEC
8284 Generate the executable file even if there are linker warnings.
8285
8286 @item /NOSTART_FILES
8287 Don't link in the object file containing the ``main'' transfer address.
8288 Used when linking with a foreign language main program compiled with an
8289 HP compiler.
8290
8291 @item /STATIC
8292 Prefer linking with object libraries over sharable images, even without
8293 /DEBUG.
8294 @end ifset
8295
8296 @end table
8297
8298 @node The GNAT Make Program gnatmake
8299 @chapter The GNAT Make Program @command{gnatmake}
8300 @findex gnatmake
8301
8302 @menu
8303 * Running gnatmake::
8304 * Switches for gnatmake::
8305 * Mode Switches for gnatmake::
8306 * Notes on the Command Line::
8307 * How gnatmake Works::
8308 * Examples of gnatmake Usage::
8309 @end menu
8310 @noindent
8311 A typical development cycle when working on an Ada program consists of
8312 the following steps:
8313
8314 @enumerate
8315 @item
8316 Edit some sources to fix bugs.
8317
8318 @item
8319 Add enhancements.
8320
8321 @item
8322 Compile all sources affected.
8323
8324 @item
8325 Rebind and relink.
8326
8327 @item
8328 Test.
8329 @end enumerate
8330
8331 @noindent
8332 The third step can be tricky, because not only do the modified files
8333 @cindex Dependency rules
8334 have to be compiled, but any files depending on these files must also be
8335 recompiled. The dependency rules in Ada can be quite complex, especially
8336 in the presence of overloading, @code{use} clauses, generics and inlined
8337 subprograms.
8338
8339 @command{gnatmake} automatically takes care of the third and fourth steps
8340 of this process. It determines which sources need to be compiled,
8341 compiles them, and binds and links the resulting object files.
8342
8343 Unlike some other Ada make programs, the dependencies are always
8344 accurately recomputed from the new sources. The source based approach of
8345 the GNAT compilation model makes this possible. This means that if
8346 changes to the source program cause corresponding changes in
8347 dependencies, they will always be tracked exactly correctly by
8348 @command{gnatmake}.
8349
8350 @node Running gnatmake
8351 @section Running @command{gnatmake}
8352
8353 @noindent
8354 The usual form of the @command{gnatmake} command is
8355
8356 @smallexample
8357 $ gnatmake [@var{switches}] @var{file_name}
8358       [@var{file_names}] [@var{mode_switches}]
8359 @end smallexample
8360
8361 @noindent
8362 The only required argument is one @var{file_name}, which specifies
8363 a compilation unit that is a main program. Several @var{file_names} can be
8364 specified: this will result in several executables being built.
8365 If @code{switches} are present, they can be placed before the first
8366 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8367 If @var{mode_switches} are present, they must always be placed after
8368 the last @var{file_name} and all @code{switches}.
8369
8370 If you are using standard file extensions (.adb and .ads), then the
8371 extension may be omitted from the @var{file_name} arguments. However, if
8372 you are using non-standard extensions, then it is required that the
8373 extension be given. A relative or absolute directory path can be
8374 specified in a @var{file_name}, in which case, the input source file will
8375 be searched for in the specified directory only. Otherwise, the input
8376 source file will first be searched in the directory where
8377 @command{gnatmake} was invoked and if it is not found, it will be search on
8378 the source path of the compiler as described in
8379 @ref{Search Paths and the Run-Time Library (RTL)}.
8380
8381 All @command{gnatmake} output (except when you specify
8382 @option{^-M^/DEPENDENCIES_LIST^}) is to
8383 @file{stderr}. The output produced by the
8384 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8385 @file{stdout}.
8386
8387 @node Switches for gnatmake
8388 @section Switches for @command{gnatmake}
8389
8390 @noindent
8391 You may specify any of the following switches to @command{gnatmake}:
8392
8393 @table @option
8394 @c !sort!
8395 @ifclear vms
8396 @item --GCC=@var{compiler_name}
8397 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8398 Program used for compiling. The default is `@command{gcc}'. You need to use
8399 quotes around @var{compiler_name} if @code{compiler_name} contains
8400 spaces or other separator characters. As an example @option{--GCC="foo -x
8401 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8402 compiler. A limitation of this syntax is that the name and path name of
8403 the executable itself must not include any embedded spaces. Note that
8404 switch @option{-c} is always inserted after your command name. Thus in the
8405 above example the compiler command that will be used by @command{gnatmake}
8406 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8407 used, only the last @var{compiler_name} is taken into account. However,
8408 all the additional switches are also taken into account. Thus,
8409 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8410 @option{--GCC="bar -x -y -z -t"}.
8411
8412 @item --GNATBIND=@var{binder_name}
8413 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8414 Program used for binding. The default is `@code{gnatbind}'. You need to
8415 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8416 or other separator characters. As an example @option{--GNATBIND="bar -x
8417 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8418 binder. Binder switches that are normally appended by @command{gnatmake}
8419 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8420 A limitation of this syntax is that the name and path name of the executable
8421 itself must not include any embedded spaces.
8422
8423 @item --GNATLINK=@var{linker_name}
8424 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8425 Program used for linking. The default is `@command{gnatlink}'. You need to
8426 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8427 or other separator characters. As an example @option{--GNATLINK="lan -x
8428 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8429 linker. Linker switches that are normally appended by @command{gnatmake} to
8430 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8431 A limitation of this syntax is that the name and path name of the executable
8432 itself must not include any embedded spaces.
8433
8434 @end ifclear
8435
8436 @item ^-a^/ALL_FILES^
8437 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8438 Consider all files in the make process, even the GNAT internal system
8439 files (for example, the predefined Ada library files), as well as any
8440 locked files. Locked files are files whose ALI file is write-protected.
8441 By default,
8442 @command{gnatmake} does not check these files,
8443 because the assumption is that the GNAT internal files are properly up
8444 to date, and also that any write protected ALI files have been properly
8445 installed. Note that if there is an installation problem, such that one
8446 of these files is not up to date, it will be properly caught by the
8447 binder.
8448 You may have to specify this switch if you are working on GNAT
8449 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8450 in conjunction with @option{^-f^/FORCE_COMPILE^}
8451 if you need to recompile an entire application,
8452 including run-time files, using special configuration pragmas,
8453 such as a @code{Normalize_Scalars} pragma.
8454
8455 By default
8456 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8457 internal files with
8458 @ifclear vms
8459 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8460 @end ifclear
8461 @ifset vms
8462 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8463 @end ifset
8464
8465 @item ^-b^/ACTIONS=BIND^
8466 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8467 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8468 compilation and binding, but no link.
8469 Can be combined with @option{^-l^/ACTIONS=LINK^}
8470 to do binding and linking. When not combined with
8471 @option{^-c^/ACTIONS=COMPILE^}
8472 all the units in the closure of the main program must have been previously
8473 compiled and must be up to date. The root unit specified by @var{file_name}
8474 may be given without extension, with the source extension or, if no GNAT
8475 Project File is specified, with the ALI file extension.
8476
8477 @item ^-c^/ACTIONS=COMPILE^
8478 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8479 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8480 is also specified. Do not perform linking, except if both
8481 @option{^-b^/ACTIONS=BIND^} and
8482  @option{^-l^/ACTIONS=LINK^} are also specified.
8483 If the root unit specified by @var{file_name} is not a main unit, this is the
8484 default. Otherwise @command{gnatmake} will attempt binding and linking
8485 unless all objects are up to date and the executable is more recent than
8486 the objects.
8487
8488 @item ^-C^/MAPPING^
8489 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8490 Use a temporary mapping file. A mapping file is a way to communicate to the
8491 compiler two mappings: from unit names to file names (without any directory
8492 information) and from file names to path names (with full directory
8493 information). These mappings are used by the compiler to short-circuit the path
8494 search. When @command{gnatmake} is invoked with this switch, it will create
8495 a temporary mapping file, initially populated by the project manager,
8496 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8497 Each invocation of the compiler will add the newly accessed sources to the
8498 mapping file. This will improve the source search during the next invocation
8499 of the compiler.
8500
8501 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8502 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8503 Use a specific mapping file. The file, specified as a path name (absolute or
8504 relative) by this switch, should already exist, otherwise the switch is
8505 ineffective. The specified mapping file will be communicated to the compiler.
8506 This switch is not compatible with a project file
8507 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8508 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8509
8510 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8511 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8512 Put all object files and ALI file in directory @var{dir}.
8513 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8514 and ALI files go in the current working directory.
8515
8516 This switch cannot be used when using a project file.
8517
8518 @ifclear vms
8519 @item -eL
8520 @cindex @option{-eL} (@command{gnatmake})
8521 Follow all symbolic links when processing project files.
8522 @end ifclear
8523
8524 @item ^-f^/FORCE_COMPILE^
8525 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8526 Force recompilations. Recompile all sources, even though some object
8527 files may be up to date, but don't recompile predefined or GNAT internal
8528 files or locked files (files with a write-protected ALI file),
8529 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8530
8531 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8532 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8533 When using project files, if some errors or warnings are detected during
8534 parsing and verbose mode is not in effect (no use of switch
8535 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8536 file, rather than its simple file name.
8537
8538 @item ^-i^/IN_PLACE^
8539 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8540 In normal mode, @command{gnatmake} compiles all object files and ALI files
8541 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8542 then instead object files and ALI files that already exist are overwritten
8543 in place. This means that once a large project is organized into separate
8544 directories in the desired manner, then @command{gnatmake} will automatically
8545 maintain and update this organization. If no ALI files are found on the
8546 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8547 the new object and ALI files are created in the
8548 directory containing the source being compiled. If another organization
8549 is desired, where objects and sources are kept in different directories,
8550 a useful technique is to create dummy ALI files in the desired directories.
8551 When detecting such a dummy file, @command{gnatmake} will be forced to
8552 recompile the corresponding source file, and it will be put the resulting
8553 object and ALI files in the directory where it found the dummy file.
8554
8555 @item ^-j^/PROCESSES=^@var{n}
8556 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8557 @cindex Parallel make
8558 Use @var{n} processes to carry out the (re)compilations. On a
8559 multiprocessor machine compilations will occur in parallel. In the
8560 event of compilation errors, messages from various compilations might
8561 get interspersed (but @command{gnatmake} will give you the full ordered
8562 list of failing compiles at the end). If this is problematic, rerun
8563 the make process with n set to 1 to get a clean list of messages.
8564
8565 @item ^-k^/CONTINUE_ON_ERROR^
8566 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8567 Keep going. Continue as much as possible after a compilation error. To
8568 ease the programmer's task in case of compilation errors, the list of
8569 sources for which the compile fails is given when @command{gnatmake}
8570 terminates.
8571
8572 If @command{gnatmake} is invoked with several @file{file_names} and with this
8573 switch, if there are compilation errors when building an executable,
8574 @command{gnatmake} will not attempt to build the following executables.
8575
8576 @item ^-l^/ACTIONS=LINK^
8577 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8578 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8579 and linking. Linking will not be performed if combined with
8580 @option{^-c^/ACTIONS=COMPILE^}
8581 but not with @option{^-b^/ACTIONS=BIND^}.
8582 When not combined with @option{^-b^/ACTIONS=BIND^}
8583 all the units in the closure of the main program must have been previously
8584 compiled and must be up to date, and the main program needs to have been bound.
8585 The root unit specified by @var{file_name}
8586 may be given without extension, with the source extension or, if no GNAT
8587 Project File is specified, with the ALI file extension.
8588
8589 @item ^-m^/MINIMAL_RECOMPILATION^
8590 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8591 Specify that the minimum necessary amount of recompilations
8592 be performed. In this mode @command{gnatmake} ignores time
8593 stamp differences when the only
8594 modifications to a source file consist in adding/removing comments,
8595 empty lines, spaces or tabs. This means that if you have changed the
8596 comments in a source file or have simply reformatted it, using this
8597 switch will tell gnatmake not to recompile files that depend on it
8598 (provided other sources on which these files depend have undergone no
8599 semantic modifications). Note that the debugging information may be
8600 out of date with respect to the sources if the @option{-m} switch causes
8601 a compilation to be switched, so the use of this switch represents a
8602 trade-off between compilation time and accurate debugging information.
8603
8604 @item ^-M^/DEPENDENCIES_LIST^
8605 @cindex Dependencies, producing list
8606 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8607 Check if all objects are up to date. If they are, output the object
8608 dependences to @file{stdout} in a form that can be directly exploited in
8609 a @file{Makefile}. By default, each source file is prefixed with its
8610 (relative or absolute) directory name. This name is whatever you
8611 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8612 and @option{^-I^/SEARCH^} switches. If you use
8613 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8614 @option{^-q^/QUIET^}
8615 (see below), only the source file names,
8616 without relative paths, are output. If you just specify the
8617 @option{^-M^/DEPENDENCIES_LIST^}
8618 switch, dependencies of the GNAT internal system files are omitted. This
8619 is typically what you want. If you also specify
8620 the @option{^-a^/ALL_FILES^} switch,
8621 dependencies of the GNAT internal files are also listed. Note that
8622 dependencies of the objects in external Ada libraries (see switch
8623 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8624 are never reported.
8625
8626 @item ^-n^/DO_OBJECT_CHECK^
8627 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8628 Don't compile, bind, or link. Checks if all objects are up to date.
8629 If they are not, the full name of the first file that needs to be
8630 recompiled is printed.
8631 Repeated use of this option, followed by compiling the indicated source
8632 file, will eventually result in recompiling all required units.
8633
8634 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8635 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8636 Output executable name. The name of the final executable program will be
8637 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8638 name for the executable will be the name of the input file in appropriate form
8639 for an executable file on the host system.
8640
8641 This switch cannot be used when invoking @command{gnatmake} with several
8642 @file{file_names}.
8643
8644 @item ^-P^/PROJECT_FILE=^@var{project}
8645 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8646 Use project file @var{project}. Only one such switch can be used.
8647 @xref{gnatmake and Project Files}.
8648
8649 @item ^-q^/QUIET^
8650 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8651 Quiet. When this flag is not set, the commands carried out by
8652 @command{gnatmake} are displayed.
8653
8654 @item ^-s^/SWITCH_CHECK/^
8655 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8656 Recompile if compiler switches have changed since last compilation.
8657 All compiler switches but -I and -o are taken into account in the
8658 following way:
8659 orders between different ``first letter'' switches are ignored, but
8660 orders between same switches are taken into account. For example,
8661 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8662 is equivalent to @option{-O -g}.
8663
8664 This switch is recommended when Integrated Preprocessing is used.
8665
8666 @item ^-u^/UNIQUE^
8667 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8668 Unique. Recompile at most the main files. It implies -c. Combined with
8669 -f, it is equivalent to calling the compiler directly. Note that using
8670 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8671 (@pxref{Project Files and Main Subprograms}).
8672
8673 @item ^-U^/ALL_PROJECTS^
8674 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8675 When used without a project file or with one or several mains on the command
8676 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8677 on the command line, all sources of all project files are checked and compiled
8678 if not up to date, and libraries are rebuilt, if necessary.
8679
8680 @item ^-v^/REASONS^
8681 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8682 Verbose. Display the reason for all recompilations @command{gnatmake}
8683 decides are necessary, with the highest verbosity level.
8684
8685 @item ^-vl^/LOW_VERBOSITY^
8686 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8687 Verbosity level Low. Display fewer lines than in verbosity Medium.
8688
8689 @item ^-vm^/MEDIUM_VERBOSITY^
8690 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8691 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8692
8693 @item ^-vh^/HIGH_VERBOSITY^
8694 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8695 Verbosity level High. Equivalent to ^-v^/REASONS^.
8696
8697 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8698 Indicate the verbosity of the parsing of GNAT project files.
8699 @xref{Switches Related to Project Files}.
8700
8701 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8702 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8703 Indicate that sources that are not part of any Project File may be compiled.
8704 Normally, when using Project Files, only sources that are part of a Project
8705 File may be compile. When this switch is used, a source outside of all Project
8706 Files may be compiled. The ALI file and the object file will be put in the
8707 object directory of the main Project. The compilation switches used will only
8708 be those specified on the command line.
8709
8710 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8711 Indicate that external variable @var{name} has the value @var{value}.
8712 The Project Manager will use this value for occurrences of
8713 @code{external(name)} when parsing the project file.
8714 @xref{Switches Related to Project Files}.
8715
8716 @item ^-z^/NOMAIN^
8717 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8718 No main subprogram. Bind and link the program even if the unit name
8719 given on the command line is a package name. The resulting executable
8720 will execute the elaboration routines of the package and its closure,
8721 then the finalization routines.
8722
8723 @item ^-g^/DEBUG^
8724 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8725 Enable debugging. This switch is simply passed to the compiler and to the
8726 linker.
8727
8728 @end table
8729
8730 @table @asis
8731 @item @command{gcc} @asis{switches}
8732 @ifclear vms
8733 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8734 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8735 @end ifclear
8736 @ifset vms
8737 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8738 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8739 automatically treated as a compiler switch, and passed on to all
8740 compilations that are carried out.
8741 @end ifset
8742 @end table
8743
8744 @noindent
8745 Source and library search path switches:
8746
8747 @table @option
8748 @c !sort!
8749 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8750 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8751 When looking for source files also look in directory @var{dir}.
8752 The order in which source files search is undertaken is
8753 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8754
8755 @item ^-aL^/SKIP_MISSING=^@var{dir}
8756 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8757 Consider @var{dir} as being an externally provided Ada library.
8758 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8759 files have been located in directory @var{dir}. This allows you to have
8760 missing bodies for the units in @var{dir} and to ignore out of date bodies
8761 for the same units. You still need to specify
8762 the location of the specs for these units by using the switches
8763 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8764 or @option{^-I^/SEARCH=^@var{dir}}.
8765 Note: this switch is provided for compatibility with previous versions
8766 of @command{gnatmake}. The easier method of causing standard libraries
8767 to be excluded from consideration is to write-protect the corresponding
8768 ALI files.
8769
8770 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8771 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8772 When searching for library and object files, look in directory
8773 @var{dir}. The order in which library files are searched is described in
8774 @ref{Search Paths for gnatbind}.
8775
8776 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8777 @cindex Search paths, for @command{gnatmake}
8778 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8779 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8780 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8781
8782 @item ^-I^/SEARCH=^@var{dir}
8783 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8784 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8785 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8786
8787 @item ^-I-^/NOCURRENT_DIRECTORY^
8788 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8789 @cindex Source files, suppressing search
8790 Do not look for source files in the directory containing the source
8791 file named in the command line.
8792 Do not look for ALI or object files in the directory
8793 where @command{gnatmake} was invoked.
8794
8795 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8796 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8797 @cindex Linker libraries
8798 Add directory @var{dir} to the list of directories in which the linker
8799 will search for libraries. This is equivalent to
8800 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8801 @ifclear vms
8802 Furthermore, under Windows, the sources pointed to by the libraries path
8803 set in the registry are not searched for.
8804 @end ifclear
8805
8806 @item -nostdinc
8807 @cindex @option{-nostdinc} (@command{gnatmake})
8808 Do not look for source files in the system default directory.
8809
8810 @item -nostdlib
8811 @cindex @option{-nostdlib} (@command{gnatmake})
8812 Do not look for library files in the system default directory.
8813
8814 @item --RTS=@var{rts-path}
8815 @cindex @option{--RTS} (@command{gnatmake})
8816 Specifies the default location of the runtime library. GNAT looks for the
8817 runtime
8818 in the following directories, and stops as soon as a valid runtime is found
8819 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8820 @file{ada_object_path} present):
8821
8822 @itemize @bullet
8823 @item <current directory>/$rts_path
8824
8825 @item <default-search-dir>/$rts_path
8826
8827 @item <default-search-dir>/rts-$rts_path
8828 @end itemize
8829
8830 @noindent
8831 The selected path is handled like a normal RTS path.
8832
8833 @end table
8834
8835 @node Mode Switches for gnatmake
8836 @section Mode Switches for @command{gnatmake}
8837
8838 @noindent
8839 The mode switches (referred to as @code{mode_switches}) allow the
8840 inclusion of switches that are to be passed to the compiler itself, the
8841 binder or the linker. The effect of a mode switch is to cause all
8842 subsequent switches up to the end of the switch list, or up to the next
8843 mode switch, to be interpreted as switches to be passed on to the
8844 designated component of GNAT.
8845
8846 @table @option
8847 @c !sort!
8848 @item -cargs @var{switches}
8849 @cindex @option{-cargs} (@command{gnatmake})
8850 Compiler switches. Here @var{switches} is a list of switches
8851 that are valid switches for @command{gcc}. They will be passed on to
8852 all compile steps performed by @command{gnatmake}.
8853
8854 @item -bargs @var{switches}
8855 @cindex @option{-bargs} (@command{gnatmake})
8856 Binder switches. Here @var{switches} is a list of switches
8857 that are valid switches for @code{gnatbind}. They will be passed on to
8858 all bind steps performed by @command{gnatmake}.
8859
8860 @item -largs @var{switches}
8861 @cindex @option{-largs} (@command{gnatmake})
8862 Linker switches. Here @var{switches} is a list of switches
8863 that are valid switches for @command{gnatlink}. They will be passed on to
8864 all link steps performed by @command{gnatmake}.
8865
8866 @item -margs @var{switches}
8867 @cindex @option{-margs} (@command{gnatmake})
8868 Make switches. The switches are directly interpreted by @command{gnatmake},
8869 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8870 or @option{-largs}.
8871 @end table
8872
8873 @node Notes on the Command Line
8874 @section Notes on the Command Line
8875
8876 @noindent
8877 This section contains some additional useful notes on the operation
8878 of the @command{gnatmake} command.
8879
8880 @itemize @bullet
8881 @item
8882 @cindex Recompilation, by @command{gnatmake}
8883 If @command{gnatmake} finds no ALI files, it recompiles the main program
8884 and all other units required by the main program.
8885 This means that @command{gnatmake}
8886 can be used for the initial compile, as well as during subsequent steps of
8887 the development cycle.
8888
8889 @item
8890 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8891 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8892 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8893 warning.
8894
8895 @item
8896 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8897 is used to specify both source and
8898 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8899 instead if you just want to specify
8900 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8901 if you want to specify library paths
8902 only.
8903
8904 @item
8905 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8906 This may conveniently be used to exclude standard libraries from
8907 consideration and in particular it means that the use of the
8908 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8909 unless @option{^-a^/ALL_FILES^} is also specified.
8910
8911 @item
8912 @command{gnatmake} has been designed to make the use of Ada libraries
8913 particularly convenient. Assume you have an Ada library organized
8914 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8915 of your Ada compilation units,
8916 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8917 specs of these units, but no bodies. Then to compile a unit
8918 stored in @code{main.adb}, which uses this Ada library you would just type
8919
8920 @smallexample
8921 @ifclear vms
8922 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8923 @end ifclear
8924 @ifset vms
8925 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8926            /SKIP_MISSING=@i{[OBJ_DIR]} main
8927 @end ifset
8928 @end smallexample
8929
8930 @item
8931 Using @command{gnatmake} along with the
8932 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8933 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8934 this switch,
8935 you can update the comments/format of your
8936 source files without having to recompile everything. Note, however, that
8937 adding or deleting lines in a source files may render its debugging
8938 info obsolete. If the file in question is a spec, the impact is rather
8939 limited, as that debugging info will only be useful during the
8940 elaboration phase of your program. For bodies the impact can be more
8941 significant. In all events, your debugger will warn you if a source file
8942 is more recent than the corresponding object, and alert you to the fact
8943 that the debugging information may be out of date.
8944 @end itemize
8945
8946 @node How gnatmake Works
8947 @section How @command{gnatmake} Works
8948
8949 @noindent
8950 Generally @command{gnatmake} automatically performs all necessary
8951 recompilations and you don't need to worry about how it works. However,
8952 it may be useful to have some basic understanding of the @command{gnatmake}
8953 approach and in particular to understand how it uses the results of
8954 previous compilations without incorrectly depending on them.
8955
8956 First a definition: an object file is considered @dfn{up to date} if the
8957 corresponding ALI file exists and if all the source files listed in the
8958 dependency section of this ALI file have time stamps matching those in
8959 the ALI file. This means that neither the source file itself nor any
8960 files that it depends on have been modified, and hence there is no need
8961 to recompile this file.
8962
8963 @command{gnatmake} works by first checking if the specified main unit is up
8964 to date. If so, no compilations are required for the main unit. If not,
8965 @command{gnatmake} compiles the main program to build a new ALI file that
8966 reflects the latest sources. Then the ALI file of the main unit is
8967 examined to find all the source files on which the main program depends,
8968 and @command{gnatmake} recursively applies the above procedure on all these
8969 files.
8970
8971 This process ensures that @command{gnatmake} only trusts the dependencies
8972 in an existing ALI file if they are known to be correct. Otherwise it
8973 always recompiles to determine a new, guaranteed accurate set of
8974 dependencies. As a result the program is compiled ``upside down'' from what may
8975 be more familiar as the required order of compilation in some other Ada
8976 systems. In particular, clients are compiled before the units on which
8977 they depend. The ability of GNAT to compile in any order is critical in
8978 allowing an order of compilation to be chosen that guarantees that
8979 @command{gnatmake} will recompute a correct set of new dependencies if
8980 necessary.
8981
8982 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8983 imported by several of the executables, it will be recompiled at most once.
8984
8985 Note: when using non-standard naming conventions
8986 (@pxref{Using Other File Names}), changing through a configuration pragmas
8987 file the version of a source and invoking @command{gnatmake} to recompile may
8988 have no effect, if the previous version of the source is still accessible
8989 by @command{gnatmake}. It may be necessary to use the switch
8990 ^-f^/FORCE_COMPILE^.
8991
8992 @node Examples of gnatmake Usage
8993 @section Examples of @command{gnatmake} Usage
8994
8995 @table @code
8996 @item gnatmake hello.adb
8997 Compile all files necessary to bind and link the main program
8998 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8999 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9000
9001 @item gnatmake main1 main2 main3
9002 Compile all files necessary to bind and link the main programs
9003 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9004 (containing unit @code{Main2}) and @file{main3.adb}
9005 (containing unit @code{Main3}) and bind and link the resulting object files
9006 to generate three executable files @file{^main1^MAIN1.EXE^},
9007 @file{^main2^MAIN2.EXE^}
9008 and @file{^main3^MAIN3.EXE^}.
9009
9010 @ifclear vms
9011 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9012 @end ifclear
9013
9014 @ifset vms
9015 @item gnatmake Main_Unit /QUIET
9016    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9017    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9018 @end ifset
9019 Compile all files necessary to bind and link the main program unit
9020 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9021 be done with optimization level 2 and the order of elaboration will be
9022 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9023 displaying commands it is executing.
9024 @end table
9025
9026 @c *************************
9027 @node Improving Performance
9028 @chapter Improving Performance
9029 @cindex Improving performance
9030
9031 @noindent
9032 This chapter presents several topics related to program performance.
9033 It first describes some of the tradeoffs that need to be considered
9034 and some of the techniques for making your program run faster.
9035 It then documents the @command{gnatelim} tool and unused subprogram/data
9036 elimination feature, which can reduce the size of program executables.
9037
9038 @ifnottex
9039 @menu
9040 * Performance Considerations::
9041 * Reducing Size of Ada Executables with gnatelim::
9042 * Reducing Size of Executables with unused subprogram/data elimination::
9043 @end menu
9044 @end ifnottex
9045
9046 @c *****************************
9047 @node Performance Considerations
9048 @section Performance Considerations
9049
9050 @noindent
9051 The GNAT system provides a number of options that allow a trade-off
9052 between
9053
9054 @itemize @bullet
9055 @item
9056 performance of the generated code
9057
9058 @item
9059 speed of compilation
9060
9061 @item
9062 minimization of dependences and recompilation
9063
9064 @item
9065 the degree of run-time checking.
9066 @end itemize
9067
9068 @noindent
9069 The defaults (if no options are selected) aim at improving the speed
9070 of compilation and minimizing dependences, at the expense of performance
9071 of the generated code:
9072
9073 @itemize @bullet
9074 @item
9075 no optimization
9076
9077 @item
9078 no inlining of subprogram calls
9079
9080 @item
9081 all run-time checks enabled except overflow and elaboration checks
9082 @end itemize
9083
9084 @noindent
9085 These options are suitable for most program development purposes. This
9086 chapter describes how you can modify these choices, and also provides
9087 some guidelines on debugging optimized code.
9088
9089 @menu
9090 * Controlling Run-Time Checks::
9091 * Use of Restrictions::
9092 * Optimization Levels::
9093 * Debugging Optimized Code::
9094 * Inlining of Subprograms::
9095 * Other Optimization Switches::
9096 * Optimization and Strict Aliasing::
9097
9098 @ifset vms
9099 * Coverage Analysis::
9100 @end ifset
9101 @end menu
9102
9103 @node Controlling Run-Time Checks
9104 @subsection Controlling Run-Time Checks
9105
9106 @noindent
9107 By default, GNAT generates all run-time checks, except arithmetic overflow
9108 checking for integer operations and checks for access before elaboration on
9109 subprogram calls. The latter are not required in default mode, because all
9110 necessary checking is done at compile time.
9111 @cindex @option{-gnatp} (@command{gcc})
9112 @cindex @option{-gnato} (@command{gcc})
9113 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9114 be modified. @xref{Run-Time Checks}.
9115
9116 Our experience is that the default is suitable for most development
9117 purposes.
9118
9119 We treat integer overflow specially because these
9120 are quite expensive and in our experience are not as important as other
9121 run-time checks in the development process. Note that division by zero
9122 is not considered an overflow check, and divide by zero checks are
9123 generated where required by default.
9124
9125 Elaboration checks are off by default, and also not needed by default, since
9126 GNAT uses a static elaboration analysis approach that avoids the need for
9127 run-time checking. This manual contains a full chapter discussing the issue
9128 of elaboration checks, and if the default is not satisfactory for your use,
9129 you should read this chapter.
9130
9131 For validity checks, the minimal checks required by the Ada Reference
9132 Manual (for case statements and assignments to array elements) are on
9133 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9134 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9135 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9136 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9137 are also suppressed entirely if @option{-gnatp} is used.
9138
9139 @cindex Overflow checks
9140 @cindex Checks, overflow
9141 @findex Suppress
9142 @findex Unsuppress
9143 @cindex pragma Suppress
9144 @cindex pragma Unsuppress
9145 Note that the setting of the switches controls the default setting of
9146 the checks. They may be modified using either @code{pragma Suppress} (to
9147 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9148 checks) in the program source.
9149
9150 @node Use of Restrictions
9151 @subsection Use of Restrictions
9152
9153 @noindent
9154 The use of pragma Restrictions allows you to control which features are
9155 permitted in your program. Apart from the obvious point that if you avoid
9156 relatively expensive features like finalization (enforceable by the use
9157 of pragma Restrictions (No_Finalization), the use of this pragma does not
9158 affect the generated code in most cases.
9159
9160 One notable exception to this rule is that the possibility of task abort
9161 results in some distributed overhead, particularly if finalization or
9162 exception handlers are used. The reason is that certain sections of code
9163 have to be marked as non-abortable.
9164
9165 If you use neither the @code{abort} statement, nor asynchronous transfer
9166 of control (@code{select .. then abort}), then this distributed overhead
9167 is removed, which may have a general positive effect in improving
9168 overall performance.  Especially code involving frequent use of tasking
9169 constructs and controlled types will show much improved performance.
9170 The relevant restrictions pragmas are
9171
9172 @smallexample @c ada
9173    pragma Restrictions (No_Abort_Statements);
9174    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9175 @end smallexample
9176
9177 @noindent
9178 It is recommended that these restriction pragmas be used if possible. Note
9179 that this also means that you can write code without worrying about the
9180 possibility of an immediate abort at any point.
9181
9182 @node Optimization Levels
9183 @subsection Optimization Levels
9184 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9185
9186 @noindent
9187 The default is optimization off. This results in the fastest compile
9188 times, but GNAT makes absolutely no attempt to optimize, and the
9189 generated programs are considerably larger and slower than when
9190 optimization is enabled. You can use the
9191 @ifclear vms
9192 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
9193 @end ifclear
9194 @ifset vms
9195 @code{OPTIMIZE} qualifier
9196 @end ifset
9197 to @command{gcc} to control the optimization level:
9198
9199 @table @option
9200 @item ^-O0^/OPTIMIZE=NONE^
9201 No optimization (the default);
9202 generates unoptimized code but has
9203 the fastest compilation time.
9204
9205 Note that many other compilers do fairly extensive optimization
9206 even if "no optimization" is specified. When using gcc, it is
9207 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9208 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9209 really does mean no optimization at all. This difference between
9210 gcc and other compilers should be kept in mind when doing
9211 performance comparisons.
9212
9213 @item ^-O1^/OPTIMIZE=SOME^
9214 Moderate optimization;
9215 optimizes reasonably well but does not
9216 degrade compilation time significantly.
9217
9218 @item ^-O2^/OPTIMIZE=ALL^
9219 @ifset vms
9220 @itemx /OPTIMIZE=DEVELOPMENT
9221 @end ifset
9222 Full optimization;
9223 generates highly optimized code and has
9224 the slowest compilation time.
9225
9226 @item ^-O3^/OPTIMIZE=INLINING^
9227 Full optimization as in @option{-O2},
9228 and also attempts automatic inlining of small
9229 subprograms within a unit (@pxref{Inlining of Subprograms}).
9230 @end table
9231
9232 @noindent
9233 Higher optimization levels perform more global transformations on the
9234 program and apply more expensive analysis algorithms in order to generate
9235 faster and more compact code. The price in compilation time, and the
9236 resulting improvement in execution time,
9237 both depend on the particular application and the hardware environment.
9238 You should experiment to find the best level for your application.
9239
9240 Since the precise set of optimizations done at each level will vary from
9241 release to release (and sometime from target to target), it is best to think
9242 of the optimization settings in general terms.
9243 The @cite{Using GNU GCC} manual contains details about
9244 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9245 individually enable or disable specific optimizations.
9246
9247 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9248 been tested extensively at all optimization levels. There are some bugs
9249 which appear only with optimization turned on, but there have also been
9250 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9251 level of optimization does not improve the reliability of the code
9252 generator, which in practice is highly reliable at all optimization
9253 levels.
9254
9255 Note regarding the use of @option{-O3}: The use of this optimization level
9256 is generally discouraged with GNAT, since it often results in larger
9257 executables which run more slowly. See further discussion of this point
9258 in @ref{Inlining of Subprograms}.
9259
9260 @node Debugging Optimized Code
9261 @subsection Debugging Optimized Code
9262 @cindex Debugging optimized code
9263 @cindex Optimization and debugging
9264
9265 @noindent
9266 Although it is possible to do a reasonable amount of debugging at
9267 @ifclear vms
9268 nonzero optimization levels,
9269 the higher the level the more likely that
9270 @end ifclear
9271 @ifset vms
9272 @option{/OPTIMIZE} settings other than @code{NONE},
9273 such settings will make it more likely that
9274 @end ifset
9275 source-level constructs will have been eliminated by optimization.
9276 For example, if a loop is strength-reduced, the loop
9277 control variable may be completely eliminated and thus cannot be
9278 displayed in the debugger.
9279 This can only happen at @option{-O2} or @option{-O3}.
9280 Explicit temporary variables that you code might be eliminated at
9281 ^level^setting^ @option{-O1} or higher.
9282
9283 The use of the @option{^-g^/DEBUG^} switch,
9284 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9285 which is needed for source-level debugging,
9286 affects the size of the program executable on disk,
9287 and indeed the debugging information can be quite large.
9288 However, it has no effect on the generated code (and thus does not
9289 degrade performance)
9290
9291 Since the compiler generates debugging tables for a compilation unit before
9292 it performs optimizations, the optimizing transformations may invalidate some
9293 of the debugging data.  You therefore need to anticipate certain
9294 anomalous situations that may arise while debugging optimized code.
9295 These are the most common cases:
9296
9297 @enumerate
9298 @item
9299 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9300 commands show
9301 the PC bouncing back and forth in the code.  This may result from any of
9302 the following optimizations:
9303
9304 @itemize @bullet
9305 @item
9306 @i{Common subexpression elimination:} using a single instance of code for a
9307 quantity that the source computes several times.  As a result you
9308 may not be able to stop on what looks like a statement.
9309
9310 @item
9311 @i{Invariant code motion:} moving an expression that does not change within a
9312 loop, to the beginning of the loop.
9313
9314 @item
9315 @i{Instruction scheduling:} moving instructions so as to
9316 overlap loads and stores (typically) with other code, or in
9317 general to move computations of values closer to their uses. Often
9318 this causes you to pass an assignment statement without the assignment
9319 happening and then later bounce back to the statement when the
9320 value is actually needed.  Placing a breakpoint on a line of code
9321 and then stepping over it may, therefore, not always cause all the
9322 expected side-effects.
9323 @end itemize
9324
9325 @item
9326 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9327 two identical pieces of code are merged and the program counter suddenly
9328 jumps to a statement that is not supposed to be executed, simply because
9329 it (and the code following) translates to the same thing as the code
9330 that @emph{was} supposed to be executed.  This effect is typically seen in
9331 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9332 a @code{break} in a C @code{^switch^switch^} statement.
9333
9334 @item
9335 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9336 There are various reasons for this effect:
9337
9338 @itemize @bullet
9339 @item
9340 In a subprogram prologue, a parameter may not yet have been moved to its
9341 ``home''.
9342
9343 @item
9344 A variable may be dead, and its register re-used.  This is
9345 probably the most common cause.
9346
9347 @item
9348 As mentioned above, the assignment of a value to a variable may
9349 have been moved.
9350
9351 @item
9352 A variable may be eliminated entirely by value propagation or
9353 other means.  In this case, GCC may incorrectly generate debugging
9354 information for the variable
9355 @end itemize
9356
9357 @noindent
9358 In general, when an unexpected value appears for a local variable or parameter
9359 you should first ascertain if that value was actually computed by
9360 your program, as opposed to being incorrectly reported by the debugger.
9361 Record fields or
9362 array elements in an object designated by an access value
9363 are generally less of a problem, once you have ascertained that the access
9364 value is sensible.
9365 Typically, this means checking variables in the preceding code and in the
9366 calling subprogram to verify that the value observed is explainable from other
9367 values (one must apply the procedure recursively to those
9368 other values); or re-running the code and stopping a little earlier
9369 (perhaps before the call) and stepping to better see how the variable obtained
9370 the value in question; or continuing to step @emph{from} the point of the
9371 strange value to see if code motion had simply moved the variable's
9372 assignments later.
9373 @end enumerate
9374
9375 @noindent
9376 In light of such anomalies, a recommended technique is to use @option{-O0}
9377 early in the software development cycle, when extensive debugging capabilities
9378 are most needed, and then move to @option{-O1} and later @option{-O2} as
9379 the debugger becomes less critical.
9380 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9381 a release management issue.
9382 @ifclear vms
9383 Note that if you use @option{-g} you can then use the @command{strip} program
9384 on the resulting executable,
9385 which removes both debugging information and global symbols.
9386 @end ifclear
9387
9388 @node Inlining of Subprograms
9389 @subsection Inlining of Subprograms
9390
9391 @noindent
9392 A call to a subprogram in the current unit is inlined if all the
9393 following conditions are met:
9394
9395 @itemize @bullet
9396 @item
9397 The optimization level is at least @option{-O1}.
9398
9399 @item
9400 The called subprogram is suitable for inlining: It must be small enough
9401 and not contain nested subprograms or anything else that @command{gcc}
9402 cannot support in inlined subprograms.
9403
9404 @item
9405 The call occurs after the definition of the body of the subprogram.
9406
9407 @item
9408 @cindex pragma Inline
9409 @findex Inline
9410 Either @code{pragma Inline} applies to the subprogram or it is
9411 small and automatic inlining (optimization level @option{-O3}) is
9412 specified.
9413 @end itemize
9414
9415 @noindent
9416 Calls to subprograms in @code{with}'ed units are normally not inlined.
9417 To achieve actual inlining (that is, replacement of the call by the code
9418 in the body of the subprogram), the following conditions must all be true.
9419
9420 @itemize @bullet
9421 @item
9422 The optimization level is at least @option{-O1}.
9423
9424 @item
9425 The called subprogram is suitable for inlining: It must be small enough
9426 and not contain nested subprograms or anything else @command{gcc} cannot
9427 support in inlined subprograms.
9428
9429 @item
9430 The call appears in a body (not in a package spec).
9431
9432 @item
9433 There is a @code{pragma Inline} for the subprogram.
9434
9435 @item
9436 @cindex @option{-gnatn} (@command{gcc})
9437 The @option{^-gnatn^/INLINE^} switch
9438 is used in the @command{gcc} command line
9439 @end itemize
9440
9441 Even if all these conditions are met, it may not be possible for
9442 the compiler to inline the call, due to the length of the body,
9443 or features in the body that make it impossible for the compiler
9444 to do the inlining.
9445
9446 Note that specifying the @option{-gnatn} switch causes additional
9447 compilation dependencies. Consider the following:
9448
9449 @smallexample @c ada
9450 @cartouche
9451 package R is
9452    procedure Q;
9453    pragma Inline (Q);
9454 end R;
9455 package body R is
9456    ...
9457 end R;
9458
9459 with R;
9460 procedure Main is
9461 begin
9462    ...
9463    R.Q;
9464 end Main;
9465 @end cartouche
9466 @end smallexample
9467
9468 @noindent
9469 With the default behavior (no @option{-gnatn} switch specified), the
9470 compilation of the @code{Main} procedure depends only on its own source,
9471 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9472 means that editing the body of @code{R} does not require recompiling
9473 @code{Main}.
9474
9475 On the other hand, the call @code{R.Q} is not inlined under these
9476 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9477 is compiled, the call will be inlined if the body of @code{Q} is small
9478 enough, but now @code{Main} depends on the body of @code{R} in
9479 @file{r.adb} as well as on the spec. This means that if this body is edited,
9480 the main program must be recompiled. Note that this extra dependency
9481 occurs whether or not the call is in fact inlined by @command{gcc}.
9482
9483 The use of front end inlining with @option{-gnatN} generates similar
9484 additional dependencies.
9485
9486 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9487 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9488 can be used to prevent
9489 all inlining. This switch overrides all other conditions and ensures
9490 that no inlining occurs. The extra dependences resulting from
9491 @option{-gnatn} will still be active, even if
9492 this switch is used to suppress the resulting inlining actions.
9493
9494 Note regarding the use of @option{-O3}: There is no difference in inlining
9495 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9496 pragma @code{Inline} assuming the use of @option{-gnatn}
9497 or @option{-gnatN} (the switches that activate inlining). If you have used
9498 pragma @code{Inline} in appropriate cases, then it is usually much better
9499 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9500 in this case only has the effect of inlining subprograms you did not
9501 think should be inlined. We often find that the use of @option{-O3} slows
9502 down code by performing excessive inlining, leading to increased instruction
9503 cache pressure from the increased code size. So the bottom line here is
9504 that you should not automatically assume that @option{-O3} is better than
9505 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9506 it actually improves performance.
9507
9508 @node Other Optimization Switches
9509 @subsection Other Optimization Switches
9510 @cindex Optimization Switches
9511
9512 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9513 @code{gcc} optimization switches are potentially usable. These switches
9514 have not been extensively tested with GNAT but can generally be expected
9515 to work. Examples of switches in this category are
9516 @option{-funroll-loops} and
9517 the various target-specific @option{-m} options (in particular, it has been
9518 observed that @option{-march=pentium4} can significantly improve performance
9519 on appropriate machines). For full details of these switches, see the
9520 @code{gcc} manual.
9521
9522 @node Optimization and Strict Aliasing
9523 @subsection Optimization and Strict Aliasing
9524 @cindex Aliasing
9525 @cindex Strict Aliasing
9526 @cindex No_Strict_Aliasing
9527
9528 @noindent
9529 The strong typing capabilities of Ada allow an optimizer to generate
9530 efficient code in situations where other languages would be forced to
9531 make worst case assumptions preventing such optimizations. Consider
9532 the following example:
9533
9534 @smallexample @c ada
9535 @cartouche
9536 procedure R is
9537    type Int1 is new Integer;
9538    type Int2 is new Integer;
9539    type Int1A is access Int1;
9540    type Int2A is access Int2;
9541    Int1V : Int1A;
9542    Int2V : Int2A;
9543    ...
9544
9545 begin
9546    ...
9547    for J in Data'Range loop
9548       if Data (J) = Int1V.all then
9549          Int2V.all := Int2V.all + 1;
9550       end if;
9551    end loop;
9552    ...
9553 end R;
9554 @end cartouche
9555 @end smallexample
9556
9557 @noindent
9558 In this example, since the variable @code{Int1V} can only access objects
9559 of type @code{Int1}, and @code{Int2V} can only access objects of type
9560 @code{Int2}, there is no possibility that the assignment to
9561 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9562 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9563 for all iterations of the loop and avoid the extra memory reference
9564 required to dereference it each time through the loop.
9565
9566 This kind of optimization, called strict aliasing analysis, is
9567 triggered by specifying an optimization level of @option{-O2} or
9568 higher and allows @code{GNAT} to generate more efficient code
9569 when access values are involved.
9570
9571 However, although this optimization is always correct in terms of
9572 the formal semantics of the Ada Reference Manual, difficulties can
9573 arise if features like @code{Unchecked_Conversion} are used to break
9574 the typing system. Consider the following complete program example:
9575
9576 @smallexample @c ada
9577 @cartouche
9578 package p1 is
9579    type int1 is new integer;
9580    type int2 is new integer;
9581    type a1 is access int1;
9582    type a2 is access int2;
9583 end p1;
9584
9585 with p1; use p1;
9586 package p2 is
9587    function to_a2 (Input : a1) return a2;
9588 end p2;
9589
9590 with Unchecked_Conversion;
9591 package body p2 is
9592    function to_a2 (Input : a1) return a2 is
9593       function to_a2u is
9594         new Unchecked_Conversion (a1, a2);
9595    begin
9596       return to_a2u (Input);
9597    end to_a2;
9598 end p2;
9599
9600 with p2; use p2;
9601 with p1; use p1;
9602 with Text_IO; use Text_IO;
9603 procedure m is
9604    v1 : a1 := new int1;
9605    v2 : a2 := to_a2 (v1);
9606 begin
9607    v1.all := 1;
9608    v2.all := 0;
9609    put_line (int1'image (v1.all));
9610 end;
9611 @end cartouche
9612 @end smallexample
9613
9614 @noindent
9615 This program prints out 0 in @code{-O0} or @code{-O1}
9616 mode, but it prints out 1 in @code{-O2} mode. That's
9617 because in strict aliasing mode, the compiler can and
9618 does assume that the assignment to @code{v2.all} could not
9619 affect the value of @code{v1.all}, since different types
9620 are involved.
9621
9622 This behavior is not a case of non-conformance with the standard, since
9623 the Ada RM specifies that an unchecked conversion where the resulting
9624 bit pattern is not a correct value of the target type can result in an
9625 abnormal value and attempting to reference an abnormal value makes the
9626 execution of a program erroneous.  That's the case here since the result
9627 does not point to an object of type @code{int2}.  This means that the
9628 effect is entirely unpredictable.
9629
9630 However, although that explanation may satisfy a language
9631 lawyer, in practice an applications programmer expects an
9632 unchecked conversion involving pointers to create true
9633 aliases and the behavior of printing 1 seems plain wrong.
9634 In this case, the strict aliasing optimization is unwelcome.
9635
9636 Indeed the compiler recognizes this possibility, and the
9637 unchecked conversion generates a warning:
9638
9639 @smallexample
9640 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9641 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9642 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9643 @end smallexample
9644
9645 @noindent
9646 Unfortunately the problem is recognized when compiling the body of
9647 package @code{p2}, but the actual "bad" code is generated while
9648 compiling the body of @code{m} and this latter compilation does not see
9649 the suspicious @code{Unchecked_Conversion}.
9650
9651 As implied by the warning message, there are approaches you can use to
9652 avoid the unwanted strict aliasing optimization in a case like this.
9653
9654 One possibility is to simply avoid the use of @code{-O2}, but
9655 that is a bit drastic, since it throws away a number of useful
9656 optimizations that do not involve strict aliasing assumptions.
9657
9658 A less drastic approach is to compile the program using the
9659 option @code{-fno-strict-aliasing}. Actually it is only the
9660 unit containing the dereferencing of the suspicious pointer
9661 that needs to be compiled. So in this case, if we compile
9662 unit @code{m} with this switch, then we get the expected
9663 value of zero printed. Analyzing which units might need
9664 the switch can be painful, so a more reasonable approach
9665 is to compile the entire program with options @code{-O2}
9666 and @code{-fno-strict-aliasing}. If the performance is
9667 satisfactory with this combination of options, then the
9668 advantage is that the entire issue of possible "wrong"
9669 optimization due to strict aliasing is avoided.
9670
9671 To avoid the use of compiler switches, the configuration
9672 pragma @code{No_Strict_Aliasing} with no parameters may be
9673 used to specify that for all access types, the strict
9674 aliasing optimization should be suppressed.
9675
9676 However, these approaches are still overkill, in that they causes
9677 all manipulations of all access values to be deoptimized. A more
9678 refined approach is to concentrate attention on the specific
9679 access type identified as problematic.
9680
9681 First, if a careful analysis of uses of the pointer shows
9682 that there are no possible problematic references, then
9683 the warning can be suppressed by bracketing the
9684 instantiation of @code{Unchecked_Conversion} to turn
9685 the warning off:
9686
9687 @smallexample @c ada
9688    pragma Warnings (Off);
9689    function to_a2u is
9690      new Unchecked_Conversion (a1, a2);
9691    pragma Warnings (On);
9692 @end smallexample
9693
9694 @noindent
9695 Of course that approach is not appropriate for this particular
9696 example, since indeed there is a problematic reference. In this
9697 case we can take one of two other approaches.
9698
9699 The first possibility is to move the instantiation of unchecked
9700 conversion to the unit in which the type is declared. In
9701 this example, we would move the instantiation of
9702 @code{Unchecked_Conversion} from the body of package
9703 @code{p2} to the spec of package @code{p1}. Now the
9704 warning disappears. That's because any use of the
9705 access type knows there is a suspicious unchecked
9706 conversion, and the strict aliasing optimization
9707 is automatically suppressed for the type.
9708
9709 If it is not practical to move the unchecked conversion to the same unit
9710 in which the destination access type is declared (perhaps because the
9711 source type is not visible in that unit), you may use pragma
9712 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9713 same declarative sequence as the declaration of the access type:
9714
9715 @smallexample @c ada
9716    type a2 is access int2;
9717    pragma No_Strict_Aliasing (a2);
9718 @end smallexample
9719
9720 @noindent
9721 Here again, the compiler now knows that the strict aliasing optimization
9722 should be suppressed for any reference to type @code{a2} and the
9723 expected behavior is obtained.
9724
9725 Finally, note that although the compiler can generate warnings for
9726 simple cases of unchecked conversions, there are tricker and more
9727 indirect ways of creating type incorrect aliases which the compiler
9728 cannot detect. Examples are the use of address overlays and unchecked
9729 conversions involving composite types containing access types as
9730 components. In such cases, no warnings are generated, but there can
9731 still be aliasing problems. One safe coding practice is to forbid the
9732 use of address clauses for type overlaying, and to allow unchecked
9733 conversion only for primitive types. This is not really a significant
9734 restriction since any possible desired effect can be achieved by
9735 unchecked conversion of access values.
9736
9737 @ifset vms
9738 @node Coverage Analysis
9739 @subsection Coverage Analysis
9740
9741 @noindent
9742 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
9743 the user to determine the distribution of execution time across a program,
9744 @pxref{Profiling} for details of usage.
9745 @end ifset
9746
9747 @node Reducing Size of Ada Executables with gnatelim
9748 @section Reducing Size of Ada Executables with @code{gnatelim}
9749 @findex gnatelim
9750
9751 @noindent
9752 This section describes @command{gnatelim}, a tool which detects unused
9753 subprograms and helps the compiler to create a smaller executable for your
9754 program.
9755
9756 @menu
9757 * About gnatelim::
9758 * Running gnatelim::
9759 * Correcting the List of Eliminate Pragmas::
9760 * Making Your Executables Smaller::
9761 * Summary of the gnatelim Usage Cycle::
9762 @end menu
9763
9764 @node About gnatelim
9765 @subsection About @code{gnatelim}
9766
9767 @noindent
9768 When a program shares a set of Ada
9769 packages with other programs, it may happen that this program uses
9770 only a fraction of the subprograms defined in these packages. The code
9771 created for these unused subprograms increases the size of the executable.
9772
9773 @code{gnatelim} tracks unused subprograms in an Ada program and
9774 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9775 subprograms that are declared but never called. By placing the list of
9776 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9777 recompiling your program, you may decrease the size of its executable,
9778 because the compiler will not generate the code for 'eliminated' subprograms.
9779 See GNAT Reference Manual for more information about this pragma.
9780
9781 @code{gnatelim} needs as its input data the name of the main subprogram
9782 and a bind file for a main subprogram.
9783
9784 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9785 the main subprogram. @code{gnatelim} can work with both Ada and C
9786 bind files; when both are present, it uses the Ada bind file.
9787 The following commands will build the program and create the bind file:
9788
9789 @smallexample
9790 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9791 $ gnatbind main_prog
9792 @end smallexample
9793
9794 Note that @code{gnatelim} needs neither object nor ALI files.
9795
9796 @node Running gnatelim
9797 @subsection Running @code{gnatelim}
9798
9799 @noindent
9800 @code{gnatelim} has the following command-line interface:
9801
9802 @smallexample
9803 $ gnatelim [options] name
9804 @end smallexample
9805
9806 @noindent
9807 @code{name} should be a name of a source file that contains the main subprogram
9808 of a program (partition).
9809
9810 @code{gnatelim} has the following switches:
9811
9812 @table @option
9813 @c !sort!
9814 @item ^-q^/QUIET^
9815 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9816 Quiet mode: by default @code{gnatelim} outputs to the standard error
9817 stream the number of program units left to be processed. This option turns
9818 this trace off.
9819
9820 @item ^-v^/VERBOSE^
9821 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9822 Verbose mode: @code{gnatelim} version information is printed as Ada
9823 comments to the standard output stream. Also, in addition to the number of
9824 program units left @code{gnatelim} will output the name of the current unit
9825 being processed.
9826
9827 @item ^-a^/ALL^
9828 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9829 Also look for subprograms from the GNAT run time that can be eliminated. Note
9830 that when @file{gnat.adc} is produced using this switch, the entire program
9831 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9832
9833 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9834 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9835 When looking for source files also look in directory @var{dir}. Specifying
9836 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9837 sources in the current directory.
9838
9839 @item ^-b^/BIND_FILE=^@var{bind_file}
9840 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9841 Specifies @var{bind_file} as the bind file to process. If not set, the name
9842 of the bind file is computed from the full expanded Ada name
9843 of a main subprogram.
9844
9845 @item ^-C^/CONFIG_FILE=^@var{config_file}
9846 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9847 Specifies a file @var{config_file} that contains configuration pragmas. The
9848 file must be specified with full path.
9849
9850 @item ^--GCC^/COMPILER^=@var{compiler_name}
9851 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9852 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9853 available on the path.
9854
9855 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9856 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9857 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9858 available on the path.
9859 @end table
9860
9861 @noindent
9862 @code{gnatelim} sends its output to the standard output stream, and all the
9863 tracing and debug information is sent to the standard error stream.
9864 In order to produce a proper GNAT configuration file
9865 @file{gnat.adc}, redirection must be used:
9866
9867 @smallexample
9868 @ifset vms
9869 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9870 @end ifset
9871 @ifclear vms
9872 $ gnatelim main_prog.adb > gnat.adc
9873 @end ifclear
9874 @end smallexample
9875
9876 @ifclear vms
9877 @noindent
9878 or
9879
9880 @smallexample
9881 $ gnatelim main_prog.adb >> gnat.adc
9882 @end smallexample
9883
9884 @noindent
9885 in order to append the @code{gnatelim} output to the existing contents of
9886 @file{gnat.adc}.
9887 @end ifclear
9888
9889 @node Correcting the List of Eliminate Pragmas
9890 @subsection Correcting the List of Eliminate Pragmas
9891
9892 @noindent
9893 In some rare cases @code{gnatelim} may try to eliminate
9894 subprograms that are actually called in the program. In this case, the
9895 compiler will generate an error message of the form:
9896
9897 @smallexample
9898 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9899 @end smallexample
9900
9901 @noindent
9902 You will need to manually remove the wrong @code{Eliminate} pragmas from
9903 the @file{gnat.adc} file. You should recompile your program
9904 from scratch after that, because you need a consistent @file{gnat.adc} file
9905 during the entire compilation.
9906
9907 @node Making Your Executables Smaller
9908 @subsection Making Your Executables Smaller
9909
9910 @noindent
9911 In order to get a smaller executable for your program you now have to
9912 recompile the program completely with the new @file{gnat.adc} file
9913 created by @code{gnatelim} in your current directory:
9914
9915 @smallexample
9916 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9917 @end smallexample
9918
9919 @noindent
9920 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9921 recompile everything
9922 with the set of pragmas @code{Eliminate} that you have obtained with
9923 @command{gnatelim}).
9924
9925 Be aware that the set of @code{Eliminate} pragmas is specific to each
9926 program. It is not recommended to merge sets of @code{Eliminate}
9927 pragmas created for different programs in one @file{gnat.adc} file.
9928
9929 @node Summary of the gnatelim Usage Cycle
9930 @subsection Summary of the gnatelim Usage Cycle
9931
9932 @noindent
9933 Here is a quick summary of the steps to be taken in order to reduce
9934 the size of your executables with @code{gnatelim}. You may use
9935 other GNAT options to control the optimization level,
9936 to produce the debugging information, to set search path, etc.
9937
9938 @enumerate
9939 @item
9940 Produce a bind file
9941
9942 @smallexample
9943 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9944 $ gnatbind main_prog
9945 @end smallexample
9946
9947 @item
9948 Generate a list of @code{Eliminate} pragmas
9949 @smallexample
9950 @ifset vms
9951 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9952 @end ifset
9953 @ifclear vms
9954 $ gnatelim main_prog >[>] gnat.adc
9955 @end ifclear
9956 @end smallexample
9957
9958 @item
9959 Recompile the application
9960
9961 @smallexample
9962 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9963 @end smallexample
9964
9965 @end enumerate
9966
9967 @node Reducing Size of Executables with unused subprogram/data elimination
9968 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
9969 @findex unused subprogram/data elimination
9970
9971 @noindent
9972 This section describes how you can eliminate unused subprograms and data from
9973 your executable just by setting options at compilation time.
9974
9975 @menu
9976 * About unused subprogram/data elimination::
9977 * Compilation options::
9978 * Example of unused subprogram/data elimination::
9979 @end menu
9980
9981 @node About unused subprogram/data elimination
9982 @subsection About unused subprogram/data elimination
9983
9984 @noindent
9985 By default, an executable contains all code and data of its composing objects
9986 (directly linked or coming from statically linked libraries), even data or code
9987 never used by this executable.
9988
9989 This feature will allow you to eliminate such unused code from your
9990 executable, making it smaller (in disk and in memory).
9991
9992 This functionality is available on all platforms using elf binary format and
9993 having GNU binutils version 2.16.1.
9994
9995 @node Compilation options
9996 @subsection Compilation options
9997
9998 @noindent
9999 The operation of eliminating the unused code and data from the final executable
10000 is directly performed by the linker.
10001
10002 In order to do this, it has to work with objects compiled with the
10003 following options:
10004 @option{-ffunction-sections} @option{-fdata-sections}.
10005 @cindex @option{-ffunction-sections} (@command{gcc})
10006 @cindex @option{-fdata-sections} (@command{gcc})
10007 These options are usable with C and Ada files.
10008 They will place respectively each
10009 function or data in a separate section in the resulting object file.
10010
10011 Once the objects and static libraries are created with these options, the
10012 linker can perform the dead code elimination. You can do this by setting
10013 the @option{-Wl,--gc-sections} option to gcc command or in the
10014 @option{-largs} section of gnatmake. This will perform a garbage collection of
10015 code and data never referenced.
10016
10017 If the linker performs a partial link (@option{-r} ld linker option), then you
10018 will need to provide one or several entry point using the
10019 @option{-e} / @option{--entry} ld option.
10020
10021 Note that objects compiled without the @option{-ffunction-sections} and
10022 @option{-fdata-sections} options can still be linked with the executable.
10023 However, no dead code elimination will be performed on those objects (they will
10024 be linked as is).
10025
10026 The GNAT static library is now compiled with -ffunction-sections and
10027 -fdata-sections on some platforms. This allows you to eliminate the unused code
10028 and data of the GNAT library from your executable.
10029
10030 @node Example of unused subprogram/data elimination
10031 @subsection Example of unused subprogram/data elimination
10032
10033 @noindent
10034 Here is a simple example:
10035
10036 @smallexample @c ada
10037 with Aux;
10038
10039 procedure Test is
10040 begin
10041    Aux.Used (10);
10042 end Test;
10043
10044 package Aux is
10045    Used_Data   : Integer;
10046    Unused_Data : Integer;
10047
10048    procedure Used   (Data : Integer);
10049    procedure Unused (Data : Integer);
10050 end Aux;
10051
10052 package body Aux is
10053    procedure Used (Data : Integer) is
10054    begin
10055       Used_Data := Data;
10056    end Used;
10057
10058    procedure Unused (Data : Integer) is
10059    begin
10060       Unused_Data := Data;
10061    end Unused;
10062 end Aux;
10063 @end smallexample
10064
10065 @noindent
10066 @code{Unused} and @code{Unused_Data} are never referenced in this code
10067 excerpt, and hence they may be safely removed from the final executable.
10068
10069 @smallexample
10070 $ gnatmake test
10071
10072 $ nm test | grep used
10073 020015f0 T aux__unused
10074 02005d88 B aux__unused_data
10075 020015cc T aux__used
10076 02005d84 B aux__used_data
10077
10078 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10079      -largs -Wl,--gc-sections
10080
10081 $ nm test | grep used
10082 02005350 T aux__used
10083 0201ffe0 B aux__used_data
10084 @end smallexample
10085
10086 @noindent
10087 It can be observed that the procedure @code{Unused} and the object
10088 @code{Unused_Data} are removed by the linker when using the
10089 appropriate options.
10090
10091 @c ********************************
10092 @node Renaming Files Using gnatchop
10093 @chapter Renaming Files Using @code{gnatchop}
10094 @findex gnatchop
10095
10096 @noindent
10097 This chapter discusses how to handle files with multiple units by using
10098 the @code{gnatchop} utility. This utility is also useful in renaming
10099 files to meet the standard GNAT default file naming conventions.
10100
10101 @menu
10102 * Handling Files with Multiple Units::
10103 * Operating gnatchop in Compilation Mode::
10104 * Command Line for gnatchop::
10105 * Switches for gnatchop::
10106 * Examples of gnatchop Usage::
10107 @end menu
10108
10109 @node Handling Files with Multiple Units
10110 @section Handling Files with Multiple Units
10111
10112 @noindent
10113 The basic compilation model of GNAT requires that a file submitted to the
10114 compiler have only one unit and there be a strict correspondence
10115 between the file name and the unit name.
10116
10117 The @code{gnatchop} utility allows both of these rules to be relaxed,
10118 allowing GNAT to process files which contain multiple compilation units
10119 and files with arbitrary file names. @code{gnatchop}
10120 reads the specified file and generates one or more output files,
10121 containing one unit per file. The unit and the file name correspond,
10122 as required by GNAT.
10123
10124 If you want to permanently restructure a set of ``foreign'' files so that
10125 they match the GNAT rules, and do the remaining development using the
10126 GNAT structure, you can simply use @command{gnatchop} once, generate the
10127 new set of files and work with them from that point on.
10128
10129 Alternatively, if you want to keep your files in the ``foreign'' format,
10130 perhaps to maintain compatibility with some other Ada compilation
10131 system, you can set up a procedure where you use @command{gnatchop} each
10132 time you compile, regarding the source files that it writes as temporary
10133 files that you throw away.
10134
10135 @node Operating gnatchop in Compilation Mode
10136 @section Operating gnatchop in Compilation Mode
10137
10138 @noindent
10139 The basic function of @code{gnatchop} is to take a file with multiple units
10140 and split it into separate files. The boundary between files is reasonably
10141 clear, except for the issue of comments and pragmas. In default mode, the
10142 rule is that any pragmas between units belong to the previous unit, except
10143 that configuration pragmas always belong to the following unit. Any comments
10144 belong to the following unit. These rules
10145 almost always result in the right choice of
10146 the split point without needing to mark it explicitly and most users will
10147 find this default to be what they want. In this default mode it is incorrect to
10148 submit a file containing only configuration pragmas, or one that ends in
10149 configuration pragmas, to @code{gnatchop}.
10150
10151 However, using a special option to activate ``compilation mode'',
10152 @code{gnatchop}
10153 can perform another function, which is to provide exactly the semantics
10154 required by the RM for handling of configuration pragmas in a compilation.
10155 In the absence of configuration pragmas (at the main file level), this
10156 option has no effect, but it causes such configuration pragmas to be handled
10157 in a quite different manner.
10158
10159 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10160 only configuration pragmas, then this file is appended to the
10161 @file{gnat.adc} file in the current directory. This behavior provides
10162 the required behavior described in the RM for the actions to be taken
10163 on submitting such a file to the compiler, namely that these pragmas
10164 should apply to all subsequent compilations in the same compilation
10165 environment. Using GNAT, the current directory, possibly containing a
10166 @file{gnat.adc} file is the representation
10167 of a compilation environment. For more information on the
10168 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10169
10170 Second, in compilation mode, if @code{gnatchop}
10171 is given a file that starts with
10172 configuration pragmas, and contains one or more units, then these
10173 configuration pragmas are prepended to each of the chopped files. This
10174 behavior provides the required behavior described in the RM for the
10175 actions to be taken on compiling such a file, namely that the pragmas
10176 apply to all units in the compilation, but not to subsequently compiled
10177 units.
10178
10179 Finally, if configuration pragmas appear between units, they are appended
10180 to the previous unit. This results in the previous unit being illegal,
10181 since the compiler does not accept configuration pragmas that follow
10182 a unit. This provides the required RM behavior that forbids configuration
10183 pragmas other than those preceding the first compilation unit of a
10184 compilation.
10185
10186 For most purposes, @code{gnatchop} will be used in default mode. The
10187 compilation mode described above is used only if you need exactly
10188 accurate behavior with respect to compilations, and you have files
10189 that contain multiple units and configuration pragmas. In this
10190 circumstance the use of @code{gnatchop} with the compilation mode
10191 switch provides the required behavior, and is for example the mode
10192 in which GNAT processes the ACVC tests.
10193
10194 @node Command Line for gnatchop
10195 @section Command Line for @code{gnatchop}
10196
10197 @noindent
10198 The @code{gnatchop} command has the form:
10199
10200 @smallexample
10201 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
10202       [@var{directory}]
10203 @end smallexample
10204
10205 @noindent
10206 The only required argument is the file name of the file to be chopped.
10207 There are no restrictions on the form of this file name. The file itself
10208 contains one or more Ada units, in normal GNAT format, concatenated
10209 together. As shown, more than one file may be presented to be chopped.
10210
10211 When run in default mode, @code{gnatchop} generates one output file in
10212 the current directory for each unit in each of the files.
10213
10214 @var{directory}, if specified, gives the name of the directory to which
10215 the output files will be written. If it is not specified, all files are
10216 written to the current directory.
10217
10218 For example, given a
10219 file called @file{hellofiles} containing
10220
10221 @smallexample @c ada
10222 @group
10223 @cartouche
10224 procedure hello;
10225
10226 with Text_IO; use Text_IO;
10227 procedure hello is
10228 begin
10229    Put_Line ("Hello");
10230 end hello;
10231 @end cartouche
10232 @end group
10233 @end smallexample
10234
10235 @noindent
10236 the command
10237
10238 @smallexample
10239 $ gnatchop ^hellofiles^HELLOFILES.^
10240 @end smallexample
10241
10242 @noindent
10243 generates two files in the current directory, one called
10244 @file{hello.ads} containing the single line that is the procedure spec,
10245 and the other called @file{hello.adb} containing the remaining text. The
10246 original file is not affected. The generated files can be compiled in
10247 the normal manner.
10248
10249 @noindent
10250 When gnatchop is invoked on a file that is empty or that contains only empty
10251 lines and/or comments, gnatchop will not fail, but will not produce any
10252 new sources.
10253
10254 For example, given a
10255 file called @file{toto.txt} containing
10256
10257 @smallexample @c ada
10258 @group
10259 @cartouche
10260 --  Just a comment
10261 @end cartouche
10262 @end group
10263 @end smallexample
10264
10265 @noindent
10266 the command
10267
10268 @smallexample
10269 $ gnatchop ^toto.txt^TOT.TXT^
10270 @end smallexample
10271
10272 @noindent
10273 will not produce any new file and will result in the following warnings:
10274
10275 @smallexample
10276 toto.txt:1:01: warning: empty file, contains no compilation units
10277 no compilation units found
10278 no source files written
10279 @end smallexample
10280
10281 @node Switches for gnatchop
10282 @section Switches for @code{gnatchop}
10283
10284 @noindent
10285 @command{gnatchop} recognizes the following switches:
10286
10287 @table @option
10288 @c !sort!
10289
10290 @item ^-c^/COMPILATION^
10291 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10292 Causes @code{gnatchop} to operate in compilation mode, in which
10293 configuration pragmas are handled according to strict RM rules. See
10294 previous section for a full description of this mode.
10295
10296 @ifclear vms
10297 @item -gnatxxx
10298 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10299 used to parse the given file. Not all @code{xxx} options make sense,
10300 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10301 process a source file that uses Latin-2 coding for identifiers.
10302 @end ifclear
10303
10304 @item ^-h^/HELP^
10305 Causes @code{gnatchop} to generate a brief help summary to the standard
10306 output file showing usage information.
10307
10308 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10309 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10310 Limit generated file names to the specified number @code{mm}
10311 of characters.
10312 This is useful if the
10313 resulting set of files is required to be interoperable with systems
10314 which limit the length of file names.
10315 @ifset vms
10316 If no value is given, or
10317 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10318 a default of 39, suitable for OpenVMS Alpha
10319 Systems, is assumed
10320 @end ifset
10321 @ifclear vms
10322 No space is allowed between the @option{-k} and the numeric value. The numeric
10323 value may be omitted in which case a default of @option{-k8},
10324 suitable for use
10325 with DOS-like file systems, is used. If no @option{-k} switch
10326 is present then
10327 there is no limit on the length of file names.
10328 @end ifclear
10329
10330 @item ^-p^/PRESERVE^
10331 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10332 Causes the file ^modification^creation^ time stamp of the input file to be
10333 preserved and used for the time stamp of the output file(s). This may be
10334 useful for preserving coherency of time stamps in an environment where
10335 @code{gnatchop} is used as part of a standard build process.
10336
10337 @item ^-q^/QUIET^
10338 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10339 Causes output of informational messages indicating the set of generated
10340 files to be suppressed. Warnings and error messages are unaffected.
10341
10342 @item ^-r^/REFERENCE^
10343 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10344 @findex Source_Reference
10345 Generate @code{Source_Reference} pragmas. Use this switch if the output
10346 files are regarded as temporary and development is to be done in terms
10347 of the original unchopped file. This switch causes
10348 @code{Source_Reference} pragmas to be inserted into each of the
10349 generated files to refers back to the original file name and line number.
10350 The result is that all error messages refer back to the original
10351 unchopped file.
10352 In addition, the debugging information placed into the object file (when
10353 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10354 specified)
10355 also refers back to this original file so that tools like profilers and
10356 debuggers will give information in terms of the original unchopped file.
10357
10358 If the original file to be chopped itself contains
10359 a @code{Source_Reference}
10360 pragma referencing a third file, then gnatchop respects
10361 this pragma, and the generated @code{Source_Reference} pragmas
10362 in the chopped file refer to the original file, with appropriate
10363 line numbers. This is particularly useful when @code{gnatchop}
10364 is used in conjunction with @code{gnatprep} to compile files that
10365 contain preprocessing statements and multiple units.
10366
10367 @item ^-v^/VERBOSE^
10368 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10369 Causes @code{gnatchop} to operate in verbose mode. The version
10370 number and copyright notice are output, as well as exact copies of
10371 the gnat1 commands spawned to obtain the chop control information.
10372
10373 @item ^-w^/OVERWRITE^
10374 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10375 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10376 fatal error if there is already a file with the same name as a
10377 file it would otherwise output, in other words if the files to be
10378 chopped contain duplicated units. This switch bypasses this
10379 check, and causes all but the last instance of such duplicated
10380 units to be skipped.
10381
10382 @ifclear vms
10383 @item --GCC=xxxx
10384 @cindex @option{--GCC=} (@code{gnatchop})
10385 Specify the path of the GNAT parser to be used. When this switch is used,
10386 no attempt is made to add the prefix to the GNAT parser executable.
10387 @end ifclear
10388 @end table
10389
10390 @node Examples of gnatchop Usage
10391 @section Examples of @code{gnatchop} Usage
10392
10393 @table @code
10394 @ifset vms
10395 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10396 @end ifset
10397 @ifclear vms
10398 @item gnatchop -w hello_s.ada prerelease/files
10399 @end ifclear
10400
10401 Chops the source file @file{hello_s.ada}. The output files will be
10402 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10403 overwriting any
10404 files with matching names in that directory (no files in the current
10405 directory are modified).
10406
10407 @item gnatchop ^archive^ARCHIVE.^
10408 Chops the source file @file{^archive^ARCHIVE.^}
10409 into the current directory. One
10410 useful application of @code{gnatchop} is in sending sets of sources
10411 around, for example in email messages. The required sources are simply
10412 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10413 command), and then
10414 @code{gnatchop} is used at the other end to reconstitute the original
10415 file names.
10416
10417 @item gnatchop file1 file2 file3 direc
10418 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10419 the resulting files in the directory @file{direc}. Note that if any units
10420 occur more than once anywhere within this set of files, an error message
10421 is generated, and no files are written. To override this check, use the
10422 @option{^-w^/OVERWRITE^} switch,
10423 in which case the last occurrence in the last file will
10424 be the one that is output, and earlier duplicate occurrences for a given
10425 unit will be skipped.
10426 @end table
10427
10428 @node Configuration Pragmas
10429 @chapter Configuration Pragmas
10430 @cindex Configuration pragmas
10431 @cindex Pragmas, configuration
10432
10433 @noindent
10434 In Ada 95, configuration pragmas include those pragmas described as
10435 such in the Ada 95 Reference Manual, as well as
10436 implementation-dependent pragmas that are configuration pragmas. See the
10437 individual descriptions of pragmas in the GNAT Reference Manual for
10438 details on these additional GNAT-specific configuration pragmas. Most
10439 notably, the pragma @code{Source_File_Name}, which allows
10440 specifying non-default names for source files, is a configuration
10441 pragma. The following is a complete list of configuration pragmas
10442 recognized by @code{GNAT}:
10443
10444 @smallexample
10445    Ada_83
10446    Ada_95
10447    Ada_05
10448    C_Pass_By_Copy
10449    Component_Alignment
10450    Detect_Blocking
10451    Discard_Names
10452    Elaboration_Checks
10453    Eliminate
10454    Extend_System
10455    External_Name_Casing
10456    Float_Representation
10457    Initialize_Scalars
10458    Interrupt_State
10459    License
10460    Locking_Policy
10461    Long_Float
10462    Normalize_Scalars
10463    Persistent_BSS
10464    Polling
10465    Profile
10466    Profile_Warnings
10467    Propagate_Exceptions
10468    Queuing_Policy
10469    Ravenscar
10470    Restricted_Run_Time
10471    Restrictions
10472    Restrictions_Warnings
10473    Reviewable
10474    Source_File_Name
10475    Style_Checks
10476    Suppress
10477    Task_Dispatching_Policy
10478    Universal_Data
10479    Unsuppress
10480    Use_VADS_Size
10481    Warnings
10482    Validity_Checks
10483 @end smallexample
10484
10485 @menu
10486 * Handling of Configuration Pragmas::
10487 * The Configuration Pragmas Files::
10488 @end menu
10489
10490 @node Handling of Configuration Pragmas
10491 @section Handling of Configuration Pragmas
10492
10493 Configuration pragmas may either appear at the start of a compilation
10494 unit, in which case they apply only to that unit, or they may apply to
10495 all compilations performed in a given compilation environment.
10496
10497 GNAT also provides the @code{gnatchop} utility to provide an automatic
10498 way to handle configuration pragmas following the semantics for
10499 compilations (that is, files with multiple units), described in the RM.
10500 See @ref{Operating gnatchop in Compilation Mode} for details.
10501 However, for most purposes, it will be more convenient to edit the
10502 @file{gnat.adc} file that contains configuration pragmas directly,
10503 as described in the following section.
10504
10505 @node The Configuration Pragmas Files
10506 @section The Configuration Pragmas Files
10507 @cindex @file{gnat.adc}
10508
10509 @noindent
10510 In GNAT a compilation environment is defined by the current
10511 directory at the time that a compile command is given. This current
10512 directory is searched for a file whose name is @file{gnat.adc}. If
10513 this file is present, it is expected to contain one or more
10514 configuration pragmas that will be applied to the current compilation.
10515 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10516 considered.
10517
10518 Configuration pragmas may be entered into the @file{gnat.adc} file
10519 either by running @code{gnatchop} on a source file that consists only of
10520 configuration pragmas, or more conveniently  by
10521 direct editing of the @file{gnat.adc} file, which is a standard format
10522 source file.
10523
10524 In addition to @file{gnat.adc}, one additional file containing configuration
10525 pragmas may be applied to the current compilation using the switch
10526 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10527 contains only configuration pragmas. These configuration pragmas are
10528 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10529 is present and switch @option{-gnatA} is not used).
10530
10531 It is allowed to specify several switches @option{-gnatec}, however only
10532 the last one on the command line will be taken into account.
10533
10534 If you are using project file, a separate mechanism is provided using
10535 project attributes, see @ref{Specifying Configuration Pragmas} for more
10536 details.
10537
10538 @ifset vms
10539 Of special interest to GNAT OpenVMS Alpha is the following
10540 configuration pragma:
10541
10542 @smallexample @c ada
10543 @cartouche
10544 pragma Extend_System (Aux_DEC);
10545 @end cartouche
10546 @end smallexample
10547
10548 @noindent
10549 In the presence of this pragma, GNAT adds to the definition of the
10550 predefined package SYSTEM all the additional types and subprograms that are
10551 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10552 @end ifset
10553
10554 @node Handling Arbitrary File Naming Conventions Using gnatname
10555 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10556 @cindex Arbitrary File Naming Conventions
10557
10558 @menu
10559 * Arbitrary File Naming Conventions::
10560 * Running gnatname::
10561 * Switches for gnatname::
10562 * Examples of gnatname Usage::
10563 @end menu
10564
10565 @node Arbitrary File Naming Conventions
10566 @section Arbitrary File Naming Conventions
10567
10568 @noindent
10569 The GNAT compiler must be able to know the source file name of a compilation
10570 unit.  When using the standard GNAT default file naming conventions
10571 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10572 does not need additional information.
10573
10574 @noindent
10575 When the source file names do not follow the standard GNAT default file naming
10576 conventions, the GNAT compiler must be given additional information through
10577 a configuration pragmas file (@pxref{Configuration Pragmas})
10578 or a project file.
10579 When the non standard file naming conventions are well-defined,
10580 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10581 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10582 if the file naming conventions are irregular or arbitrary, a number
10583 of pragma @code{Source_File_Name} for individual compilation units
10584 must be defined.
10585 To help maintain the correspondence between compilation unit names and
10586 source file names within the compiler,
10587 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10588 set of files.
10589
10590 @node Running gnatname
10591 @section Running @code{gnatname}
10592
10593 @noindent
10594 The usual form of the @code{gnatname} command is
10595
10596 @smallexample
10597 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10598 @end smallexample
10599
10600 @noindent
10601 All of the arguments are optional. If invoked without any argument,
10602 @code{gnatname} will display its usage.
10603
10604 @noindent
10605 When used with at least one naming pattern, @code{gnatname} will attempt to
10606 find all the compilation units in files that follow at least one of the
10607 naming patterns. To find these compilation units,
10608 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10609 regular files.
10610
10611 @noindent
10612 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10613 Each Naming Pattern is enclosed between double quotes.
10614 A Naming Pattern is a regular expression similar to the wildcard patterns
10615 used in file names by the Unix shells or the DOS prompt.
10616
10617 @noindent
10618 Examples of Naming Patterns are
10619
10620 @smallexample
10621    "*.[12].ada"
10622    "*.ad[sb]*"
10623    "body_*"    "spec_*"
10624 @end smallexample
10625
10626 @noindent
10627 For a more complete description of the syntax of Naming Patterns,
10628 see the second kind of regular expressions described in @file{g-regexp.ads}
10629 (the ``Glob'' regular expressions).
10630
10631 @noindent
10632 When invoked with no switches, @code{gnatname} will create a configuration
10633 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10634 @code{Source_File_Name} for each file that contains a valid Ada unit.
10635
10636 @node Switches for gnatname
10637 @section Switches for @code{gnatname}
10638
10639 @noindent
10640 Switches for @code{gnatname} must precede any specified Naming Pattern.
10641
10642 @noindent
10643 You may specify any of the following switches to @code{gnatname}:
10644
10645 @table @option
10646 @c !sort!
10647
10648 @item ^-c^/CONFIG_FILE=^@file{file}
10649 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10650 Create a configuration pragmas file @file{file} (instead of the default
10651 @file{gnat.adc}).
10652 @ifclear vms
10653 There may be zero, one or more space between @option{-c} and
10654 @file{file}.
10655 @end ifclear
10656 @file{file} may include directory information. @file{file} must be
10657 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10658 When a switch @option{^-c^/CONFIG_FILE^} is
10659 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10660
10661 @item ^-d^/SOURCE_DIRS=^@file{dir}
10662 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10663 Look for source files in directory @file{dir}. There may be zero, one or more
10664 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10665 When a switch @option{^-d^/SOURCE_DIRS^}
10666 is specified, the current working directory will not be searched for source
10667 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10668 or @option{^-D^/DIR_FILES^} switch.
10669 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10670 If @file{dir} is a relative path, it is relative to the directory of
10671 the configuration pragmas file specified with switch
10672 @option{^-c^/CONFIG_FILE^},
10673 or to the directory of the project file specified with switch
10674 @option{^-P^/PROJECT_FILE^} or,
10675 if neither switch @option{^-c^/CONFIG_FILE^}
10676 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10677 current working directory. The directory
10678 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10679
10680 @item ^-D^/DIRS_FILE=^@file{file}
10681 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10682 Look for source files in all directories listed in text file @file{file}.
10683 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10684 and @file{file}.
10685 @file{file} must be an existing, readable text file.
10686 Each non empty line in @file{file} must be a directory.
10687 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10688 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10689 @file{file}.
10690
10691 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10692 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10693 Foreign patterns. Using this switch, it is possible to add sources of languages
10694 other than Ada to the list of sources of a project file.
10695 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10696 For example,
10697 @smallexample
10698 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10699 @end smallexample
10700 @noindent
10701 will look for Ada units in all files with the @file{.ada} extension,
10702 and will add to the list of file for project @file{prj.gpr} the C files
10703 with extension ".^c^C^".
10704
10705 @item ^-h^/HELP^
10706 @cindex @option{^-h^/HELP^} (@code{gnatname})
10707 Output usage (help) information. The output is written to @file{stdout}.
10708
10709 @item ^-P^/PROJECT_FILE=^@file{proj}
10710 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10711 Create or update project file @file{proj}. There may be zero, one or more space
10712 between @option{-P} and @file{proj}. @file{proj} may include directory
10713 information. @file{proj} must be writable.
10714 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10715 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10716 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10717
10718 @item ^-v^/VERBOSE^
10719 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10720 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10721 This includes name of the file written, the name of the directories to search
10722 and, for each file in those directories whose name matches at least one of
10723 the Naming Patterns, an indication of whether the file contains a unit,
10724 and if so the name of the unit.
10725
10726 @item ^-v -v^/VERBOSE /VERBOSE^
10727 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10728 Very Verbose mode. In addition to the output produced in verbose mode,
10729 for each file in the searched directories whose name matches none of
10730 the Naming Patterns, an indication is given that there is no match.
10731
10732 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10733 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10734 Excluded patterns. Using this switch, it is possible to exclude some files
10735 that would match the name patterns. For example,
10736 @smallexample
10737 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10738 @end smallexample
10739 @noindent
10740 will look for Ada units in all files with the @file{.ada} extension,
10741 except those whose names end with @file{_nt.ada}.
10742
10743 @end table
10744
10745 @node Examples of gnatname Usage
10746 @section Examples of @code{gnatname} Usage
10747
10748 @ifset vms
10749 @smallexample
10750 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10751 @end smallexample
10752 @end ifset
10753
10754 @ifclear vms
10755 @smallexample
10756 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10757 @end smallexample
10758 @end ifclear
10759
10760 @noindent
10761 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10762 and be writable. In addition, the directory
10763 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10764 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10765
10766 @ifclear vms
10767 Note the optional spaces after @option{-c} and @option{-d}.
10768 @end ifclear
10769
10770 @smallexample
10771 @ifclear vms
10772 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10773   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10774 @end ifclear
10775 @ifset vms
10776 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10777   /EXCLUDED_PATTERN=*_nt_body.ada
10778   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10779   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10780 @end ifset
10781 @end smallexample
10782
10783 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10784 even in conjunction with one or several switches
10785 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10786 are used in this example.
10787
10788 @c *****************************************
10789 @c * G N A T  P r o j e c t  M a n a g e r *
10790 @c *****************************************
10791 @node GNAT Project Manager
10792 @chapter GNAT Project Manager
10793
10794 @menu
10795 * Introduction::
10796 * Examples of Project Files::
10797 * Project File Syntax::
10798 * Objects and Sources in Project Files::
10799 * Importing Projects::
10800 * Project Extension::
10801 * Project Hierarchy Extension::
10802 * External References in Project Files::
10803 * Packages in Project Files::
10804 * Variables from Imported Projects::
10805 * Naming Schemes::
10806 * Library Projects::
10807 * Stand-alone Library Projects::
10808 * Switches Related to Project Files::
10809 * Tools Supporting Project Files::
10810 * An Extended Example::
10811 * Project File Complete Syntax::
10812 @end menu
10813
10814 @c ****************
10815 @c * Introduction *
10816 @c ****************
10817
10818 @node Introduction
10819 @section Introduction
10820
10821 @noindent
10822 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10823 you to manage complex builds involving a number of source files, directories,
10824 and compilation options for different system configurations. In particular,
10825 project files allow you to specify:
10826 @itemize @bullet
10827 @item
10828 The directory or set of directories containing the source files, and/or the
10829 names of the specific source files themselves
10830 @item
10831 The directory in which the compiler's output
10832 (@file{ALI} files, object files, tree files) is to be placed
10833 @item
10834 The directory in which the executable programs is to be placed
10835 @item
10836 ^Switch^Switch^ settings for any of the project-enabled tools
10837 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10838 @code{gnatfind}); you can apply these settings either globally or to individual
10839 compilation units.
10840 @item
10841 The source files containing the main subprogram(s) to be built
10842 @item
10843 The source programming language(s) (currently Ada and/or C)
10844 @item
10845 Source file naming conventions; you can specify these either globally or for
10846 individual compilation units
10847 @end itemize
10848
10849 @menu
10850 * Project Files::
10851 @end menu
10852
10853 @node Project Files
10854 @subsection Project Files
10855
10856 @noindent
10857 Project files are written in a syntax close to that of Ada, using  familiar
10858 notions such as packages, context clauses, declarations, default values,
10859 assignments, and inheritance. Finally, project files can be built
10860 hierarchically from other project files, simplifying complex system
10861 integration and project reuse.
10862
10863 A @dfn{project} is a specific set of values for various compilation properties.
10864 The settings for a given project are described by means of
10865 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10866 Property values in project files are either strings or lists of strings.
10867 Properties that are not explicitly set receive default values.  A project
10868 file may interrogate the values of @dfn{external variables} (user-defined
10869 command-line switches or environment variables), and it may specify property
10870 settings conditionally, based on the value of such variables.
10871
10872 In simple cases, a project's source files depend only on other source files
10873 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10874 used in
10875 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10876 the Project Manager also allows more sophisticated arrangements,
10877 where the source files in one project depend on source files in other
10878 projects:
10879 @itemize @bullet
10880 @item
10881 One project can @emph{import} other projects containing needed source files.
10882 @item
10883 You can organize GNAT projects in a hierarchy: a @emph{child} project
10884 can extend a @emph{parent} project, inheriting the parent's source files and
10885 optionally overriding any of them with alternative versions
10886 @end itemize
10887
10888 @noindent
10889 More generally, the Project Manager lets you structure large development
10890 efforts into hierarchical subsystems, where build decisions are delegated
10891 to the subsystem level, and thus different compilation environments
10892 (^switch^switch^ settings) used for different subsystems.
10893
10894 The Project Manager is invoked through the
10895 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10896 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10897 @ifclear vms
10898 There may be zero, one or more spaces between @option{-P} and
10899 @option{@emph{projectfile}}.
10900 @end ifclear
10901 If you want to define (on the command line) an external variable that is
10902 queried by the project file, you must use the
10903 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10904 The Project Manager parses and interprets the project file, and drives the
10905 invoked tool based on the project settings.
10906
10907 The Project Manager supports a wide range of development strategies,
10908 for systems of all sizes.  Here are some typical practices that are
10909 easily handled:
10910 @itemize @bullet
10911 @item
10912 Using a common set of source files, but generating object files in different
10913 directories via different ^switch^switch^ settings
10914 @item
10915 Using a mostly-shared set of source files, but with different versions of
10916 some unit or units
10917 @end itemize
10918
10919 @noindent
10920 The destination of an executable can be controlled inside a project file
10921 using the @option{^-o^-o^}
10922 ^switch^switch^.
10923 In the absence of such a ^switch^switch^ either inside
10924 the project file or on the command line, any executable files generated by
10925 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10926 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10927 in the object directory of the project.
10928
10929 You can use project files to achieve some of the effects of a source
10930 versioning system (for example, defining separate projects for
10931 the different sets of sources that comprise different releases) but the
10932 Project Manager is independent of any source configuration management tools
10933 that might be used by the developers.
10934
10935 The next section introduces the main features of GNAT's project facility
10936 through a sequence of examples; subsequent sections will present the syntax
10937 and semantics in more detail. A more formal description of the project
10938 facility appears in the GNAT Reference Manual.
10939
10940 @c *****************************
10941 @c * Examples of Project Files *
10942 @c *****************************
10943
10944 @node Examples of Project Files
10945 @section Examples of Project Files
10946 @noindent
10947 This section illustrates some of the typical uses of project files and
10948 explains their basic structure and behavior.
10949
10950 @menu
10951 * Common Sources with Different ^Switches^Switches^ and Directories::
10952 * Using External Variables::
10953 * Importing Other Projects::
10954 * Extending a Project::
10955 @end menu
10956
10957 @node Common Sources with Different ^Switches^Switches^ and Directories
10958 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10959
10960 @menu
10961 * Source Files::
10962 * Specifying the Object Directory::
10963 * Specifying the Exec Directory::
10964 * Project File Packages::
10965 * Specifying ^Switch^Switch^ Settings::
10966 * Main Subprograms::
10967 * Executable File Names::
10968 * Source File Naming Conventions::
10969 * Source Language(s)::
10970 @end menu
10971
10972 @noindent
10973 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10974 @file{proc.adb} are in the @file{/common} directory.  The file
10975 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10976 package @code{Pack}.  We want to compile these source files under two sets
10977 of ^switches^switches^:
10978 @itemize @bullet
10979 @item
10980 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10981 and the @option{^-gnata^-gnata^},
10982 @option{^-gnato^-gnato^},
10983 and @option{^-gnatE^-gnatE^} switches to the
10984 compiler; the compiler's output is to appear in @file{/common/debug}
10985 @item
10986 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10987 to the compiler; the compiler's output is to appear in @file{/common/release}
10988 @end itemize
10989
10990 @noindent
10991 The GNAT project files shown below, respectively @file{debug.gpr} and
10992 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10993
10994 Schematically:
10995 @smallexample
10996 @group
10997 ^/common^[COMMON]^
10998   debug.gpr
10999   release.gpr
11000   pack.ads
11001   pack.adb
11002   proc.adb
11003 @end group
11004 @group
11005 ^/common/debug^[COMMON.DEBUG]^
11006   proc.ali, proc.o
11007   pack.ali, pack.o
11008 @end group
11009 @group
11010 ^/common/release^[COMMON.RELEASE]^
11011   proc.ali, proc.o
11012   pack.ali, pack.o
11013 @end group
11014 @end smallexample
11015 Here are the corresponding project files:
11016
11017 @smallexample @c projectfile
11018 @group
11019 project Debug is
11020   for Object_Dir use "debug";
11021   for Main use ("proc");
11022
11023   package Builder is
11024     for ^Default_Switches^Default_Switches^ ("Ada")
11025         use ("^-g^-g^");
11026     for Executable ("proc.adb") use "proc1";
11027   end Builder;
11028 @end group
11029
11030 @group
11031   package Compiler is
11032     for ^Default_Switches^Default_Switches^ ("Ada")
11033        use ("-fstack-check",
11034             "^-gnata^-gnata^",
11035             "^-gnato^-gnato^",
11036             "^-gnatE^-gnatE^");
11037   end Compiler;
11038 end Debug;
11039 @end group
11040 @end smallexample
11041
11042 @smallexample @c projectfile
11043 @group
11044 project Release is
11045   for Object_Dir use "release";
11046   for Exec_Dir use ".";
11047   for Main use ("proc");
11048
11049   package Compiler is
11050     for ^Default_Switches^Default_Switches^ ("Ada")
11051         use ("^-O2^-O2^");
11052   end Compiler;
11053 end Release;
11054 @end group
11055 @end smallexample
11056
11057 @noindent
11058 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11059 insensitive), and analogously the project defined by @file{release.gpr} is
11060 @code{"Release"}.  For consistency the file should have the same name as the
11061 project, and the project file's extension should be @code{"gpr"}. These
11062 conventions are not required, but a warning is issued if they are not followed.
11063
11064 If the current directory is @file{^/temp^[TEMP]^}, then the command
11065 @smallexample
11066 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11067 @end smallexample
11068
11069 @noindent
11070 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11071 as well as the @code{^proc1^PROC1.EXE^} executable,
11072 using the ^switch^switch^ settings defined in the project file.
11073
11074 Likewise, the command
11075 @smallexample
11076 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11077 @end smallexample
11078
11079 @noindent
11080 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11081 and the @code{^proc^PROC.EXE^}
11082 executable in @file{^/common^[COMMON]^},
11083 using the ^switch^switch^ settings from the project file.
11084
11085 @node Source Files
11086 @unnumberedsubsubsec Source Files
11087
11088 @noindent
11089 If a project file does not explicitly specify a set of source directories or
11090 a set of source files, then by default the project's source files are the
11091 Ada source files in the project file directory.  Thus @file{pack.ads},
11092 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11093
11094 @node Specifying the Object Directory
11095 @unnumberedsubsubsec Specifying the Object Directory
11096
11097 @noindent
11098 Several project properties are modeled by Ada-style @emph{attributes};
11099 a property is defined by supplying the equivalent of an Ada attribute
11100 definition clause in the project file.
11101 A project's object directory is another such a property; the corresponding
11102 attribute is @code{Object_Dir}, and its value is also a string expression,
11103 specified either as absolute or relative. In the later case,
11104 it is relative to the project file directory. Thus the compiler's
11105 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11106 (for the @code{Debug} project)
11107 and to @file{^/common/release^[COMMON.RELEASE]^}
11108 (for the @code{Release} project).
11109 If @code{Object_Dir} is not specified, then the default is the project file
11110 directory itself.
11111
11112 @node Specifying the Exec Directory
11113 @unnumberedsubsubsec Specifying the Exec Directory
11114
11115 @noindent
11116 A project's exec directory is another property; the corresponding
11117 attribute is @code{Exec_Dir}, and its value is also a string expression,
11118 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11119 then the default is the object directory (which may also be the project file
11120 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11121 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11122 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11123 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11124
11125 @node Project File Packages
11126 @unnumberedsubsubsec Project File Packages
11127
11128 @noindent
11129 A GNAT tool that is integrated with the Project Manager is modeled by a
11130 corresponding package in the project file. In the example above,
11131 The @code{Debug} project defines the packages @code{Builder}
11132 (for @command{gnatmake}) and @code{Compiler};
11133 the @code{Release} project defines only the @code{Compiler} package.
11134
11135 The Ada-like package syntax is not to be taken literally.  Although packages in
11136 project files bear a surface resemblance to packages in Ada source code, the
11137 notation is simply a way to convey a grouping of properties for a named
11138 entity.  Indeed, the package names permitted in project files are restricted
11139 to a predefined set, corresponding to the project-aware tools, and the contents
11140 of packages are limited to a small set of constructs.
11141 The packages in the example above contain attribute definitions.
11142
11143 @node Specifying ^Switch^Switch^ Settings
11144 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11145
11146 @noindent
11147 ^Switch^Switch^ settings for a project-aware tool can be specified through
11148 attributes in the package that corresponds to the tool.
11149 The example above illustrates one of the relevant attributes,
11150 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11151 in both project files.
11152 Unlike simple attributes like @code{Source_Dirs},
11153 @code{^Default_Switches^Default_Switches^} is
11154 known as an @emph{associative array}.  When you define this attribute, you must
11155 supply an ``index'' (a literal string), and the effect of the attribute
11156 definition is to set the value of the array at the specified index.
11157 For the @code{^Default_Switches^Default_Switches^} attribute,
11158 the index is a programming language (in our case, Ada),
11159 and the value specified (after @code{use}) must be a list
11160 of string expressions.
11161
11162 The attributes permitted in project files are restricted to a predefined set.
11163 Some may appear at project level, others in packages.
11164 For any attribute that is an associative array, the index must always be a
11165 literal string, but the restrictions on this string (e.g., a file name or a
11166 language name) depend on the individual attribute.
11167 Also depending on the attribute, its specified value will need to be either a
11168 string or a string list.
11169
11170 In the @code{Debug} project, we set the switches for two tools,
11171 @command{gnatmake} and the compiler, and thus we include the two corresponding
11172 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11173 attribute with index @code{"Ada"}.
11174 Note that the package corresponding to
11175 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
11176 similar, but only includes the @code{Compiler} package.
11177
11178 In project @code{Debug} above, the ^switches^switches^ starting with
11179 @option{-gnat} that are specified in package @code{Compiler}
11180 could have been placed in package @code{Builder}, since @command{gnatmake}
11181 transmits all such ^switches^switches^ to the compiler.
11182
11183 @node Main Subprograms
11184 @unnumberedsubsubsec Main Subprograms
11185
11186 @noindent
11187 One of the specifiable properties of a project is a list of files that contain
11188 main subprograms.  This property is captured in the @code{Main} attribute,
11189 whose value is a list of strings.  If a project defines the @code{Main}
11190 attribute, it is not necessary to identify the main subprogram(s) when
11191 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11192
11193 @node Executable File Names
11194 @unnumberedsubsubsec Executable File Names
11195
11196 @noindent
11197 By default, the executable file name corresponding to a main source is
11198 deduced from the main source file name. Through the attributes
11199 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11200 it is possible to change this default.
11201 In project @code{Debug} above, the executable file name
11202 for main source @file{^proc.adb^PROC.ADB^} is
11203 @file{^proc1^PROC1.EXE^}.
11204 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11205 of the executable files, when no attribute @code{Executable} applies:
11206 its value replace the platform-specific executable suffix.
11207 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11208 specify a non default executable file name when several mains are built at once
11209 in a single @command{gnatmake} command.
11210
11211 @node Source File Naming Conventions
11212 @unnumberedsubsubsec Source File Naming Conventions
11213
11214 @noindent
11215 Since the project files above do not specify any source file naming
11216 conventions, the GNAT defaults are used.  The mechanism for defining source
11217 file naming conventions -- a package named @code{Naming} --
11218 is described below (@pxref{Naming Schemes}).
11219
11220 @node Source Language(s)
11221 @unnumberedsubsubsec Source Language(s)
11222
11223 @noindent
11224 Since the project files do not specify a @code{Languages} attribute, by
11225 default the GNAT tools assume that the language of the project file is Ada.
11226 More generally, a project can comprise source files
11227 in Ada, C, and/or other languages.
11228
11229 @node Using External Variables
11230 @subsection Using External Variables
11231
11232 @noindent
11233 Instead of supplying different project files for debug and release, we can
11234 define a single project file that queries an external variable (set either
11235 on the command line or via an ^environment variable^logical name^) in order to
11236 conditionally define the appropriate settings.  Again, assume that the
11237 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11238 located in directory @file{^/common^[COMMON]^}.  The following project file,
11239 @file{build.gpr}, queries the external variable named @code{STYLE} and
11240 defines an object directory and ^switch^switch^ settings based on whether
11241 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11242 the default is @code{"deb"}.
11243
11244 @smallexample @c projectfile
11245 @group
11246 project Build is
11247   for Main use ("proc");
11248
11249   type Style_Type is ("deb", "rel");
11250   Style : Style_Type := external ("STYLE", "deb");
11251
11252   case Style is
11253     when "deb" =>
11254       for Object_Dir use "debug";
11255
11256     when "rel" =>
11257       for Object_Dir use "release";
11258       for Exec_Dir use ".";
11259   end case;
11260 @end group
11261
11262 @group
11263   package Builder is
11264
11265     case Style is
11266       when "deb" =>
11267         for ^Default_Switches^Default_Switches^ ("Ada")
11268             use ("^-g^-g^");
11269         for Executable ("proc") use "proc1";
11270       when others =>
11271         null;
11272     end case;
11273
11274   end Builder;
11275 @end group
11276
11277 @group
11278   package Compiler is
11279
11280     case Style is
11281       when "deb" =>
11282         for ^Default_Switches^Default_Switches^ ("Ada")
11283             use ("^-gnata^-gnata^",
11284                  "^-gnato^-gnato^",
11285                  "^-gnatE^-gnatE^");
11286
11287       when "rel" =>
11288         for ^Default_Switches^Default_Switches^ ("Ada")
11289             use ("^-O2^-O2^");
11290     end case;
11291
11292   end Compiler;
11293
11294 end Build;
11295 @end group
11296 @end smallexample
11297
11298 @noindent
11299 @code{Style_Type} is an example of a @emph{string type}, which is the project
11300 file analog of an Ada enumeration type but whose components are string literals
11301 rather than identifiers.  @code{Style} is declared as a variable of this type.
11302
11303 The form @code{external("STYLE", "deb")} is known as an
11304 @emph{external reference}; its first argument is the name of an
11305 @emph{external variable}, and the second argument is a default value to be
11306 used if the external variable doesn't exist.  You can define an external
11307 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11308 or you can use ^an environment variable^a logical name^
11309 as an external variable.
11310
11311 Each @code{case} construct is expanded by the Project Manager based on the
11312 value of @code{Style}. Thus the command
11313 @ifclear vms
11314 @smallexample
11315 gnatmake -P/common/build.gpr -XSTYLE=deb
11316 @end smallexample
11317 @end ifclear
11318
11319 @ifset vms
11320 @smallexample
11321 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11322 @end smallexample
11323 @end ifset
11324
11325 @noindent
11326 is equivalent to the @command{gnatmake} invocation using the project file
11327 @file{debug.gpr} in the earlier example.  So is the command
11328 @smallexample
11329 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11330 @end smallexample
11331
11332 @noindent
11333 since @code{"deb"} is the default for @code{STYLE}.
11334
11335 Analogously,
11336
11337 @ifclear vms
11338 @smallexample
11339 gnatmake -P/common/build.gpr -XSTYLE=rel
11340 @end smallexample
11341 @end ifclear
11342
11343 @ifset vms
11344 @smallexample
11345 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11346 @end smallexample
11347 @end ifset
11348
11349 @noindent
11350 is equivalent to the @command{gnatmake} invocation using the project file
11351 @file{release.gpr} in the earlier example.
11352
11353 @node Importing Other Projects
11354 @subsection Importing Other Projects
11355 @cindex @code{ADA_PROJECT_PATH}
11356
11357 @noindent
11358 A compilation unit in a source file in one project may depend on compilation
11359 units in source files in other projects.  To compile this unit under
11360 control of a project file, the
11361 dependent project must @emph{import} the projects containing the needed source
11362 files.
11363 This effect is obtained using syntax similar to an Ada @code{with} clause,
11364 but where @code{with}ed entities are strings that denote project files.
11365
11366 As an example, suppose that the two projects @code{GUI_Proj} and
11367 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11368 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11369 and @file{^/comm^[COMM]^}, respectively.
11370 Suppose that the source files for @code{GUI_Proj} are
11371 @file{gui.ads} and @file{gui.adb}, and that the source files for
11372 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11373 files is located in its respective project file directory.  Schematically:
11374
11375 @smallexample
11376 @group
11377 ^/gui^[GUI]^
11378   gui_proj.gpr
11379   gui.ads
11380   gui.adb
11381 @end group
11382
11383 @group
11384 ^/comm^[COMM]^
11385   comm_proj.gpr
11386   comm.ads
11387   comm.adb
11388 @end group
11389 @end smallexample
11390
11391 @noindent
11392 We want to develop an application in directory @file{^/app^[APP]^} that
11393 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11394 the corresponding project files (e.g. the ^switch^switch^ settings
11395 and object directory).
11396 Skeletal code for a main procedure might be something like the following:
11397
11398 @smallexample @c ada
11399 @group
11400 with GUI, Comm;
11401 procedure App_Main is
11402    ...
11403 begin
11404    ...
11405 end App_Main;
11406 @end group
11407 @end smallexample
11408
11409 @noindent
11410 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11411 effect:
11412
11413 @smallexample @c projectfile
11414 @group
11415 with "/gui/gui_proj", "/comm/comm_proj";
11416 project App_Proj is
11417    for Main use ("app_main");
11418 end App_Proj;
11419 @end group
11420 @end smallexample
11421
11422 @noindent
11423 Building an executable is achieved through the command:
11424 @smallexample
11425 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11426 @end smallexample
11427 @noindent
11428 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11429 in the directory where @file{app_proj.gpr} resides.
11430
11431 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11432 (as illustrated above) the @code{with} clause can omit the extension.
11433
11434 Our example specified an absolute path for each imported project file.
11435 Alternatively, the directory name of an imported object can be omitted
11436 if either
11437 @itemize @bullet
11438 @item
11439 The imported project file is in the same directory as the importing project
11440 file, or
11441 @item
11442 You have defined ^an environment variable^a logical name^
11443 that includes the directory containing
11444 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11445 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11446 directory names separated by colons (semicolons on Windows).
11447 @end itemize
11448
11449 @noindent
11450 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11451 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11452 as follows:
11453
11454 @smallexample @c projectfile
11455 @group
11456 with "gui_proj", "comm_proj";
11457 project App_Proj is
11458    for Main use ("app_main");
11459 end App_Proj;
11460 @end group
11461 @end smallexample
11462
11463 @noindent
11464 Importing other projects can create ambiguities.
11465 For example, the same unit might be present in different imported projects, or
11466 it might be present in both the importing project and in an imported project.
11467 Both of these conditions are errors.  Note that in the current version of
11468 the Project Manager, it is illegal to have an ambiguous unit even if the
11469 unit is never referenced by the importing project.  This restriction may be
11470 relaxed in a future release.
11471
11472 @node Extending a Project
11473 @subsection Extending a Project
11474
11475 @noindent
11476 In large software systems it is common to have multiple
11477 implementations of a common interface; in Ada terms, multiple versions of a
11478 package body for the same specification.  For example, one implementation
11479 might be safe for use in tasking programs, while another might only be used
11480 in sequential applications.  This can be modeled in GNAT using the concept
11481 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11482 another project (the ``parent'') then by default all source files of the
11483 parent project are inherited by the child, but the child project can
11484 override any of the parent's source files with new versions, and can also
11485 add new files.  This facility is the project analog of a type extension in
11486 Object-Oriented Programming.  Project hierarchies are permitted (a child
11487 project may be the parent of yet another project), and a project that
11488 inherits one project can also import other projects.
11489
11490 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11491 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11492 @file{pack.adb}, and @file{proc.adb}:
11493
11494 @smallexample
11495 @group
11496 ^/seq^[SEQ]^
11497   pack.ads
11498   pack.adb
11499   proc.adb
11500   seq_proj.gpr
11501 @end group
11502 @end smallexample
11503
11504 @noindent
11505 Note that the project file can simply be empty (that is, no attribute or
11506 package is defined):
11507
11508 @smallexample @c projectfile
11509 @group
11510 project Seq_Proj is
11511 end Seq_Proj;
11512 @end group
11513 @end smallexample
11514
11515 @noindent
11516 implying that its source files are all the Ada source files in the project
11517 directory.
11518
11519 Suppose we want to supply an alternate version of @file{pack.adb}, in
11520 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11521 @file{pack.ads} and @file{proc.adb}.  We can define a project
11522 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11523
11524 @smallexample
11525 @group
11526 ^/tasking^[TASKING]^
11527   pack.adb
11528   tasking_proj.gpr
11529 @end group
11530
11531 @group
11532 project Tasking_Proj extends "/seq/seq_proj" is
11533 end Tasking_Proj;
11534 @end group
11535 @end smallexample
11536
11537 @noindent
11538 The version of @file{pack.adb} used in a build depends on which project file
11539 is specified.
11540
11541 Note that we could have obtained the desired behavior using project import
11542 rather than project inheritance; a @code{base} project would contain the
11543 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11544 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11545 would import @code{base} and add a different version of @file{pack.adb}.  The
11546 choice depends on whether other sources in the original project need to be
11547 overridden.  If they do, then project extension is necessary, otherwise,
11548 importing is sufficient.
11549
11550 @noindent
11551 In a project file that extends another project file, it is possible to
11552 indicate that an inherited source is not part of the sources of the extending
11553 project. This is necessary sometimes when a package spec has been overloaded
11554 and no longer requires a body: in this case, it is necessary to indicate that
11555 the inherited body is not part of the sources of the project, otherwise there
11556 will be a compilation error when compiling the spec.
11557
11558 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11559 Its value is a string list: a list of file names.
11560
11561 @smallexample @c @projectfile
11562 project B extends "a" is
11563    for Source_Files use ("pkg.ads");
11564    --  New spec of Pkg does not need a completion
11565    for Locally_Removed_Files use ("pkg.adb");
11566 end B;
11567 @end smallexample
11568
11569 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11570 is still needed: if it is possible to build using @command{gnatmake} when such
11571 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11572 it is possible to remove the source completely from a system that includes
11573 project P.
11574
11575 @c ***********************
11576 @c * Project File Syntax *
11577 @c ***********************
11578
11579 @node Project File Syntax
11580 @section Project File Syntax
11581
11582 @menu
11583 * Basic Syntax::
11584 * Packages::
11585 * Expressions::
11586 * String Types::
11587 * Variables::
11588 * Attributes::
11589 * Associative Array Attributes::
11590 * case Constructions::
11591 @end menu
11592
11593 @noindent
11594 This section describes the structure of project files.
11595
11596 A project may be an @emph{independent project}, entirely defined by a single
11597 project file. Any Ada source file in an independent project depends only
11598 on the predefined library and other Ada source files in the same project.
11599
11600 @noindent
11601 A project may also @dfn{depend on} other projects, in either or both of
11602 the following ways:
11603 @itemize @bullet
11604 @item It may import any number of projects
11605 @item It may extend at most one other project
11606 @end itemize
11607
11608 @noindent
11609 The dependence relation is a directed acyclic graph (the subgraph reflecting
11610 the ``extends'' relation is a tree).
11611
11612 A project's @dfn{immediate sources} are the source files directly defined by
11613 that project, either implicitly by residing in the project file's directory,
11614 or explicitly through any of the source-related attributes described below.
11615 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11616 of @var{proj} together with the immediate sources (unless overridden) of any
11617 project on which @var{proj} depends (either directly or indirectly).
11618
11619 @node Basic Syntax
11620 @subsection Basic Syntax
11621
11622 @noindent
11623 As seen in the earlier examples, project files have an Ada-like syntax.
11624 The minimal project file is:
11625 @smallexample @c projectfile
11626 @group
11627 project Empty is
11628
11629 end Empty;
11630 @end group
11631 @end smallexample
11632
11633 @noindent
11634 The identifier @code{Empty} is the name of the project.
11635 This project name must be present after the reserved
11636 word @code{end} at the end of the project file, followed by a semi-colon.
11637
11638 Any name in a project file, such as the project name or a variable name,
11639 has the same syntax as an Ada identifier.
11640
11641 The reserved words of project files are the Ada reserved words plus
11642 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11643 reserved words currently used in project file syntax are:
11644
11645 @itemize @bullet
11646 @item
11647 @code{case}
11648 @item
11649 @code{end}
11650 @item
11651 @code{for}
11652 @item
11653 @code{is}
11654 @item
11655 @code{others}
11656 @item
11657 @code{package}
11658 @item
11659 @code{renames}
11660 @item
11661 @code{type}
11662 @item
11663 @code{use}
11664 @item
11665 @code{when}
11666 @item
11667 @code{with}
11668 @end itemize
11669
11670 @noindent
11671 Comments in project files have the same syntax as in Ada, two consecutives
11672 hyphens through the end of the line.
11673
11674 @node Packages
11675 @subsection Packages
11676
11677 @noindent
11678 A project file may contain @emph{packages}. The name of a package must be one
11679 of the identifiers from the following list. A package
11680 with a given name may only appear once in a project file. Package names are
11681 case insensitive. The following package names are legal:
11682
11683 @itemize @bullet
11684 @item
11685 @code{Naming}
11686 @item
11687 @code{Builder}
11688 @item
11689 @code{Compiler}
11690 @item
11691 @code{Binder}
11692 @item
11693 @code{Linker}
11694 @item
11695 @code{Finder}
11696 @item
11697 @code{Cross_Reference}
11698 @item
11699 @code{Eliminate}
11700 @item
11701 @code{Pretty_Printer}
11702 @item
11703 @code{Metrics}
11704 @item
11705 @code{gnatls}
11706 @item
11707 @code{gnatstub}
11708 @item
11709 @code{IDE}
11710 @item
11711 @code{Language_Processing}
11712 @end itemize
11713
11714 @noindent
11715 In its simplest form, a package may be empty:
11716
11717 @smallexample @c projectfile
11718 @group
11719 project Simple is
11720   package Builder is
11721   end Builder;
11722 end Simple;
11723 @end group
11724 @end smallexample
11725
11726 @noindent
11727 A package may contain @emph{attribute declarations},
11728 @emph{variable declarations} and @emph{case constructions}, as will be
11729 described below.
11730
11731 When there is ambiguity between a project name and a package name,
11732 the name always designates the project. To avoid possible confusion, it is
11733 always a good idea to avoid naming a project with one of the
11734 names allowed for packages or any name that starts with @code{gnat}.
11735
11736 @node Expressions
11737 @subsection Expressions
11738
11739 @noindent
11740 An @emph{expression} is either a @emph{string expression} or a
11741 @emph{string list expression}.
11742
11743 A @emph{string expression} is either a @emph{simple string expression} or a
11744 @emph{compound string expression}.
11745
11746 A @emph{simple string expression} is one of the following:
11747 @itemize @bullet
11748 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11749 @item A string-valued variable reference (@pxref{Variables})
11750 @item A string-valued attribute reference (@pxref{Attributes})
11751 @item An external reference (@pxref{External References in Project Files})
11752 @end itemize
11753
11754 @noindent
11755 A @emph{compound string expression} is a concatenation of string expressions,
11756 using the operator @code{"&"}
11757 @smallexample
11758        Path & "/" & File_Name & ".ads"
11759 @end smallexample
11760
11761 @noindent
11762 A @emph{string list expression} is either a
11763 @emph{simple string list expression} or a
11764 @emph{compound string list expression}.
11765
11766 A @emph{simple string list expression} is one of the following:
11767 @itemize @bullet
11768 @item A parenthesized list of zero or more string expressions,
11769 separated by commas
11770 @smallexample
11771    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11772    Empty_List := ();
11773 @end smallexample
11774 @item A string list-valued variable reference
11775 @item A string list-valued attribute reference
11776 @end itemize
11777
11778 @noindent
11779 A @emph{compound string list expression} is the concatenation (using
11780 @code{"&"}) of a simple string list expression and an expression.  Note that
11781 each term in a compound string list expression, except the first, may be
11782 either a string expression or a string list expression.
11783
11784 @smallexample @c projectfile
11785 @group
11786    File_Name_List := () & File_Name; --  One string in this list
11787    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11788    --  Two strings
11789    Big_List := File_Name_List & Extended_File_Name_List;
11790    --  Concatenation of two string lists: three strings
11791    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11792    --  Illegal: must start with a string list
11793 @end group
11794 @end smallexample
11795
11796 @node String Types
11797 @subsection String Types
11798
11799 @noindent
11800 A @emph{string type declaration} introduces a discrete set of string literals.
11801 If a string variable is declared to have this type, its value
11802 is restricted to the given set of literals.
11803
11804 Here is an example of a string type declaration:
11805
11806 @smallexample @c projectfile
11807    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11808 @end smallexample
11809
11810 @noindent
11811 Variables of a string type are called @emph{typed variables}; all other
11812 variables are called @emph{untyped variables}. Typed variables are
11813 particularly useful in @code{case} constructions, to support conditional
11814 attribute declarations.
11815 (@pxref{case Constructions}).
11816
11817 The string literals in the list are case sensitive and must all be different.
11818 They may include any graphic characters allowed in Ada, including spaces.
11819
11820 A string type may only be declared at the project level, not inside a package.
11821
11822 A string type may be referenced by its name if it has been declared in the same
11823 project file, or by an expanded name whose prefix is the name of the project
11824 in which it is declared.
11825
11826 @node Variables
11827 @subsection Variables
11828
11829 @noindent
11830 A variable may be declared at the project file level, or within a package.
11831 Here are some examples of variable declarations:
11832
11833 @smallexample @c projectfile
11834 @group
11835    This_OS : OS := external ("OS"); --  a typed variable declaration
11836    That_OS := "GNU/Linux";          --  an untyped variable declaration
11837 @end group
11838 @end smallexample
11839
11840 @noindent
11841 The syntax of a @emph{typed variable declaration} is identical to the Ada
11842 syntax for an object declaration. By contrast, the syntax of an untyped
11843 variable declaration is identical to an Ada assignment statement. In fact,
11844 variable declarations in project files have some of the characteristics of
11845 an assignment, in that successive declarations for the same variable are
11846 allowed. Untyped variable declarations do establish the expected kind of the
11847 variable (string or string list), and successive declarations for it must
11848 respect the initial kind.
11849
11850 @noindent
11851 A string variable declaration (typed or untyped) declares a variable
11852 whose value is a string. This variable may be used as a string expression.
11853 @smallexample @c projectfile
11854    File_Name       := "readme.txt";
11855    Saved_File_Name := File_Name & ".saved";
11856 @end smallexample
11857
11858 @noindent
11859 A string list variable declaration declares a variable whose value is a list
11860 of strings. The list may contain any number (zero or more) of strings.
11861
11862 @smallexample @c projectfile
11863    Empty_List := ();
11864    List_With_One_Element := ("^-gnaty^-gnaty^");
11865    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11866    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11867                  "pack2.ada", "util_.ada", "util.ada");
11868 @end smallexample
11869
11870 @noindent
11871 The same typed variable may not be declared more than once at project level,
11872 and it may not be declared more than once in any package; it is in effect
11873 a constant.
11874
11875 The same untyped variable may be declared several times. Declarations are
11876 elaborated in the order in which they appear, so  the new value replaces
11877 the old one, and any subsequent reference to the variable uses the new value.
11878 However, as noted above, if a variable has been declared as a string, all
11879 subsequent
11880 declarations must give it a string value. Similarly, if a variable has
11881 been declared as a string list, all subsequent declarations
11882 must give it a string list value.
11883
11884 A @emph{variable reference} may take several forms:
11885
11886 @itemize @bullet
11887 @item The simple variable name, for a variable in the current package (if any)
11888 or in the current project
11889 @item An expanded name, whose prefix is a context name.
11890 @end itemize
11891
11892 @noindent
11893 A @emph{context} may be one of the following:
11894
11895 @itemize @bullet
11896 @item The name of an existing package in the current project
11897 @item The name of an imported project of the current project
11898 @item The name of an ancestor project (i.e., a project extended by the current
11899 project, either directly or indirectly)
11900 @item An expanded name whose prefix is an imported/parent project name, and
11901 whose selector is a package name in that project.
11902 @end itemize
11903
11904 @noindent
11905 A variable reference may be used in an expression.
11906
11907 @node Attributes
11908 @subsection Attributes
11909
11910 @noindent
11911 A project (and its packages) may have @emph{attributes} that define
11912 the project's properties.  Some attributes have values that are strings;
11913 others have values that are string lists.
11914
11915 There are two categories of attributes: @emph{simple attributes}
11916 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11917
11918 Legal project attribute names, and attribute names for each legal package are
11919 listed below. Attributes names are case-insensitive.
11920
11921 The following attributes are defined on projects (all are simple attributes):
11922
11923 @multitable @columnfractions .4 .3
11924 @item @emph{Attribute Name}
11925 @tab @emph{Value}
11926 @item @code{Source_Files}
11927 @tab string list
11928 @item @code{Source_Dirs}
11929 @tab string list
11930 @item @code{Source_List_File}
11931 @tab string
11932 @item @code{Object_Dir}
11933 @tab string
11934 @item @code{Exec_Dir}
11935 @tab string
11936 @item @code{Locally_Removed_Files}
11937 @tab string list
11938 @item @code{Languages}
11939 @tab string list
11940 @item @code{Main}
11941 @tab string list
11942 @item @code{Library_Dir}
11943 @tab string
11944 @item @code{Library_Name}
11945 @tab string
11946 @item @code{Library_Kind}
11947 @tab string
11948 @item @code{Library_Version}
11949 @tab string
11950 @item @code{Library_Interface}
11951 @tab string
11952 @item @code{Library_Auto_Init}
11953 @tab string
11954 @item @code{Library_Options}
11955 @tab string list
11956 @item @code{Library_Src_Dir}
11957 @tab string
11958 @item @code{Library_ALI_Dir}
11959 @tab string
11960 @item @code{Library_GCC}
11961 @tab string
11962 @item @code{Library_Symbol_File}
11963 @tab string
11964 @item @code{Library_Symbol_Policy}
11965 @tab string
11966 @item @code{Library_Reference_Symbol_File}
11967 @tab string
11968 @item @code{Externally_Built}
11969 @tab string
11970 @end multitable
11971
11972 @noindent
11973 The following attributes are defined for package  @code{Naming}
11974 (@pxref{Naming Schemes}):
11975
11976 @multitable @columnfractions .4 .2 .2 .2
11977 @item Attribute Name @tab Category @tab Index @tab Value
11978 @item @code{Spec_Suffix}
11979 @tab associative array
11980 @tab language name
11981 @tab string
11982 @item @code{Body_Suffix}
11983 @tab associative array
11984 @tab language name
11985 @tab string
11986 @item @code{Separate_Suffix}
11987 @tab simple attribute
11988 @tab n/a
11989 @tab string
11990 @item @code{Casing}
11991 @tab simple attribute
11992 @tab n/a
11993 @tab string
11994 @item @code{Dot_Replacement}
11995 @tab simple attribute
11996 @tab n/a
11997 @tab string
11998 @item @code{Spec}
11999 @tab associative array
12000 @tab Ada unit name
12001 @tab string
12002 @item @code{Body}
12003 @tab associative array
12004 @tab Ada unit name
12005 @tab string
12006 @item @code{Specification_Exceptions}
12007 @tab associative array
12008 @tab language name
12009 @tab string list
12010 @item @code{Implementation_Exceptions}
12011 @tab associative array
12012 @tab language name
12013 @tab string list
12014 @end multitable
12015
12016 @noindent
12017 The following attributes are defined for packages @code{Builder},
12018 @code{Compiler}, @code{Binder},
12019 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12020 (@pxref{^Switches^Switches^ and Project Files}).
12021
12022 @multitable @columnfractions .4 .2 .2 .2
12023 @item Attribute Name @tab Category @tab Index @tab Value
12024 @item @code{^Default_Switches^Default_Switches^}
12025 @tab associative array
12026 @tab language name
12027 @tab string list
12028 @item @code{^Switches^Switches^}
12029 @tab associative array
12030 @tab file name
12031 @tab string list
12032 @end multitable
12033
12034 @noindent
12035 In addition, package @code{Compiler} has a single string attribute
12036 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12037 string attribute @code{Global_Configuration_Pragmas}.
12038
12039 @noindent
12040 Each simple attribute has a default value: the empty string (for string-valued
12041 attributes) and the empty list (for string list-valued attributes).
12042
12043 An attribute declaration defines a new value for an attribute.
12044
12045 Examples of simple attribute declarations:
12046
12047 @smallexample @c projectfile
12048    for Object_Dir use "objects";
12049    for Source_Dirs use ("units", "test/drivers");
12050 @end smallexample
12051
12052 @noindent
12053 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12054 attribute definition clause in Ada.
12055
12056 Attributes references may be appear in expressions.
12057 The general form for such a reference is @code{<entity>'<attribute>}:
12058 Associative array attributes are functions. Associative
12059 array attribute references must have an argument that is a string literal.
12060
12061 Examples are:
12062
12063 @smallexample @c projectfile
12064   project'Object_Dir
12065   Naming'Dot_Replacement
12066   Imported_Project'Source_Dirs
12067   Imported_Project.Naming'Casing
12068   Builder'^Default_Switches^Default_Switches^("Ada")
12069 @end smallexample
12070
12071 @noindent
12072 The prefix of an attribute may be:
12073 @itemize @bullet
12074 @item @code{project} for an attribute of the current project
12075 @item The name of an existing package of the current project
12076 @item The name of an imported project
12077 @item The name of a parent project that is extended by the current project
12078 @item An expanded name whose prefix is imported/parent project name,
12079       and whose selector is a package name
12080 @end itemize
12081
12082 @noindent
12083 Example:
12084 @smallexample @c projectfile
12085 @group
12086    project Prj is
12087      for Source_Dirs use project'Source_Dirs & "units";
12088      for Source_Dirs use project'Source_Dirs & "test/drivers"
12089    end Prj;
12090 @end group
12091 @end smallexample
12092
12093 @noindent
12094 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12095 has the default value: an empty string list. After this declaration,
12096 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12097 After the second attribute declaration @code{Source_Dirs} is a string list of
12098 two elements: @code{"units"} and @code{"test/drivers"}.
12099
12100 Note: this example is for illustration only. In practice,
12101 the project file would contain only one attribute declaration:
12102
12103 @smallexample @c projectfile
12104    for Source_Dirs use ("units", "test/drivers");
12105 @end smallexample
12106
12107 @node Associative Array Attributes
12108 @subsection Associative Array Attributes
12109
12110 @noindent
12111 Some attributes are defined as @emph{associative arrays}. An associative
12112 array may be regarded as a function that takes a string as a parameter
12113 and delivers a string or string list value as its result.
12114
12115 Here are some examples of single associative array attribute associations:
12116
12117 @smallexample @c projectfile
12118    for Body ("main") use "Main.ada";
12119    for ^Switches^Switches^ ("main.ada")
12120        use ("^-v^-v^",
12121             "^-gnatv^-gnatv^");
12122    for ^Switches^Switches^ ("main.ada")
12123             use Builder'^Switches^Switches^ ("main.ada")
12124               & "^-g^-g^";
12125 @end smallexample
12126
12127 @noindent
12128 Like untyped variables and simple attributes, associative array attributes
12129 may be declared several times. Each declaration supplies a new value for the
12130 attribute, and replaces the previous setting.
12131
12132 @noindent
12133 An associative array attribute may be declared as a full associative array
12134 declaration, with the value of the same attribute in an imported or extended
12135 project.
12136
12137 @smallexample @c projectfile
12138    package Builder is
12139       for Default_Switches use Default.Builder'Default_Switches;
12140    end Builder;
12141 @end smallexample
12142
12143 @noindent
12144 In this example, @code{Default} must be either a project imported by the
12145 current project, or the project that the current project extends. If the
12146 attribute is in a package (in this case, in package @code{Builder}), the same
12147 package needs to be specified.
12148
12149 @noindent
12150 A full associative array declaration replaces any other declaration for the
12151 attribute, including other full associative array declaration. Single
12152 associative array associations may be declare after a full associative
12153 declaration, modifying the value for a single association of the attribute.
12154
12155 @node case Constructions
12156 @subsection @code{case} Constructions
12157
12158 @noindent
12159 A @code{case} construction is used in a project file to effect conditional
12160 behavior.
12161 Here is a typical example:
12162
12163 @smallexample @c projectfile
12164 @group
12165 project MyProj is
12166    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12167
12168    OS : OS_Type := external ("OS", "GNU/Linux");
12169 @end group
12170
12171 @group
12172    package Compiler is
12173      case OS is
12174        when "GNU/Linux" | "Unix" =>
12175          for ^Default_Switches^Default_Switches^ ("Ada")
12176              use ("^-gnath^-gnath^");
12177        when "NT" =>
12178          for ^Default_Switches^Default_Switches^ ("Ada")
12179              use ("^-gnatP^-gnatP^");
12180        when others =>
12181      end case;
12182    end Compiler;
12183 end MyProj;
12184 @end group
12185 @end smallexample
12186
12187 @noindent
12188 The syntax of a @code{case} construction is based on the Ada case statement
12189 (although there is no @code{null} construction for empty alternatives).
12190
12191 The case expression must be a typed string variable.
12192 Each alternative comprises the reserved word @code{when}, either a list of
12193 literal strings separated by the @code{"|"} character or the reserved word
12194 @code{others},  and the @code{"=>"} token.
12195 Each literal string must belong to the string type that is the type of the
12196 case variable.
12197 An @code{others} alternative, if present, must occur last.
12198
12199 After each @code{=>}, there are zero or more constructions.  The only
12200 constructions allowed in a case construction are other case constructions and
12201 attribute declarations. String type declarations, variable declarations and
12202 package declarations are not allowed.
12203
12204 The value of the case variable is often given by an external reference
12205 (@pxref{External References in Project Files}).
12206
12207 @c ****************************************
12208 @c * Objects and Sources in Project Files *
12209 @c ****************************************
12210
12211 @node Objects and Sources in Project Files
12212 @section Objects and Sources in Project Files
12213
12214 @menu
12215 * Object Directory::
12216 * Exec Directory::
12217 * Source Directories::
12218 * Source File Names::
12219 @end menu
12220
12221 @noindent
12222 Each project has exactly one object directory and one or more source
12223 directories. The source directories must contain at least one source file,
12224 unless  the project file explicitly specifies that no source files are present
12225 (@pxref{Source File Names}).
12226
12227 @node Object Directory
12228 @subsection Object Directory
12229
12230 @noindent
12231 The object directory for a project is the directory containing the compiler's
12232 output (such as @file{ALI} files and object files) for the project's immediate
12233 sources.
12234
12235 The object directory is given by the value of the attribute @code{Object_Dir}
12236 in the project file.
12237
12238 @smallexample @c projectfile
12239    for Object_Dir use "objects";
12240 @end smallexample
12241
12242 @noindent
12243 The attribute @var{Object_Dir} has a string value, the path name of the object
12244 directory. The path name may be absolute or relative to the directory of the
12245 project file. This directory must already exist, and be readable and writable.
12246
12247 By default, when the attribute @code{Object_Dir} is not given an explicit value
12248 or when its value is the empty string, the object directory is the same as the
12249 directory containing the project file.
12250
12251 @node Exec Directory
12252 @subsection Exec Directory
12253
12254 @noindent
12255 The exec directory for a project is the directory containing the executables
12256 for the project's main subprograms.
12257
12258 The exec directory is given by the value of the attribute @code{Exec_Dir}
12259 in the project file.
12260
12261 @smallexample @c projectfile
12262    for Exec_Dir use "executables";
12263 @end smallexample
12264
12265 @noindent
12266 The attribute @var{Exec_Dir} has a string value, the path name of the exec
12267 directory. The path name may be absolute or relative to the directory of the
12268 project file. This directory must already exist, and be writable.
12269
12270 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12271 or when its value is the empty string, the exec directory is the same as the
12272 object directory of the project file.
12273
12274 @node Source Directories
12275 @subsection Source Directories
12276
12277 @noindent
12278 The source directories of a project are specified by the project file
12279 attribute @code{Source_Dirs}.
12280
12281 This attribute's value is a string list. If the attribute is not given an
12282 explicit value, then there is only one source directory, the one where the
12283 project file resides.
12284
12285 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12286 as in
12287
12288 @smallexample @c projectfile
12289     for Source_Dirs use ();
12290 @end smallexample
12291
12292 @noindent
12293 indicates that the project contains no source files.
12294
12295 Otherwise, each string in the string list designates one or more
12296 source directories.
12297
12298 @smallexample @c projectfile
12299    for Source_Dirs use ("sources", "test/drivers");
12300 @end smallexample
12301
12302 @noindent
12303 If a string in the list ends with @code{"/**"},  then the directory whose path
12304 name precedes the two asterisks, as well as all its subdirectories
12305 (recursively), are source directories.
12306
12307 @smallexample @c projectfile
12308    for Source_Dirs use ("/system/sources/**");
12309 @end smallexample
12310
12311 @noindent
12312 Here the directory @code{/system/sources} and all of its subdirectories
12313 (recursively) are source directories.
12314
12315 To specify that the source directories are the directory of the project file
12316 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12317 @smallexample @c projectfile
12318    for Source_Dirs use ("./**");
12319 @end smallexample
12320
12321 @noindent
12322 Each of the source directories must exist and be readable.
12323
12324 @node Source File Names
12325 @subsection Source File Names
12326
12327 @noindent
12328 In a project that contains source files, their names may be specified by the
12329 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12330 (a string). Source file names never include any directory information.
12331
12332 If the attribute @code{Source_Files} is given an explicit value, then each
12333 element of the list is a source file name.
12334
12335 @smallexample @c projectfile
12336    for Source_Files use ("main.adb");
12337    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12338 @end smallexample
12339
12340 @noindent
12341 If the attribute @code{Source_Files} is not given an explicit value,
12342 but the attribute @code{Source_List_File} is given a string value,
12343 then the source file names are contained in the text file whose path name
12344 (absolute or relative to the directory of the project file) is the
12345 value of the attribute @code{Source_List_File}.
12346
12347 Each line in the file that is not empty or is not a comment
12348 contains a source file name.
12349
12350 @smallexample @c projectfile
12351    for Source_List_File use "source_list.txt";
12352 @end smallexample
12353
12354 @noindent
12355 By default, if neither the attribute @code{Source_Files} nor the attribute
12356 @code{Source_List_File} is given an explicit value, then each file in the
12357 source directories that conforms to the project's naming scheme
12358 (@pxref{Naming Schemes}) is an immediate source of the project.
12359
12360 A warning is issued if both attributes @code{Source_Files} and
12361 @code{Source_List_File} are given explicit values. In this case, the attribute
12362 @code{Source_Files} prevails.
12363
12364 Each source file name must be the name of one existing source file
12365 in one of the source directories.
12366
12367 A @code{Source_Files} attribute whose value is an empty list
12368 indicates that there are no source files in the project.
12369
12370 If the order of the source directories is known statically, that is if
12371 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12372 be several files with the same source file name. In this case, only the file
12373 in the first directory is considered as an immediate source of the project
12374 file. If the order of the source directories is not known statically, it is
12375 an error to have several files with the same source file name.
12376
12377 Projects can be specified to have no Ada source
12378 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12379 list, or the @code{"Ada"} may be absent from @code{Languages}:
12380
12381 @smallexample @c projectfile
12382    for Source_Dirs use ();
12383    for Source_Files use ();
12384    for Languages use ("C", "C++");
12385 @end smallexample
12386
12387 @noindent
12388 Otherwise, a project must contain at least one immediate source.
12389
12390 Projects with no source files are useful as template packages
12391 (@pxref{Packages in Project Files}) for other projects; in particular to
12392 define a package @code{Naming} (@pxref{Naming Schemes}).
12393
12394 @c ****************************
12395 @c * Importing Projects *
12396 @c ****************************
12397
12398 @node  Importing Projects
12399 @section Importing Projects
12400 @cindex @code{ADA_PROJECT_PATH}
12401
12402 @noindent
12403 An immediate source of a project P may depend on source files that
12404 are neither immediate sources of P nor in the predefined library.
12405 To get this effect, P must @emph{import} the projects that contain the needed
12406 source files.
12407
12408 @smallexample @c projectfile
12409 @group
12410   with "project1", "utilities.gpr";
12411   with "/namings/apex.gpr";
12412   project Main is
12413     ...
12414 @end group
12415 @end smallexample
12416
12417 @noindent
12418 As can be seen in this example, the syntax for importing projects is similar
12419 to the syntax for importing compilation units in Ada. However, project files
12420 use literal strings instead of names, and the @code{with} clause identifies
12421 project files rather than packages.
12422
12423 Each literal string is the file name or path name (absolute or relative) of a
12424 project file. If a string corresponds to a file name, with no path or a
12425 relative path, then its location is determined by the @emph{project path}. The
12426 latter can be queried using @code{gnatls -v}. It contains:
12427
12428 @itemize @bullet
12429 @item
12430 In first position, the directory containing the current project file.
12431 @item
12432 In last position, the default project directory. This default project directory
12433 is part of the GNAT installation and is the standard place to install project
12434 files giving access to standard support libraries.
12435 @ifclear vms
12436 @ref{Installing a library}
12437 @end ifclear
12438
12439 @item
12440 In between, all the directories referenced in the
12441 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12442 @end itemize
12443
12444 @noindent
12445 If a relative pathname is used, as in
12446
12447 @smallexample @c projectfile
12448   with "tests/proj";
12449 @end smallexample
12450
12451 @noindent
12452 then the full path for the project is constructed by concatenating this
12453 relative path to those in the project path, in order, until a matching file is
12454 found. Any symbolic link will be fully resolved in the directory of the
12455 importing project file before the imported project file is examined.
12456
12457 If the @code{with}'ed project file name does not have an extension,
12458 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12459 then the file name as specified in the @code{with} clause (no extension) will
12460 be used. In the above example, if a file @code{project1.gpr} is found, then it
12461 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12462 then it will be used; if neither file exists, this is an error.
12463
12464 A warning is issued if the name of the project file does not match the
12465 name of the project; this check is case insensitive.
12466
12467 Any source file that is an immediate source of the imported project can be
12468 used by the immediate sources of the importing project, transitively. Thus
12469 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12470 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12471 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12472 because if and when @code{B} ceases to import @code{C}, some sources in
12473 @code{A} will no longer compile.
12474
12475 A side effect of this capability is that normally cyclic dependencies are not
12476 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12477 is not allowed to import @code{A}. However, there are cases when cyclic
12478 dependencies would be beneficial. For these cases, another form of import
12479 between projects exists, the @code{limited with}: a project @code{A} that
12480 imports a project @code{B} with a straight @code{with} may also be imported,
12481 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12482 to @code{A} include at least one @code{limited with}.
12483
12484 @smallexample @c 0projectfile
12485 with "../b/b.gpr";
12486 with "../c/c.gpr";
12487 project A is
12488 end A;
12489
12490 limited with "../a/a.gpr";
12491 project B is
12492 end B;
12493
12494 with "../d/d.gpr";
12495 project C is
12496 end C;
12497
12498 limited with "../a/a.gpr";
12499 project D is
12500 end D;
12501 @end smallexample
12502
12503 @noindent
12504 In the above legal example, there are two project cycles:
12505 @itemize @bullet
12506 @item A-> B-> A
12507 @item A -> C -> D -> A
12508 @end itemize
12509
12510 @noindent
12511 In each of these cycle there is one @code{limited with}: import of @code{A}
12512 from @code{B} and import of @code{A} from @code{D}.
12513
12514 The difference between straight @code{with} and @code{limited with} is that
12515 the name of a project imported with a @code{limited with} cannot be used in the
12516 project that imports it. In particular, its packages cannot be renamed and
12517 its variables cannot be referred to.
12518
12519 An exception to the above rules for @code{limited with} is that for the main
12520 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12521 @code{limited with} is equivalent to a straight @code{with}. For example,
12522 in the example above, projects @code{B} and @code{D} could not be main
12523 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12524 each have a @code{limited with} that is the only one in a cycle of importing
12525 projects.
12526
12527 @c *********************
12528 @c * Project Extension *
12529 @c *********************
12530
12531 @node Project Extension
12532 @section Project Extension
12533
12534 @noindent
12535 During development of a large system, it is sometimes necessary to use
12536 modified versions of some of the source files, without changing the original
12537 sources. This can be achieved through the @emph{project extension} facility.
12538
12539 @smallexample @c projectfile
12540    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12541 @end smallexample
12542
12543 @noindent
12544 A project extension declaration introduces an extending project
12545 (the @emph{child}) and a project being extended (the @emph{parent}).
12546
12547 By default, a child project inherits all the sources of its parent.
12548 However, inherited sources can be overridden: a unit in a parent is hidden
12549 by a unit of the same name in the child.
12550
12551 Inherited sources are considered to be sources (but not immediate sources)
12552 of the child project; see @ref{Project File Syntax}.
12553
12554 An inherited source file retains any switches specified in the parent project.
12555
12556 For example if the project @code{Utilities} contains the specification and the
12557 body of an Ada package @code{Util_IO}, then the project
12558 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12559 The original body of @code{Util_IO} will not be considered in program builds.
12560 However, the package specification will still be found in the project
12561 @code{Utilities}.
12562
12563 A child project can have only one parent but it may import any number of other
12564 projects.
12565
12566 A project is not allowed to import directly or indirectly at the same time a
12567 child project and any of its ancestors.
12568
12569 @c *******************************
12570 @c * Project Hierarchy Extension *
12571 @c *******************************
12572
12573 @node Project Hierarchy Extension
12574 @section Project Hierarchy Extension
12575
12576 @noindent
12577 When extending a large system spanning multiple projects, it is often
12578 inconvenient to extend every project in the hierarchy that is impacted by a
12579 small change introduced. In such cases, it is possible to create a virtual
12580 extension of entire hierarchy using @code{extends all} relationship.
12581
12582 When the project is extended using @code{extends all} inheritance, all projects
12583 that are imported by it, both directly and indirectly, are considered virtually
12584 extended. That is, the Project Manager creates "virtual projects"
12585 that extend every project in the hierarchy; all these virtual projects have
12586 no sources of their own and have as object directory the object directory of
12587 the root of "extending all" project.
12588
12589 It is possible to explicitly extend one or more projects in the hierarchy
12590 in order to modify the sources. These extending projects must be imported by
12591 the "extending all" project, which will replace the corresponding virtual
12592 projects with the explicit ones.
12593
12594 When building such a project hierarchy extension, the Project Manager will
12595 ensure that both modified sources and sources in virtual extending projects
12596 that depend on them, are recompiled.
12597
12598 By means of example, consider the following hierarchy of projects.
12599
12600 @enumerate
12601 @item
12602 project A, containing package P1
12603 @item
12604 project B importing A and containing package P2 which depends on P1
12605 @item
12606 project C importing B and containing package P3 which depends on P2
12607 @end enumerate
12608
12609 @noindent
12610 We want to modify packages P1 and P3.
12611
12612 This project hierarchy will need to be extended as follows:
12613
12614 @enumerate
12615 @item
12616 Create project A1 that extends A, placing modified P1 there:
12617
12618 @smallexample @c 0projectfile
12619 project A1 extends "(...)/A" is
12620 end A1;
12621 @end smallexample
12622
12623 @item
12624 Create project C1 that "extends all" C and imports A1, placing modified
12625 P3 there:
12626
12627 @smallexample @c 0projectfile
12628 with "(...)/A1";
12629 project C1 extends all "(...)/C" is
12630 end C1;
12631 @end smallexample
12632 @end enumerate
12633
12634 When you build project C1, your entire modified project space will be
12635 recompiled, including the virtual project B1 that has been impacted by the
12636 "extending all" inheritance of project C.
12637
12638 Note that if a Library Project in the hierarchy is virtually extended,
12639 the virtual project that extends the Library Project is not a Library Project.
12640
12641 @c ****************************************
12642 @c * External References in Project Files *
12643 @c ****************************************
12644
12645 @node  External References in Project Files
12646 @section External References in Project Files
12647
12648 @noindent
12649 A project file may contain references to external variables; such references
12650 are called @emph{external references}.
12651
12652 An external variable is either defined as part of the environment (an
12653 environment variable in Unix, for example) or else specified on the command
12654 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12655 If both, then the command line value is used.
12656
12657 The value of an external reference is obtained by means of the built-in
12658 function @code{external}, which returns a string value.
12659 This function has two forms:
12660 @itemize @bullet
12661 @item @code{external (external_variable_name)}
12662 @item @code{external (external_variable_name, default_value)}
12663 @end itemize
12664
12665 @noindent
12666 Each parameter must be a string literal.  For example:
12667
12668 @smallexample @c projectfile
12669    external ("USER")
12670    external ("OS", "GNU/Linux")
12671 @end smallexample
12672
12673 @noindent
12674 In the form with one parameter, the function returns the value of
12675 the external variable given as parameter. If this name is not present in the
12676 environment, the function returns an empty string.
12677
12678 In the form with two string parameters, the second argument is
12679 the value returned when the variable given as the first argument is not
12680 present in the environment. In the example above, if @code{"OS"} is not
12681 the name of ^an environment variable^a logical name^ and is not passed on
12682 the command line, then the returned value is @code{"GNU/Linux"}.
12683
12684 An external reference may be part of a string expression or of a string
12685 list expression, and can therefore appear in a variable declaration or
12686 an attribute declaration.
12687
12688 @smallexample @c projectfile
12689 @group
12690    type Mode_Type is ("Debug", "Release");
12691    Mode : Mode_Type := external ("MODE");
12692    case Mode is
12693      when "Debug" =>
12694         ...
12695 @end group
12696 @end smallexample
12697
12698 @c *****************************
12699 @c * Packages in Project Files *
12700 @c *****************************
12701
12702 @node  Packages in Project Files
12703 @section Packages in Project Files
12704
12705 @noindent
12706 A @emph{package} defines the settings for project-aware tools within a
12707 project.
12708 For each such tool one can declare a package; the names for these
12709 packages are preset (@pxref{Packages}).
12710 A package may contain variable declarations, attribute declarations, and case
12711 constructions.
12712
12713 @smallexample @c projectfile
12714 @group
12715    project Proj is
12716       package Builder is  -- used by gnatmake
12717          for ^Default_Switches^Default_Switches^ ("Ada")
12718              use ("^-v^-v^",
12719                   "^-g^-g^");
12720       end Builder;
12721    end Proj;
12722 @end group
12723 @end smallexample
12724
12725 @noindent
12726 The syntax of package declarations mimics that of package in Ada.
12727
12728 Most of the packages have an attribute
12729 @code{^Default_Switches^Default_Switches^}.
12730 This attribute is an associative array, and its value is a string list.
12731 The index of the associative array is the name of a programming language (case
12732 insensitive). This attribute indicates the ^switch^switch^
12733 or ^switches^switches^ to be used
12734 with the corresponding tool.
12735
12736 Some packages also have another attribute, @code{^Switches^Switches^},
12737 an associative array whose value is a string list.
12738 The index is the name of a source file.
12739 This attribute indicates the ^switch^switch^
12740 or ^switches^switches^ to be used by the corresponding
12741 tool when dealing with this specific file.
12742
12743 Further information on these ^switch^switch^-related attributes is found in
12744 @ref{^Switches^Switches^ and Project Files}.
12745
12746 A package may be declared as a @emph{renaming} of another package; e.g., from
12747 the project file for an imported project.
12748
12749 @smallexample @c projectfile
12750 @group
12751   with "/global/apex.gpr";
12752   project Example is
12753     package Naming renames Apex.Naming;
12754     ...
12755   end Example;
12756 @end group
12757 @end smallexample
12758
12759 @noindent
12760 Packages that are renamed in other project files often come from project files
12761 that have no sources: they are just used as templates. Any modification in the
12762 template will be reflected automatically in all the project files that rename
12763 a package from the template.
12764
12765 In addition to the tool-oriented packages, you can also declare a package
12766 named @code{Naming} to establish specialized source file naming conventions
12767 (@pxref{Naming Schemes}).
12768
12769 @c ************************************
12770 @c * Variables from Imported Projects *
12771 @c ************************************
12772
12773 @node Variables from Imported Projects
12774 @section Variables from Imported Projects
12775
12776 @noindent
12777 An attribute or variable defined in an imported or parent project can
12778 be used in expressions in the importing / extending project.
12779 Such an attribute or variable is denoted by an expanded name whose prefix
12780 is either the name of the project or the expanded name of a package within
12781 a project.
12782
12783 @smallexample @c projectfile
12784 @group
12785   with "imported";
12786   project Main extends "base" is
12787      Var1 := Imported.Var;
12788      Var2 := Base.Var & ".new";
12789 @end group
12790
12791 @group
12792      package Builder is
12793         for ^Default_Switches^Default_Switches^ ("Ada")
12794             use Imported.Builder.Ada_^Switches^Switches^ &
12795                 "^-gnatg^-gnatg^" &
12796                 "^-v^-v^";
12797      end Builder;
12798 @end group
12799
12800 @group
12801      package Compiler is
12802         for ^Default_Switches^Default_Switches^ ("Ada")
12803             use Base.Compiler.Ada_^Switches^Switches^;
12804      end Compiler;
12805   end Main;
12806 @end group
12807 @end smallexample
12808
12809 @noindent
12810 In this example:
12811
12812 @itemize @bullet
12813 @item
12814 The value of @code{Var1} is a copy of the variable @code{Var} defined
12815 in the project file @file{"imported.gpr"}
12816 @item
12817 the value of @code{Var2} is a copy of the value of variable @code{Var}
12818 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12819 @item
12820 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12821 @code{Builder} is a string list that includes in its value a copy of the value
12822 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12823 in project file @file{imported.gpr} plus two new elements:
12824 @option{"^-gnatg^-gnatg^"}
12825 and @option{"^-v^-v^"};
12826 @item
12827 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12828 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12829 defined in the @code{Compiler} package in project file @file{base.gpr},
12830 the project being extended.
12831 @end itemize
12832
12833 @c ******************
12834 @c * Naming Schemes *
12835 @c ******************
12836
12837 @node  Naming Schemes
12838 @section Naming Schemes
12839
12840 @noindent
12841 Sometimes an Ada software system is ported from a foreign compilation
12842 environment to GNAT, and the file names do not use the default GNAT
12843 conventions. Instead of changing all the file names (which for a variety
12844 of reasons might not be possible), you can define the relevant file
12845 naming scheme in the @code{Naming} package in your project file.
12846
12847 @noindent
12848 Note that the use of pragmas described in
12849 @ref{Alternative File Naming Schemes} by mean of a configuration
12850 pragmas file is not supported when using project files. You must use
12851 the features described in this paragraph. You can however use specify
12852 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12853
12854 @ifclear vms
12855 For example, the following
12856 package models the Apex file naming rules:
12857
12858 @smallexample @c projectfile
12859 @group
12860   package Naming is
12861     for Casing               use "lowercase";
12862     for Dot_Replacement      use ".";
12863     for Spec_Suffix ("Ada")  use ".1.ada";
12864     for Body_Suffix ("Ada")  use ".2.ada";
12865   end Naming;
12866 @end group
12867 @end smallexample
12868 @end ifclear
12869
12870 @ifset vms
12871 For example, the following package models the HP Ada file naming rules:
12872
12873 @smallexample @c projectfile
12874 @group
12875   package Naming is
12876     for Casing               use "lowercase";
12877     for Dot_Replacement      use "__";
12878     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12879     for Body_Suffix ("Ada")  use ".^ada^ada^";
12880   end Naming;
12881 @end group
12882 @end smallexample
12883
12884 @noindent
12885 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12886 names in lower case)
12887 @end ifset
12888
12889 @noindent
12890 You can define the following attributes in package @code{Naming}:
12891
12892 @table @code
12893
12894 @item @var{Casing}
12895 This must be a string with one of the three values @code{"lowercase"},
12896 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12897
12898 @noindent
12899 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12900
12901 @item @var{Dot_Replacement}
12902 This must be a string whose value satisfies the following conditions:
12903
12904 @itemize @bullet
12905 @item It must not be empty
12906 @item It cannot start or end with an alphanumeric character
12907 @item It cannot be a single underscore
12908 @item It cannot start with an underscore followed by an alphanumeric
12909 @item It cannot contain a dot @code{'.'} except if the entire string
12910 is @code{"."}
12911 @end itemize
12912
12913 @noindent
12914 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12915
12916 @item @var{Spec_Suffix}
12917 This is an associative array (indexed by the programming language name, case
12918 insensitive) whose value is a string that must satisfy the following
12919 conditions:
12920
12921 @itemize @bullet
12922 @item It must not be empty
12923 @item It must include at least one dot
12924 @end itemize
12925 @noindent
12926 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12927 @code{"^.ads^.ADS^"}.
12928
12929 @item @var{Body_Suffix}
12930 This is an associative array (indexed by the programming language name, case
12931 insensitive) whose value is a string that must satisfy the following
12932 conditions:
12933
12934 @itemize @bullet
12935 @item It must not be empty
12936 @item It must include at least one dot
12937 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12938 @end itemize
12939 @noindent
12940 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12941 @code{"^.adb^.ADB^"}.
12942
12943 @item @var{Separate_Suffix}
12944 This must be a string whose value satisfies the same conditions as
12945 @code{Body_Suffix}.
12946
12947 @noindent
12948 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12949 value as @code{Body_Suffix ("Ada")}.
12950
12951 @item @var{Spec}
12952 @noindent
12953 You can use the associative array attribute @code{Spec}  to define
12954 the source file name for an individual Ada compilation unit's spec. The array
12955 index must be a string literal that identifies the Ada unit (case insensitive).
12956 The value of this attribute must be a string that identifies the file that
12957 contains this unit's spec (case sensitive or insensitive depending on the
12958 operating system).
12959
12960 @smallexample @c projectfile
12961    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12962 @end smallexample
12963
12964 @item @var{Body}
12965
12966 You can use the associative array attribute @code{Body} to
12967 define the source file name for an individual Ada compilation unit's body
12968 (possibly a subunit).  The array index must be a string literal that identifies
12969 the Ada unit (case insensitive).  The value of this attribute must be a string
12970 that identifies the file that contains this unit's body or subunit (case
12971 sensitive or insensitive depending on the operating system).
12972
12973 @smallexample @c projectfile
12974    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12975 @end smallexample
12976 @end table
12977
12978 @c ********************
12979 @c * Library Projects *
12980 @c ********************
12981
12982 @node Library Projects
12983 @section Library Projects
12984
12985 @noindent
12986 @emph{Library projects} are projects whose object code is placed in a library.
12987 (Note that this facility is not yet supported on all platforms)
12988
12989 To create a library project, you need to define in its project file
12990 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12991 Additionally, you may define other library-related attributes such as
12992 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12993 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12994
12995 The @code{Library_Name} attribute has a string value. There is no restriction
12996 on the name of a library. It is the responsibility of the developer to
12997 choose a name that will be accepted by the platform. It is recommended to
12998 choose names that could be Ada identifiers; such names are almost guaranteed
12999 to be acceptable on all platforms.
13000
13001 The @code{Library_Dir} attribute has a string value that designates the path
13002 (absolute or relative) of the directory where the library will reside.
13003 It must designate an existing directory, and this directory must be writable,
13004 different from the project's object directory and from any source directory
13005 in the project tree.
13006
13007 If both @code{Library_Name} and @code{Library_Dir} are specified and
13008 are legal, then the project file defines a library project.  The optional
13009 library-related attributes are checked only for such project files.
13010
13011 The @code{Library_Kind} attribute has a string value that must be one of the
13012 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13013 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13014 attribute is not specified, the library is a static library, that is
13015 an archive of object files that can be potentially linked into a
13016 static executable. Otherwise, the library may be dynamic or
13017 relocatable, that is a library that is loaded only at the start of execution.
13018
13019 If you need to build both a static and a dynamic library, you should use two
13020 different object directories, since in some cases some extra code needs to
13021 be generated for the latter. For such cases, it is recommended to either use
13022 two different project files, or a single one which uses external variables
13023 to indicate what kind of library should be build.
13024
13025 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13026 directory where the ALI files of the library will be copied. When it is
13027 not specified, the ALI files are copied ti the directory specified in
13028 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13029 must be writable and different from the project's object directory and from
13030 any source directory in the project tree.
13031
13032 The @code{Library_Version} attribute has a string value whose interpretation
13033 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13034 used only for dynamic/relocatable libraries as the internal name of the
13035 library (the @code{"soname"}). If the library file name (built from the
13036 @code{Library_Name}) is different from the @code{Library_Version}, then the
13037 library file will be a symbolic link to the actual file whose name will be
13038 @code{Library_Version}.
13039
13040 Example (on Unix):
13041
13042 @smallexample @c projectfile
13043 @group
13044 project Plib is
13045
13046    Version := "1";
13047
13048    for Library_Dir use "lib_dir";
13049    for Library_Name use "dummy";
13050    for Library_Kind use "relocatable";
13051    for Library_Version use "libdummy.so." & Version;
13052
13053 end Plib;
13054 @end group
13055 @end smallexample
13056
13057 @noindent
13058 Directory @file{lib_dir} will contain the internal library file whose name
13059 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13060 @file{libdummy.so.1}.
13061
13062 When @command{gnatmake} detects that a project file
13063 is a library project file, it will check all immediate sources of the project
13064 and rebuild the library if any of the sources have been recompiled.
13065
13066 Standard project files can import library project files. In such cases,
13067 the libraries will only be rebuilt if some of its sources are recompiled
13068 because they are in the closure of some other source in an importing project.
13069 Sources of the library project files that are not in such a closure will
13070 not be checked, unless the full library is checked, because one of its sources
13071 needs to be recompiled.
13072
13073 For instance, assume the project file @code{A} imports the library project file
13074 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13075 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13076 @file{l2.ads}, @file{l2.adb}.
13077
13078 If @file{l1.adb} has been modified, then the library associated with @code{L}
13079 will be rebuilt when compiling all the immediate sources of @code{A} only
13080 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13081 @code{"with L1;"}.
13082
13083 To be sure that all the sources in the library associated with @code{L} are
13084 up to date, and that all the sources of project @code{A} are also up to date,
13085 the following two commands needs to be used:
13086
13087 @smallexample
13088 gnatmake -Pl.gpr
13089 gnatmake -Pa.gpr
13090 @end smallexample
13091
13092 When a library is built or rebuilt, an attempt is made first to delete all
13093 files in the library directory.
13094 All @file{ALI} files will also be copied from the object directory to the
13095 library directory. To build executables, @command{gnatmake} will use the
13096 library rather than the individual object files.
13097
13098 @ifclear vms
13099 It is also possible to create library project files for third-party libraries
13100 that are precompiled and cannot be compiled locally thanks to the
13101 @code{externally_built} attribute. (See @ref{Installing a library}).
13102 @end ifclear
13103
13104 @c *******************************
13105 @c * Stand-alone Library Projects *
13106 @c *******************************
13107
13108 @node Stand-alone Library Projects
13109 @section Stand-alone Library Projects
13110
13111 @noindent
13112 A Stand-alone Library is a library that contains the necessary code to
13113 elaborate the Ada units that are included in the library. A Stand-alone
13114 Library is suitable to be used in an executable when the main is not
13115 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13116 subprogram.
13117
13118 A Stand-alone Library Project is a Library Project where the library is
13119 a Stand-alone Library.
13120
13121 To be a Stand-alone Library Project, in addition to the two attributes
13122 that make a project a Library Project (@code{Library_Name} and
13123 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13124 @code{Library_Interface} must be defined.
13125
13126 @smallexample @c projectfile
13127 @group
13128    for Library_Dir use "lib_dir";
13129    for Library_Name use "dummy";
13130    for Library_Interface use ("int1", "int1.child");
13131 @end group
13132 @end smallexample
13133
13134 Attribute @code{Library_Interface} has a non empty string list value,
13135 each string in the list designating a unit contained in an immediate source
13136 of the project file.
13137
13138 When a Stand-alone Library is built, first the binder is invoked to build
13139 a package whose name depends on the library name
13140 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13141 This binder-generated package includes initialization and
13142 finalization procedures whose
13143 names depend on the library name (dummyinit and dummyfinal in the example
13144 above). The object corresponding to this package is included in the library.
13145
13146 A dynamic or relocatable Stand-alone Library is automatically initialized
13147 if automatic initialization of Stand-alone Libraries is supported on the
13148 platform and if attribute @code{Library_Auto_Init} is not specified or
13149 is specified with the value "true". A static Stand-alone Library is never
13150 automatically initialized.
13151
13152 Single string attribute @code{Library_Auto_Init} may be specified with only
13153 two possible values: "false" or "true" (case-insensitive). Specifying
13154 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13155 initialization of dynamic or relocatable libraries.
13156
13157 When a non automatically initialized Stand-alone Library is used
13158 in an executable, its initialization procedure must be called before
13159 any service of the library is used.
13160 When the main subprogram is in Ada, it may mean that the initialization
13161 procedure has to be called during elaboration of another package.
13162
13163 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13164 (those that are listed in attribute @code{Library_Interface}) are copied to
13165 the Library Directory. As a consequence, only the Interface Units may be
13166 imported from Ada units outside of the library. If other units are imported,
13167 the binding phase will fail.
13168
13169 When a Stand-Alone Library is bound, the switches that are specified in
13170 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13171 used in the call to @command{gnatbind}.
13172
13173 The string list attribute @code{Library_Options} may be used to specified
13174 additional switches to the call to @command{gcc} to link the library.
13175
13176 The attribute @code{Library_Src_Dir}, may be specified for a
13177 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13178 single string value. Its value must be the path (absolute or relative to the
13179 project directory) of an existing directory. This directory cannot be the
13180 object directory or one of the source directories, but it can be the same as
13181 the library directory. The sources of the Interface
13182 Units of the library, necessary to an Ada client of the library, will be
13183 copied to the designated directory, called Interface Copy directory.
13184 These sources includes the specs of the Interface Units, but they may also
13185 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13186 are used, or when there is a generic units in the spec. Before the sources
13187 are copied to the Interface Copy directory, an attempt is made to delete all
13188 files in the Interface Copy directory.
13189
13190 @c *************************************
13191 @c * Switches Related to Project Files *
13192 @c *************************************
13193 @node Switches Related to Project Files
13194 @section Switches Related to Project Files
13195
13196 @noindent
13197 The following switches are used by GNAT tools that support project files:
13198
13199 @table @option
13200
13201 @item ^-P^/PROJECT_FILE=^@var{project}
13202 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
13203 Indicates the name of a project file. This project file will be parsed with
13204 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13205 if any, and using the external references indicated
13206 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13207 @ifclear vms
13208 There may zero, one or more spaces between @option{-P} and @var{project}.
13209 @end ifclear
13210
13211 @noindent
13212 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13213
13214 @noindent
13215 Since the Project Manager parses the project file only after all the switches
13216 on the command line are checked, the order of the switches
13217 @option{^-P^/PROJECT_FILE^},
13218 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13219 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13220
13221 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13222 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
13223 Indicates that external variable @var{name} has the value @var{value}.
13224 The Project Manager will use this value for occurrences of
13225 @code{external(name)} when parsing the project file.
13226
13227 @ifclear vms
13228 @noindent
13229 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13230 put between quotes.
13231 @smallexample
13232   -XOS=NT
13233   -X"user=John Doe"
13234 @end smallexample
13235 @end ifclear
13236
13237 @noindent
13238 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13239 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13240 @var{name}, only the last one is used.
13241
13242 @noindent
13243 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13244 takes precedence over the value of the same name in the environment.
13245
13246 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13247 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13248 @c Previous line uses code vs option command, to stay less than 80 chars
13249 Indicates the verbosity of the parsing of GNAT project files.
13250
13251 @ifclear vms
13252 @option{-vP0} means Default;
13253 @option{-vP1} means Medium;
13254 @option{-vP2} means High.
13255 @end ifclear
13256
13257 @ifset vms
13258 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13259 HIGH.
13260 @end ifset
13261
13262 @noindent
13263 The default is ^Default^DEFAULT^: no output for syntactically correct
13264 project files.
13265 @noindent
13266 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13267 only the last one is used.
13268
13269 @end table
13270
13271 @c **********************************
13272 @c * Tools Supporting Project Files *
13273 @c **********************************
13274
13275 @node  Tools Supporting Project Files
13276 @section Tools Supporting Project Files
13277
13278 @menu
13279 * gnatmake and Project Files::
13280 * The GNAT Driver and Project Files::
13281 @ifclear vms
13282 * Glide and Project Files::
13283 @end ifclear
13284 @end menu
13285
13286 @node gnatmake and Project Files
13287 @subsection gnatmake and Project Files
13288
13289 @noindent
13290 This section covers several topics related to @command{gnatmake} and
13291 project files: defining ^switches^switches^ for @command{gnatmake}
13292 and for the tools that it invokes; specifying configuration pragmas;
13293 the use of the @code{Main} attribute; building and rebuilding library project
13294 files.
13295
13296 @menu
13297 * ^Switches^Switches^ and Project Files::
13298 * Specifying Configuration Pragmas::
13299 * Project Files and Main Subprograms::
13300 * Library Project Files::
13301 @end menu
13302
13303 @node ^Switches^Switches^ and Project Files
13304 @subsubsection ^Switches^Switches^ and Project Files
13305
13306 @ifset vms
13307 It is not currently possible to specify VMS style qualifiers in the project
13308 files; only Unix style ^switches^switches^ may be specified.
13309 @end ifset
13310
13311 @noindent
13312 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13313 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13314 attribute, a @code{^Switches^Switches^} attribute, or both;
13315 as their names imply, these ^switch^switch^-related
13316 attributes affect the ^switches^switches^ that are used for each of these GNAT
13317 components when
13318 @command{gnatmake} is invoked.  As will be explained below, these
13319 component-specific ^switches^switches^ precede
13320 the ^switches^switches^ provided on the @command{gnatmake} command line.
13321
13322 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13323 array indexed by language name (case insensitive) whose value is a string list.
13324 For example:
13325
13326 @smallexample @c projectfile
13327 @group
13328 package Compiler is
13329   for ^Default_Switches^Default_Switches^ ("Ada")
13330       use ("^-gnaty^-gnaty^",
13331            "^-v^-v^");
13332 end Compiler;
13333 @end group
13334 @end smallexample
13335
13336 @noindent
13337 The @code{^Switches^Switches^} attribute is also an associative array,
13338 indexed by a file name (which may or may not be case sensitive, depending
13339 on the operating system) whose value is a string list.  For example:
13340
13341 @smallexample @c projectfile
13342 @group
13343 package Builder is
13344    for ^Switches^Switches^ ("main1.adb")
13345        use ("^-O2^-O2^");
13346    for ^Switches^Switches^ ("main2.adb")
13347        use ("^-g^-g^");
13348 end Builder;
13349 @end group
13350 @end smallexample
13351
13352 @noindent
13353 For the @code{Builder} package, the file names must designate source files
13354 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
13355 file names must designate @file{ALI} or source files for main subprograms.
13356 In each case just the file name without an explicit extension is acceptable.
13357
13358 For each tool used in a program build (@command{gnatmake}, the compiler, the
13359 binder, and the linker), the corresponding package @dfn{contributes} a set of
13360 ^switches^switches^ for each file on which the tool is invoked, based on the
13361 ^switch^switch^-related attributes defined in the package.
13362 In particular, the ^switches^switches^
13363 that each of these packages contributes for a given file @var{f} comprise:
13364
13365 @itemize @bullet
13366 @item
13367 the value of attribute @code{^Switches^Switches^ (@var{f})},
13368 if it is specified in the package for the given file,
13369 @item
13370 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13371 if it is specified in the package.
13372 @end itemize
13373
13374 @noindent
13375 If neither of these attributes is defined in the package, then the package does
13376 not contribute any ^switches^switches^ for the given file.
13377
13378 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13379 two sets, in the following order: those contributed for the file
13380 by the @code{Builder} package;
13381 and the switches passed on the command line.
13382
13383 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13384 the ^switches^switches^ passed to the tool comprise three sets,
13385 in the following order:
13386
13387 @enumerate
13388 @item
13389 the applicable ^switches^switches^ contributed for the file
13390 by the @code{Builder} package in the project file supplied on the command line;
13391
13392 @item
13393 those contributed for the file by the package (in the relevant project file --
13394 see below) corresponding to the tool; and
13395
13396 @item
13397 the applicable switches passed on the command line.
13398 @end enumerate
13399
13400 @noindent
13401 The term @emph{applicable ^switches^switches^} reflects the fact that
13402 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13403 tools, depending on the individual ^switch^switch^.
13404
13405 @command{gnatmake} may invoke the compiler on source files from different
13406 projects. The Project Manager will use the appropriate project file to
13407 determine the @code{Compiler} package for each source file being compiled.
13408 Likewise for the @code{Binder} and @code{Linker} packages.
13409
13410 As an example, consider the following package in a project file:
13411
13412 @smallexample @c projectfile
13413 @group
13414 project Proj1 is
13415    package Compiler is
13416       for ^Default_Switches^Default_Switches^ ("Ada")
13417           use ("^-g^-g^");
13418       for ^Switches^Switches^ ("a.adb")
13419           use ("^-O1^-O1^");
13420       for ^Switches^Switches^ ("b.adb")
13421           use ("^-O2^-O2^",
13422                "^-gnaty^-gnaty^");
13423    end Compiler;
13424 end Proj1;
13425 @end group
13426 @end smallexample
13427
13428 @noindent
13429 If @command{gnatmake} is invoked with this project file, and it needs to
13430 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13431 @file{a.adb} will be compiled with the ^switch^switch^
13432 @option{^-O1^-O1^},
13433 @file{b.adb} with ^switches^switches^
13434 @option{^-O2^-O2^}
13435 and @option{^-gnaty^-gnaty^},
13436 and @file{c.adb} with @option{^-g^-g^}.
13437
13438 The following example illustrates the ordering of the ^switches^switches^
13439 contributed by different packages:
13440
13441 @smallexample @c projectfile
13442 @group
13443 project Proj2 is
13444    package Builder is
13445       for ^Switches^Switches^ ("main.adb")
13446           use ("^-g^-g^",
13447                "^-O1^-)1^",
13448                "^-f^-f^");
13449    end Builder;
13450 @end group
13451
13452 @group
13453    package Compiler is
13454       for ^Switches^Switches^ ("main.adb")
13455           use ("^-O2^-O2^");
13456    end Compiler;
13457 end Proj2;
13458 @end group
13459 @end smallexample
13460
13461 @noindent
13462 If you issue the command:
13463
13464 @smallexample
13465     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13466 @end smallexample
13467
13468 @noindent
13469 then the compiler will be invoked on @file{main.adb} with the following
13470 sequence of ^switches^switches^
13471
13472 @smallexample
13473    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13474 @end smallexample
13475
13476 with the last @option{^-O^-O^}
13477 ^switch^switch^ having precedence over the earlier ones;
13478 several other ^switches^switches^
13479 (such as @option{^-c^-c^}) are added implicitly.
13480
13481 The ^switches^switches^
13482 @option{^-g^-g^}
13483 and @option{^-O1^-O1^} are contributed by package
13484 @code{Builder},  @option{^-O2^-O2^} is contributed
13485 by the package @code{Compiler}
13486 and @option{^-O0^-O0^} comes from the command line.
13487
13488 The @option{^-g^-g^}
13489 ^switch^switch^ will also be passed in the invocation of
13490 @command{Gnatlink.}
13491
13492 A final example illustrates switch contributions from packages in different
13493 project files:
13494
13495 @smallexample @c projectfile
13496 @group
13497 project Proj3 is
13498    for Source_Files use ("pack.ads", "pack.adb");
13499    package Compiler is
13500       for ^Default_Switches^Default_Switches^ ("Ada")
13501           use ("^-gnata^-gnata^");
13502    end Compiler;
13503 end Proj3;
13504 @end group
13505
13506 @group
13507 with "Proj3";
13508 project Proj4 is
13509    for Source_Files use ("foo_main.adb", "bar_main.adb");
13510    package Builder is
13511       for ^Switches^Switches^ ("foo_main.adb")
13512           use ("^-s^-s^",
13513                "^-g^-g^");
13514    end Builder;
13515 end Proj4;
13516 @end group
13517
13518 @group
13519 -- Ada source file:
13520 with Pack;
13521 procedure Foo_Main is
13522    ...
13523 end Foo_Main;
13524 @end group
13525 @end smallexample
13526
13527 If the command is
13528 @smallexample
13529 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13530 @end smallexample
13531
13532 @noindent
13533 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13534 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13535 @option{^-gnato^-gnato^} (passed on the command line).
13536 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13537 are @option{^-g^-g^} from @code{Proj4.Builder},
13538 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13539 and @option{^-gnato^-gnato^} from the command line.
13540
13541 @noindent
13542 When using @command{gnatmake} with project files, some ^switches^switches^ or
13543 arguments may be expressed as relative paths. As the working directory where
13544 compilation occurs may change, these relative paths are converted to absolute
13545 paths. For the ^switches^switches^ found in a project file, the relative paths
13546 are relative to the project file directory, for the switches on the command
13547 line, they are relative to the directory where @command{gnatmake} is invoked.
13548 The ^switches^switches^ for which this occurs are:
13549 ^-I^-I^,
13550 ^-A^-A^,
13551 ^-L^-L^,
13552 ^-aO^-aO^,
13553 ^-aL^-aL^,
13554 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13555 ^switch^switch^
13556 ^-o^-o^, object files specified in package @code{Linker} or after
13557 -largs on the command line). The exception to this rule is the ^switch^switch^
13558 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13559
13560 @node Specifying Configuration Pragmas
13561 @subsubsection Specifying Configuration Pragmas
13562
13563 When using @command{gnatmake} with project files, if there exists a file
13564 @file{gnat.adc} that contains configuration pragmas, this file will be
13565 ignored.
13566
13567 Configuration pragmas can be defined by means of the following attributes in
13568 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13569 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13570
13571 Both these attributes are single string attributes. Their values is the path
13572 name of a file containing configuration pragmas. If a path name is relative,
13573 then it is relative to the project directory of the project file where the
13574 attribute is defined.
13575
13576 When compiling a source, the configuration pragmas used are, in order,
13577 those listed in the file designated by attribute
13578 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13579 project file, if it is specified, and those listed in the file designated by
13580 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13581 the project file of the source, if it exists.
13582
13583 @node Project Files and Main Subprograms
13584 @subsubsection Project Files and Main Subprograms
13585
13586 @noindent
13587 When using a project file, you can invoke @command{gnatmake}
13588 with one or several main subprograms, by specifying their source files on the
13589 command line.
13590
13591 @smallexample
13592     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13593 @end smallexample
13594
13595 @noindent
13596 Each of these needs to be a source file of the same project, except
13597 when the switch ^-u^/UNIQUE^ is used.
13598
13599 @noindent
13600 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13601 same project, one of the project in the tree rooted at the project specified
13602 on the command line. The package @code{Builder} of this common project, the
13603 "main project" is the one that is considered by @command{gnatmake}.
13604
13605 @noindent
13606 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13607 imported directly or indirectly by the project specified on the command line.
13608 Note that if such a source file is not part of the project specified on the
13609 command line, the ^switches^switches^ found in package @code{Builder} of the
13610 project specified on the command line, if any, that are transmitted
13611 to the compiler will still be used, not those found in the project file of
13612 the source file.
13613
13614 @noindent
13615 When using a project file, you can also invoke @command{gnatmake} without
13616 explicitly specifying any main, and the effect depends on whether you have
13617 defined the @code{Main} attribute.  This attribute has a string list value,
13618 where each element in the list is the name of a source file (the file
13619 extension is optional) that contains a unit that can be a main subprogram.
13620
13621 If the @code{Main} attribute is defined in a project file as a non-empty
13622 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13623 line, then invoking @command{gnatmake} with this project file but without any
13624 main on the command line is equivalent to invoking @command{gnatmake} with all
13625 the file names in the @code{Main} attribute on the command line.
13626
13627 Example:
13628 @smallexample @c projectfile
13629 @group
13630    project Prj is
13631       for Main use ("main1", "main2", "main3");
13632    end Prj;
13633 @end group
13634 @end smallexample
13635
13636 @noindent
13637 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13638 is equivalent to
13639 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13640
13641 When the project attribute @code{Main} is not specified, or is specified
13642 as an empty string list, or when the switch @option{-u} is used on the command
13643 line, then invoking @command{gnatmake} with no main on the command line will
13644 result in all immediate sources of the project file being checked, and
13645 potentially recompiled. Depending on the presence of the switch @option{-u},
13646 sources from other project files on which the immediate sources of the main
13647 project file depend are also checked and potentially recompiled. In other
13648 words, the @option{-u} switch is applied to all of the immediate sources of the
13649 main project file.
13650
13651 When no main is specified on the command line and attribute @code{Main} exists
13652 and includes several mains, or when several mains are specified on the
13653 command line, the default ^switches^switches^ in package @code{Builder} will
13654 be used for all mains, even if there are specific ^switches^switches^
13655 specified for one or several mains.
13656
13657 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13658 the specific ^switches^switches^ for each main, if they are specified.
13659
13660 @node Library Project Files
13661 @subsubsection Library Project Files
13662
13663 @noindent
13664 When @command{gnatmake} is invoked with a main project file that is a library
13665 project file, it is not allowed to specify one or more mains on the command
13666 line.
13667
13668 @noindent
13669 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13670 ^-l^/ACTION=LINK^ have special meanings.
13671
13672 @itemize @bullet
13673 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13674 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13675 library.
13676
13677 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13678 to @command{gnatmake} that the binder generated file should be compiled
13679 (in the case of a stand-alone library) and that the library should be built.
13680
13681 @end itemize
13682
13683 @node The GNAT Driver and Project Files
13684 @subsection The GNAT Driver and Project Files
13685
13686 @noindent
13687 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13688 are project-aware:
13689 @command{^gnatbind^gnatbind^},
13690 @command{^gnatfind^gnatfind^},
13691 @command{^gnatlink^gnatlink^},
13692 @command{^gnatls^gnatls^},
13693 @command{^gnatelim^gnatelim^},
13694 @command{^gnatpp^gnatpp^},
13695 @command{^gnatmetric^gnatmetric^},
13696 @command{^gnatstub^gnatstub^},
13697 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13698 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13699 They must be invoked through the @command{gnat} driver.
13700
13701 The @command{gnat} driver is a front-end that accepts a number of commands and
13702 call the corresponding tool. It has been designed initially for VMS to convert
13703 VMS style qualifiers to Unix style switches, but it is now available to all
13704 the GNAT supported platforms.
13705
13706 On non VMS platforms, the @command{gnat} driver accepts the following commands
13707 (case insensitive):
13708
13709 @itemize @bullet
13710 @item
13711 BIND to invoke @command{^gnatbind^gnatbind^}
13712 @item
13713 CHOP to invoke @command{^gnatchop^gnatchop^}
13714 @item
13715 CLEAN to invoke @command{^gnatclean^gnatclean^}
13716 @item
13717 COMP or COMPILE to invoke the compiler
13718 @item
13719 ELIM to invoke @command{^gnatelim^gnatelim^}
13720 @item
13721 FIND to invoke @command{^gnatfind^gnatfind^}
13722 @item
13723 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13724 @item
13725 LINK to invoke @command{^gnatlink^gnatlink^}
13726 @item
13727 LS or LIST to invoke @command{^gnatls^gnatls^}
13728 @item
13729 MAKE to invoke @command{^gnatmake^gnatmake^}
13730 @item
13731 NAME to invoke @command{^gnatname^gnatname^}
13732 @item
13733 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13734 @item
13735 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13736 @item
13737 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13738 @item
13739 STUB to invoke @command{^gnatstub^gnatstub^}
13740 @item
13741 XREF to invoke @command{^gnatxref^gnatxref^}
13742 @end itemize
13743
13744 @noindent
13745 (note that the compiler is invoked using the command
13746 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13747
13748 @noindent
13749 On non VMS platforms, between @command{gnat} and the command, two
13750 special switches may be used:
13751
13752 @itemize @bullet
13753 @item
13754 @command{-v} to display the invocation of the tool.
13755 @item
13756 @command{-dn} to prevent the @command{gnat} driver from removing
13757 the temporary files it has created. These temporary files are
13758 configuration files and temporary file list files.
13759 @end itemize
13760
13761 @noindent
13762 The command may be followed by switches and arguments for the invoked
13763 tool.
13764
13765 @smallexample
13766   gnat bind -C main.ali
13767   gnat ls -a main
13768   gnat chop foo.txt
13769 @end smallexample
13770
13771 @noindent
13772 Switches may also be put in text files, one switch per line, and the text
13773 files may be specified with their path name preceded by '@@'.
13774
13775 @smallexample
13776    gnat bind @@args.txt main.ali
13777 @end smallexample
13778
13779 @noindent
13780 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13781 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13782 (@option{^-P^/PROJECT_FILE^},
13783 @option{^-X^/EXTERNAL_REFERENCE^} and
13784 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13785 the switches of the invoking tool.
13786
13787 @noindent
13788 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13789 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13790 the immediate sources of the specified project file.
13791
13792 @noindent
13793 When GNAT METRIC is used with a project file, but with no source
13794 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13795 with all the immediate sources of the specified project file and with
13796 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13797 of the project.
13798
13799 @noindent
13800 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13801 a project file, no source is specified on the command line and
13802 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13803 the underlying tool (^gnatpp^gnatpp^ or
13804 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13805 not only for the immediate sources of the main project.
13806 @ifclear vms
13807 (-U stands for Universal or Union of the project files of the project tree)
13808 @end ifclear
13809
13810 @noindent
13811 For each of the following commands, there is optionally a corresponding
13812 package in the main project.
13813
13814 @itemize @bullet
13815 @item
13816 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13817
13818 @item
13819 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13820
13821 @item
13822 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13823
13824 @item
13825 package @code{Eliminate} for command ELIM (invoking
13826 @code{^gnatelim^gnatelim^})
13827
13828 @item
13829 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13830
13831 @item
13832 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13833
13834 @item
13835 package @code{Metrics} for command METRIC
13836 (invoking @code{^gnatmetric^gnatmetric^})
13837
13838 @item
13839 package @code{Pretty_Printer} for command PP or PRETTY
13840 (invoking @code{^gnatpp^gnatpp^})
13841
13842 @item
13843 package @code{Gnatstub} for command STUB
13844 (invoking @code{^gnatstub^gnatstub^})
13845
13846 @item
13847 package @code{Cross_Reference} for command XREF (invoking
13848 @code{^gnatxref^gnatxref^})
13849
13850 @end itemize
13851
13852 @noindent
13853 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13854 a simple variable with a string list value. It contains ^switches^switches^
13855 for the invocation of @code{^gnatls^gnatls^}.
13856
13857 @smallexample @c projectfile
13858 @group
13859 project Proj1 is
13860    package gnatls is
13861       for ^Switches^Switches^
13862           use ("^-a^-a^",
13863                "^-v^-v^");
13864    end gnatls;
13865 end Proj1;
13866 @end group
13867 @end smallexample
13868
13869 @noindent
13870 All other packages have two attribute @code{^Switches^Switches^} and
13871 @code{^Default_Switches^Default_Switches^}.
13872
13873 @noindent
13874 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13875 source file name, that has a string list value: the ^switches^switches^ to be
13876 used when the tool corresponding to the package is invoked for the specific
13877 source file.
13878
13879 @noindent
13880 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13881 indexed by  the programming language that has a string list value.
13882 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13883 ^switches^switches^ for the invocation of the tool corresponding
13884 to the package, except if a specific @code{^Switches^Switches^} attribute
13885 is specified for the source file.
13886
13887 @smallexample @c projectfile
13888 @group
13889 project Proj is
13890
13891    for Source_Dirs use ("./**");
13892
13893    package gnatls is
13894       for ^Switches^Switches^ use
13895           ("^-a^-a^",
13896            "^-v^-v^");
13897    end gnatls;
13898 @end group
13899 @group
13900
13901    package Compiler is
13902       for ^Default_Switches^Default_Switches^ ("Ada")
13903           use ("^-gnatv^-gnatv^",
13904                "^-gnatwa^-gnatwa^");
13905    end Binder;
13906 @end group
13907 @group
13908
13909    package Binder is
13910       for ^Default_Switches^Default_Switches^ ("Ada")
13911           use ("^-C^-C^",
13912                "^-e^-e^");
13913    end Binder;
13914 @end group
13915 @group
13916
13917    package Linker is
13918       for ^Default_Switches^Default_Switches^ ("Ada")
13919           use ("^-C^-C^");
13920       for ^Switches^Switches^ ("main.adb")
13921           use ("^-C^-C^",
13922                "^-v^-v^",
13923                "^-v^-v^");
13924    end Linker;
13925 @end group
13926 @group
13927
13928    package Finder is
13929       for ^Default_Switches^Default_Switches^ ("Ada")
13930            use ("^-a^-a^",
13931                 "^-f^-f^");
13932    end Finder;
13933 @end group
13934 @group
13935
13936    package Cross_Reference is
13937       for ^Default_Switches^Default_Switches^ ("Ada")
13938           use ("^-a^-a^",
13939                "^-f^-f^",
13940                "^-d^-d^",
13941                "^-u^-u^");
13942    end Cross_Reference;
13943 end Proj;
13944 @end group
13945 @end smallexample
13946
13947 @noindent
13948 With the above project file, commands such as
13949
13950 @smallexample
13951    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13952    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13953    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13954    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13955    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13956 @end smallexample
13957
13958 @noindent
13959 will set up the environment properly and invoke the tool with the switches
13960 found in the package corresponding to the tool:
13961 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13962 except @code{^Switches^Switches^ ("main.adb")}
13963 for @code{^gnatlink^gnatlink^}.
13964
13965 @ifclear vms
13966 @node Glide and Project Files
13967 @subsection Glide and Project Files
13968
13969 @noindent
13970 Glide will automatically recognize the @file{.gpr} extension for
13971 project files, and will
13972 convert them to its own internal format automatically. However, it
13973 doesn't provide a syntax-oriented editor for modifying these
13974 files.
13975 The project file will be loaded as text when you select the menu item
13976 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13977 You can edit this text and save the @file{gpr} file;
13978 when you next select this project file in Glide it
13979 will be automatically reloaded.
13980 @end ifclear
13981
13982 @c **********************
13983 @node An Extended Example
13984 @section An Extended Example
13985
13986 @noindent
13987 Suppose that we have two programs, @var{prog1} and @var{prog2},
13988 whose sources are in corresponding directories. We would like
13989 to build them with a single @command{gnatmake} command, and we want to place
13990 their object files into @file{build} subdirectories of the source directories.
13991 Furthermore, we want to have to have two separate subdirectories
13992 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13993 the object files compiled with different set of compilation flags.
13994
13995 In other words, we have the following structure:
13996
13997 @smallexample
13998 @group
13999    main
14000      |- prog1
14001      |    |- build
14002      |         | debug
14003      |         | release
14004      |- prog2
14005           |- build
14006                | debug
14007                | release
14008 @end group
14009 @end smallexample
14010
14011 @noindent
14012 Here are the project files that we must place in a directory @file{main}
14013 to maintain this structure:
14014
14015 @enumerate
14016
14017 @item We create a @code{Common} project with a package @code{Compiler} that
14018 specifies the compilation ^switches^switches^:
14019
14020 @smallexample
14021 File "common.gpr":
14022 @group
14023 @b{project} Common @b{is}
14024
14025    @b{for} Source_Dirs @b{use} (); -- No source files
14026 @end group
14027
14028 @group
14029    @b{type} Build_Type @b{is} ("release", "debug");
14030    Build : Build_Type := External ("BUILD", "debug");
14031 @end group
14032 @group
14033    @b{package} Compiler @b{is}
14034       @b{case} Build @b{is}
14035          @b{when} "release" =>
14036            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14037                    @b{use} ("^-O2^-O2^");
14038          @b{when} "debug"   =>
14039            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14040                    @b{use} ("^-g^-g^");
14041       @b{end case};
14042    @b{end} Compiler;
14043
14044 @b{end} Common;
14045 @end group
14046 @end smallexample
14047
14048 @item We create separate projects for the two programs:
14049
14050 @smallexample
14051 @group
14052 File "prog1.gpr":
14053
14054 @b{with} "common";
14055 @b{project} Prog1 @b{is}
14056
14057     @b{for} Source_Dirs @b{use} ("prog1");
14058     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
14059
14060     @b{package} Compiler @b{renames} Common.Compiler;
14061
14062 @b{end} Prog1;
14063 @end group
14064 @end smallexample
14065
14066 @smallexample
14067 @group
14068 File "prog2.gpr":
14069
14070 @b{with} "common";
14071 @b{project} Prog2 @b{is}
14072
14073     @b{for} Source_Dirs @b{use} ("prog2");
14074     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
14075
14076     @b{package} Compiler @b{renames} Common.Compiler;
14077
14078 @end group
14079 @b{end} Prog2;
14080 @end smallexample
14081
14082 @item We create a wrapping project @code{Main}:
14083
14084 @smallexample
14085 @group
14086 File "main.gpr":
14087
14088 @b{with} "common";
14089 @b{with} "prog1";
14090 @b{with} "prog2";
14091 @b{project} Main @b{is}
14092
14093    @b{package} Compiler @b{renames} Common.Compiler;
14094
14095 @b{end} Main;
14096 @end group
14097 @end smallexample
14098
14099 @item Finally we need to create a dummy procedure that @code{with}s (either
14100 explicitly or implicitly) all the sources of our two programs.
14101
14102 @end enumerate
14103
14104 @noindent
14105 Now we can build the programs using the command
14106
14107 @smallexample
14108    gnatmake ^-P^/PROJECT_FILE=^main dummy
14109 @end smallexample
14110
14111 @noindent
14112 for the Debug mode, or
14113
14114 @ifclear vms
14115 @smallexample
14116    gnatmake -Pmain -XBUILD=release
14117 @end smallexample
14118 @end ifclear
14119
14120 @ifset vms
14121 @smallexample
14122    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14123 @end smallexample
14124 @end ifset
14125
14126 @noindent
14127 for the Release mode.
14128
14129 @c ********************************
14130 @c * Project File Complete Syntax *
14131 @c ********************************
14132
14133 @node Project File Complete Syntax
14134 @section Project File Complete Syntax
14135
14136 @smallexample
14137 project ::=
14138   context_clause project_declaration
14139
14140 context_clause ::=
14141   @{with_clause@}
14142
14143 with_clause ::=
14144   @b{with} path_name @{ , path_name @} ;
14145
14146 path_name ::=
14147    string_literal
14148
14149 project_declaration ::=
14150   simple_project_declaration | project_extension
14151
14152 simple_project_declaration ::=
14153   @b{project} <project_>simple_name @b{is}
14154     @{declarative_item@}
14155   @b{end} <project_>simple_name;
14156
14157 project_extension ::=
14158   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
14159     @{declarative_item@}
14160   @b{end} <project_>simple_name;
14161
14162 declarative_item ::=
14163   package_declaration |
14164   typed_string_declaration |
14165   other_declarative_item
14166
14167 package_declaration ::=
14168   package_specification | package_renaming
14169
14170 package_specification ::=
14171   @b{package} package_identifier @b{is}
14172     @{simple_declarative_item@}
14173   @b{end} package_identifier ;
14174
14175 package_identifier ::=
14176   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14177   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
14178   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
14179
14180 package_renaming ::==
14181   @b{package} package_identifier @b{renames}
14182        <project_>simple_name.package_identifier ;
14183
14184 typed_string_declaration ::=
14185   @b{type} <typed_string_>_simple_name @b{is}
14186    ( string_literal @{, string_literal@} );
14187
14188 other_declarative_item ::=
14189   attribute_declaration |
14190   typed_variable_declaration |
14191   variable_declaration |
14192   case_construction
14193
14194 attribute_declaration ::=
14195   full_associative_array_declaration |
14196   @b{for} attribute_designator @b{use} expression ;
14197
14198 full_associative_array_declaration ::=
14199   @b{for} <associative_array_attribute_>simple_name @b{use}
14200   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14201
14202 attribute_designator ::=
14203   <simple_attribute_>simple_name |
14204   <associative_array_attribute_>simple_name ( string_literal )
14205
14206 typed_variable_declaration ::=
14207   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
14208
14209 variable_declaration ::=
14210   <variable_>simple_name := expression;
14211
14212 expression ::=
14213   term @{& term@}
14214
14215 term ::=
14216   literal_string |
14217   string_list |
14218   <variable_>name |
14219   external_value |
14220   attribute_reference
14221
14222 string_literal ::=
14223   (same as Ada)
14224
14225 string_list ::=
14226   ( <string_>expression @{ , <string_>expression @} )
14227
14228 external_value ::=
14229   @b{external} ( string_literal [, string_literal] )
14230
14231 attribute_reference ::=
14232   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14233
14234 attribute_prefix ::=
14235   @b{project} |
14236   <project_>simple_name | package_identifier |
14237   <project_>simple_name . package_identifier
14238
14239 case_construction ::=
14240   @b{case} <typed_variable_>name @b{is}
14241     @{case_item@}
14242   @b{end case} ;
14243
14244 case_item ::=
14245   @b{when} discrete_choice_list =>
14246       @{case_construction | attribute_declaration@}
14247
14248 discrete_choice_list ::=
14249   string_literal @{| string_literal@} |
14250   @b{others}
14251
14252 name ::=
14253   simple_name @{. simple_name@}
14254
14255 simple_name ::=
14256   identifier (same as Ada)
14257
14258 @end smallexample
14259
14260 @node The Cross-Referencing Tools gnatxref and gnatfind
14261 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14262 @findex gnatxref
14263 @findex gnatfind
14264
14265 @noindent
14266 The compiler generates cross-referencing information (unless
14267 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14268 This information indicates where in the source each entity is declared and
14269 referenced. Note that entities in package Standard are not included, but
14270 entities in all other predefined units are included in the output.
14271
14272 Before using any of these two tools, you need to compile successfully your
14273 application, so that GNAT gets a chance to generate the cross-referencing
14274 information.
14275
14276 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14277 information to provide the user with the capability to easily locate the
14278 declaration and references to an entity. These tools are quite similar,
14279 the difference being that @code{gnatfind} is intended for locating
14280 definitions and/or references to a specified entity or entities, whereas
14281 @code{gnatxref} is oriented to generating a full report of all
14282 cross-references.
14283
14284 To use these tools, you must not compile your application using the
14285 @option{-gnatx} switch on the @command{gnatmake} command line
14286 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14287 information will not be generated.
14288
14289 @menu
14290 * gnatxref Switches::
14291 * gnatfind Switches::
14292 * Project Files for gnatxref and gnatfind::
14293 * Regular Expressions in gnatfind and gnatxref::
14294 * Examples of gnatxref Usage::
14295 * Examples of gnatfind Usage::
14296 @end menu
14297
14298 @node gnatxref Switches
14299 @section @code{gnatxref} Switches
14300
14301 @noindent
14302 The command invocation for @code{gnatxref} is:
14303 @smallexample
14304 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14305 @end smallexample
14306
14307 @noindent
14308 where
14309
14310 @table @code
14311 @item sourcefile1, sourcefile2
14312 identifies the source files for which a report is to be generated. The
14313 ``with''ed units will be processed too. You must provide at least one file.
14314
14315 These file names are considered to be regular expressions, so for instance
14316 specifying @file{source*.adb} is the same as giving every file in the current
14317 directory whose name starts with @file{source} and whose extension is
14318 @file{adb}.
14319
14320 You shouldn't specify any directory name, just base names. @command{gnatxref}
14321 and @command{gnatfind} will be able to locate these files by themselves using
14322 the source path. If you specify directories, no result is produced.
14323
14324 @end table
14325
14326 @noindent
14327 The switches can be :
14328 @table @option
14329 @c !sort!
14330 @item ^-a^/ALL_FILES^
14331 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14332 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14333 the read-only files found in the library search path. Otherwise, these files
14334 will be ignored. This option can be used to protect Gnat sources or your own
14335 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14336 much faster, and their output much smaller. Read-only here refers to access
14337 or permissions status in the file system for the current user.
14338
14339 @item -aIDIR
14340 @cindex @option{-aIDIR} (@command{gnatxref})
14341 When looking for source files also look in directory DIR. The order in which
14342 source file search is undertaken is the same as for @command{gnatmake}.
14343
14344 @item -aODIR
14345 @cindex @option{-aODIR} (@command{gnatxref})
14346 When searching for library and object files, look in directory
14347 DIR. The order in which library files are searched is the same as for
14348 @command{gnatmake}.
14349
14350 @item -nostdinc
14351 @cindex @option{-nostdinc} (@command{gnatxref})
14352 Do not look for sources in the system default directory.
14353
14354 @item -nostdlib
14355 @cindex @option{-nostdlib} (@command{gnatxref})
14356 Do not look for library files in the system default directory.
14357
14358 @item --RTS=@var{rts-path}
14359 @cindex @option{--RTS} (@command{gnatxref})
14360 Specifies the default location of the runtime library. Same meaning as the
14361 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14362
14363 @item ^-d^/DERIVED_TYPES^
14364 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14365 If this switch is set @code{gnatxref} will output the parent type
14366 reference for each matching derived types.
14367
14368 @item ^-f^/FULL_PATHNAME^
14369 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14370 If this switch is set, the output file names will be preceded by their
14371 directory (if the file was found in the search path). If this switch is
14372 not set, the directory will not be printed.
14373
14374 @item ^-g^/IGNORE_LOCALS^
14375 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14376 If this switch is set, information is output only for library-level
14377 entities, ignoring local entities. The use of this switch may accelerate
14378 @code{gnatfind} and @code{gnatxref}.
14379
14380 @item -IDIR
14381 @cindex @option{-IDIR} (@command{gnatxref})
14382 Equivalent to @samp{-aODIR -aIDIR}.
14383
14384 @item -pFILE
14385 @cindex @option{-pFILE} (@command{gnatxref})
14386 Specify a project file to use @xref{Project Files}. These project files are
14387 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
14388 project files, you should use gnatxref through the GNAT driver
14389 (@command{gnat xref -Pproject}).
14390
14391 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14392 project file in the current directory.
14393
14394 If a project file is either specified or found by the tools, then the content
14395 of the source directory and object directory lines are added as if they
14396 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14397 and @samp{^-aO^OBJECT_SEARCH^}.
14398 @item ^-u^/UNUSED^
14399 Output only unused symbols. This may be really useful if you give your
14400 main compilation unit on the command line, as @code{gnatxref} will then
14401 display every unused entity and 'with'ed package.
14402
14403 @ifclear vms
14404 @item -v
14405 Instead of producing the default output, @code{gnatxref} will generate a
14406 @file{tags} file that can be used by vi. For examples how to use this
14407 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14408 to the standard output, thus you will have to redirect it to a file.
14409 @end ifclear
14410
14411 @end table
14412
14413 @noindent
14414 All these switches may be in any order on the command line, and may even
14415 appear after the file names. They need not be separated by spaces, thus
14416 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14417 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14418
14419 @node gnatfind Switches
14420 @section @code{gnatfind} Switches
14421
14422 @noindent
14423 The command line for @code{gnatfind} is:
14424
14425 @smallexample
14426 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14427       [file1 file2 ...]
14428 @end smallexample
14429
14430 @noindent
14431 where
14432
14433 @table @code
14434 @item pattern
14435 An entity will be output only if it matches the regular expression found
14436 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14437
14438 Omitting the pattern is equivalent to specifying @samp{*}, which
14439 will match any entity. Note that if you do not provide a pattern, you
14440 have to provide both a sourcefile and a line.
14441
14442 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14443 for matching purposes. At the current time there is no support for
14444 8-bit codes other than Latin-1, or for wide characters in identifiers.
14445
14446 @item sourcefile
14447 @code{gnatfind} will look for references, bodies or declarations
14448 of symbols referenced in @file{sourcefile}, at line @samp{line}
14449 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14450 for syntax examples.
14451
14452 @item line
14453 is a decimal integer identifying the line number containing
14454 the reference to the entity (or entities) to be located.
14455
14456 @item column
14457 is a decimal integer identifying the exact location on the
14458 line of the first character of the identifier for the
14459 entity reference. Columns are numbered from 1.
14460
14461 @item file1 file2 ...
14462 The search will be restricted to these source files. If none are given, then
14463 the search will be done for every library file in the search path.
14464 These file must appear only after the pattern or sourcefile.
14465
14466 These file names are considered to be regular expressions, so for instance
14467 specifying 'source*.adb' is the same as giving every file in the current
14468 directory whose name starts with 'source' and whose extension is 'adb'.
14469
14470 The location of the spec of the entity will always be displayed, even if it
14471 isn't in one of file1, file2,... The occurrences of the entity in the
14472 separate units of the ones given on the command line will also be displayed.
14473
14474 Note that if you specify at least one file in this part, @code{gnatfind} may
14475 sometimes not be able to find the body of the subprograms...
14476
14477 @end table
14478
14479 @noindent
14480 At least one of 'sourcefile' or 'pattern' has to be present on
14481 the command line.
14482
14483 The following switches are available:
14484 @table @option
14485 @c !sort!
14486
14487 @item ^-a^/ALL_FILES^
14488 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14489 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14490 the read-only files found in the library search path. Otherwise, these files
14491 will be ignored. This option can be used to protect Gnat sources or your own
14492 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14493 much faster, and their output much smaller. Read-only here refers to access
14494 or permission status in the file system for the current user.
14495
14496 @item -aIDIR
14497 @cindex @option{-aIDIR} (@command{gnatfind})
14498 When looking for source files also look in directory DIR. The order in which
14499 source file search is undertaken is the same as for @command{gnatmake}.
14500
14501 @item -aODIR
14502 @cindex @option{-aODIR} (@command{gnatfind})
14503 When searching for library and object files, look in directory
14504 DIR. The order in which library files are searched is the same as for
14505 @command{gnatmake}.
14506
14507 @item -nostdinc
14508 @cindex @option{-nostdinc} (@command{gnatfind})
14509 Do not look for sources in the system default directory.
14510
14511 @item -nostdlib
14512 @cindex @option{-nostdlib} (@command{gnatfind})
14513 Do not look for library files in the system default directory.
14514
14515 @item --RTS=@var{rts-path}
14516 @cindex @option{--RTS} (@command{gnatfind})
14517 Specifies the default location of the runtime library. Same meaning as the
14518 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14519
14520 @item ^-d^/DERIVED_TYPE_INFORMATION^
14521 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14522 If this switch is set, then @code{gnatfind} will output the parent type
14523 reference for each matching derived types.
14524
14525 @item ^-e^/EXPRESSIONS^
14526 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14527 By default, @code{gnatfind} accept the simple regular expression set for
14528 @samp{pattern}. If this switch is set, then the pattern will be
14529 considered as full Unix-style regular expression.
14530
14531 @item ^-f^/FULL_PATHNAME^
14532 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14533 If this switch is set, the output file names will be preceded by their
14534 directory (if the file was found in the search path). If this switch is
14535 not set, the directory will not be printed.
14536
14537 @item ^-g^/IGNORE_LOCALS^
14538 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14539 If this switch is set, information is output only for library-level
14540 entities, ignoring local entities. The use of this switch may accelerate
14541 @code{gnatfind} and @code{gnatxref}.
14542
14543 @item -IDIR
14544 @cindex @option{-IDIR} (@command{gnatfind})
14545 Equivalent to @samp{-aODIR -aIDIR}.
14546
14547 @item -pFILE
14548 @cindex @option{-pFILE} (@command{gnatfind})
14549 Specify a project file (@pxref{Project Files}) to use.
14550 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14551 project file in the current directory.
14552
14553 If a project file is either specified or found by the tools, then the content
14554 of the source directory and object directory lines are added as if they
14555 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14556 @samp{^-aO^/OBJECT_SEARCH^}.
14557
14558 @item ^-r^/REFERENCES^
14559 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14560 By default, @code{gnatfind} will output only the information about the
14561 declaration, body or type completion of the entities. If this switch is
14562 set, the @code{gnatfind} will locate every reference to the entities in
14563 the files specified on the command line (or in every file in the search
14564 path if no file is given on the command line).
14565
14566 @item ^-s^/PRINT_LINES^
14567 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14568 If this switch is set, then @code{gnatfind} will output the content
14569 of the Ada source file lines were the entity was found.
14570
14571 @item ^-t^/TYPE_HIERARCHY^
14572 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14573 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14574 the specified type. It act like -d option but recursively from parent
14575 type to parent type. When this switch is set it is not possible to
14576 specify more than one file.
14577
14578 @end table
14579
14580 @noindent
14581 All these switches may be in any order on the command line, and may even
14582 appear after the file names. They need not be separated by spaces, thus
14583 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14584 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14585
14586 As stated previously, gnatfind will search in every directory in the
14587 search path. You can force it to look only in the current directory if
14588 you specify @code{*} at the end of the command line.
14589
14590 @node Project Files for gnatxref and gnatfind
14591 @section Project Files for @command{gnatxref} and @command{gnatfind}
14592
14593 @noindent
14594 Project files allow a programmer to specify how to compile its
14595 application, where to find sources, etc.  These files are used
14596 @ifclear vms
14597 primarily by the Glide Ada mode, but they can also be used
14598 @end ifclear
14599 by the two tools
14600 @code{gnatxref} and @code{gnatfind}.
14601
14602 A project file name must end with @file{.gpr}. If a single one is
14603 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14604 extract the information from it. If multiple project files are found, none of
14605 them is read, and you have to use the @samp{-p} switch to specify the one
14606 you want to use.
14607
14608 The following lines can be included, even though most of them have default
14609 values which can be used in most cases.
14610 The lines can be entered in any order in the file.
14611 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14612 each line. If you have multiple instances, only the last one is taken into
14613 account.
14614
14615 @table @code
14616 @item src_dir=DIR
14617 [default: @code{"^./^[]^"}]
14618 specifies a directory where to look for source files. Multiple @code{src_dir}
14619 lines can be specified and they will be searched in the order they
14620 are specified.
14621
14622 @item obj_dir=DIR
14623 [default: @code{"^./^[]^"}]
14624 specifies a directory where to look for object and library files. Multiple
14625 @code{obj_dir} lines can be specified, and they will be searched in the order
14626 they are specified
14627
14628 @item comp_opt=SWITCHES
14629 [default: @code{""}]
14630 creates a variable which can be referred to subsequently by using
14631 the @code{$@{comp_opt@}} notation. This is intended to store the default
14632 switches given to @command{gnatmake} and @command{gcc}.
14633
14634 @item bind_opt=SWITCHES
14635 [default: @code{""}]
14636 creates a variable which can be referred to subsequently by using
14637 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14638 switches given to @command{gnatbind}.
14639
14640 @item link_opt=SWITCHES
14641 [default: @code{""}]
14642 creates a variable which can be referred to subsequently by using
14643 the @samp{$@{link_opt@}} notation. This is intended to store the default
14644 switches given to @command{gnatlink}.
14645
14646 @item main=EXECUTABLE
14647 [default: @code{""}]
14648 specifies the name of the executable for the application. This variable can
14649 be referred to in the following lines by using the @samp{$@{main@}} notation.
14650
14651 @ifset vms
14652 @item comp_cmd=COMMAND
14653 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14654 @end ifset
14655 @ifclear vms
14656 @item comp_cmd=COMMAND
14657 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14658 @end ifclear
14659 specifies the command used to compile a single file in the application.
14660
14661 @ifset vms
14662 @item make_cmd=COMMAND
14663 [default: @code{"GNAT MAKE $@{main@}
14664 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14665 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14666 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14667 @end ifset
14668 @ifclear vms
14669 @item make_cmd=COMMAND
14670 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14671  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14672  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14673 @end ifclear
14674 specifies the command used to recompile the whole application.
14675
14676 @item run_cmd=COMMAND
14677 [default: @code{"$@{main@}"}]
14678 specifies the command used to run the application.
14679
14680 @item debug_cmd=COMMAND
14681 [default: @code{"gdb $@{main@}"}]
14682 specifies the command used to debug the application
14683
14684 @end table
14685
14686 @noindent
14687 @command{gnatxref} and @command{gnatfind} only take into account the
14688 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14689
14690 @node Regular Expressions in gnatfind and gnatxref
14691 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14692
14693 @noindent
14694 As specified in the section about @command{gnatfind}, the pattern can be a
14695 regular expression. Actually, there are to set of regular expressions
14696 which are recognized by the program :
14697
14698 @table @code
14699 @item globbing patterns
14700 These are the most usual regular expression. They are the same that you
14701 generally used in a Unix shell command line, or in a DOS session.
14702
14703 Here is a more formal grammar :
14704 @smallexample
14705 @group
14706 @iftex
14707 @leftskip=.5cm
14708 @end iftex
14709 regexp ::= term
14710 term   ::= elmt            -- matches elmt
14711 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14712 term   ::= *               -- any string of 0 or more characters
14713 term   ::= ?               -- matches any character
14714 term   ::= [char @{char@}] -- matches any character listed
14715 term   ::= [char - char]   -- matches any character in range
14716 @end group
14717 @end smallexample
14718
14719 @item full regular expression
14720 The second set of regular expressions is much more powerful. This is the
14721 type of regular expressions recognized by utilities such a @file{grep}.
14722
14723 The following is the form of a regular expression, expressed in Ada
14724 reference manual style BNF is as follows
14725
14726 @smallexample
14727 @iftex
14728 @leftskip=.5cm
14729 @end iftex
14730 @group
14731 regexp ::= term @{| term@} -- alternation (term or term ...)
14732
14733 term ::= item @{item@}     -- concatenation (item then item)
14734
14735 item ::= elmt              -- match elmt
14736 item ::= elmt *            -- zero or more elmt's
14737 item ::= elmt +            -- one or more elmt's
14738 item ::= elmt ?            -- matches elmt or nothing
14739 @end group
14740 @group
14741 elmt ::= nschar            -- matches given character
14742 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14743 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14744 elmt ::= [char - char]     -- matches chars in given range
14745 elmt ::= \ char            -- matches given character
14746 elmt ::= .                 -- matches any single character
14747 elmt ::= ( regexp )        -- parens used for grouping
14748
14749 char ::= any character, including special characters
14750 nschar ::= any character except ()[].*+?^^^
14751 @end group
14752 @end smallexample
14753
14754 Following are a few examples :
14755
14756 @table @samp
14757 @item abcde|fghi
14758 will match any of the two strings 'abcde' and 'fghi'.
14759
14760 @item abc*d
14761 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14762
14763 @item [a-z]+
14764 will match any string which has only lowercase characters in it (and at
14765 least one character
14766
14767 @end table
14768 @end table
14769
14770 @node Examples of gnatxref Usage
14771 @section Examples of @code{gnatxref} Usage
14772
14773 @subsection General Usage
14774
14775 @noindent
14776 For the following examples, we will consider the following units :
14777
14778 @smallexample @c ada
14779 @group
14780 @cartouche
14781 main.ads:
14782 1: with Bar;
14783 2: package Main is
14784 3:     procedure Foo (B : in Integer);
14785 4:     C : Integer;
14786 5: private
14787 6:     D : Integer;
14788 7: end Main;
14789
14790 main.adb:
14791 1: package body Main is
14792 2:     procedure Foo (B : in Integer) is
14793 3:     begin
14794 4:        C := B;
14795 5:        D := B;
14796 6:        Bar.Print (B);
14797 7:        Bar.Print (C);
14798 8:     end Foo;
14799 9: end Main;
14800
14801 bar.ads:
14802 1: package Bar is
14803 2:     procedure Print (B : Integer);
14804 3: end bar;
14805 @end cartouche
14806 @end group
14807 @end smallexample
14808
14809 @table @code
14810
14811 @noindent
14812 The first thing to do is to recompile your application (for instance, in
14813 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14814 the cross-referencing information.
14815 You can then issue any of the following commands:
14816
14817 @item gnatxref main.adb
14818 @code{gnatxref} generates cross-reference information for main.adb
14819 and every unit 'with'ed by main.adb.
14820
14821 The output would be:
14822 @smallexample
14823 @iftex
14824 @leftskip=0cm
14825 @end iftex
14826 B                                                      Type: Integer
14827   Decl: bar.ads           2:22
14828 B                                                      Type: Integer
14829   Decl: main.ads          3:20
14830   Body: main.adb          2:20
14831   Ref:  main.adb          4:13     5:13     6:19
14832 Bar                                                    Type: Unit
14833   Decl: bar.ads           1:9
14834   Ref:  main.adb          6:8      7:8
14835        main.ads           1:6
14836 C                                                      Type: Integer
14837   Decl: main.ads          4:5
14838   Modi: main.adb          4:8
14839   Ref:  main.adb          7:19
14840 D                                                      Type: Integer
14841   Decl: main.ads          6:5
14842   Modi: main.adb          5:8
14843 Foo                                                    Type: Unit
14844   Decl: main.ads          3:15
14845   Body: main.adb          2:15
14846 Main                                                    Type: Unit
14847   Decl: main.ads          2:9
14848   Body: main.adb          1:14
14849 Print                                                   Type: Unit
14850   Decl: bar.ads           2:15
14851   Ref:  main.adb          6:12     7:12
14852 @end smallexample
14853
14854 @noindent
14855 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14856 its body is in main.adb, line 1, column 14 and is not referenced any where.
14857
14858 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14859 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14860
14861 @item gnatxref package1.adb package2.ads
14862 @code{gnatxref} will generates cross-reference information for
14863 package1.adb, package2.ads and any other package 'with'ed by any
14864 of these.
14865
14866 @end table
14867
14868 @ifclear vms
14869 @subsection Using gnatxref with vi
14870
14871 @code{gnatxref} can generate a tags file output, which can be used
14872 directly from @file{vi}. Note that the standard version of @file{vi}
14873 will not work properly with overloaded symbols. Consider using another
14874 free implementation of @file{vi}, such as @file{vim}.
14875
14876 @smallexample
14877 $ gnatxref -v gnatfind.adb > tags
14878 @end smallexample
14879
14880 @noindent
14881 will generate the tags file for @code{gnatfind} itself (if the sources
14882 are in the search path!).
14883
14884 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14885 (replacing @i{entity} by whatever you are looking for), and vi will
14886 display a new file with the corresponding declaration of entity.
14887 @end ifclear
14888
14889 @node Examples of gnatfind Usage
14890 @section Examples of @code{gnatfind} Usage
14891
14892 @table @code
14893
14894 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14895 Find declarations for all entities xyz referenced at least once in
14896 main.adb. The references are search in every library file in the search
14897 path.
14898
14899 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14900 switch is set)
14901
14902 The output will look like:
14903 @smallexample
14904 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14905 ^directory/^[directory]^main.adb:24:10: xyz <= body
14906 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14907 @end smallexample
14908
14909 @noindent
14910 that is to say, one of the entities xyz found in main.adb is declared at
14911 line 12 of main.ads (and its body is in main.adb), and another one is
14912 declared at line 45 of foo.ads
14913
14914 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14915 This is the same command as the previous one, instead @code{gnatfind} will
14916 display the content of the Ada source file lines.
14917
14918 The output will look like:
14919
14920 @smallexample
14921 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14922    procedure xyz;
14923 ^directory/^[directory]^main.adb:24:10: xyz <= body
14924    procedure xyz is
14925 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14926    xyz : Integer;
14927 @end smallexample
14928
14929 @noindent
14930 This can make it easier to find exactly the location your are looking
14931 for.
14932
14933 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14934 Find references to all entities containing an x that are
14935 referenced on line 123 of main.ads.
14936 The references will be searched only in main.ads and foo.adb.
14937
14938 @item gnatfind main.ads:123
14939 Find declarations and bodies for all entities that are referenced on
14940 line 123 of main.ads.
14941
14942 This is the same as @code{gnatfind "*":main.adb:123}.
14943
14944 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14945 Find the declaration for the entity referenced at column 45 in
14946 line 123 of file main.adb in directory mydir. Note that it
14947 is usual to omit the identifier name when the column is given,
14948 since the column position identifies a unique reference.
14949
14950 The column has to be the beginning of the identifier, and should not
14951 point to any character in the middle of the identifier.
14952
14953 @end table
14954
14955 @c *********************************
14956 @node The GNAT Pretty-Printer gnatpp
14957 @chapter The GNAT Pretty-Printer @command{gnatpp}
14958 @findex gnatpp
14959 @cindex Pretty-Printer
14960
14961 @noindent
14962 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14963 for source reformatting / pretty-printing.
14964 It takes an Ada source file as input and generates a reformatted
14965 version as output.
14966 You can specify various style directives via switches; e.g.,
14967 identifier case conventions, rules of indentation, and comment layout.
14968
14969 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14970 tree for the input source and thus requires the input to be syntactically and
14971 semantically legal.
14972 If this condition is not met, @command{gnatpp} will terminate with an
14973 error message; no output file will be generated.
14974
14975 If the compilation unit
14976 contained in the input source depends semantically upon units located
14977 outside the current directory, you have to provide the source search path
14978 when invoking @command{gnatpp}, if these units are contained in files with
14979 names that do not follow the GNAT file naming rules, you have to provide
14980 the configuration file describing the corresponding naming scheme;
14981 see the description of the @command{gnatpp}
14982 switches below. Another possibility is to use a project file and to
14983 call @command{gnatpp} through the @command{gnat} driver
14984
14985 The @command{gnatpp} command has the form
14986
14987 @smallexample
14988 $ gnatpp [@var{switches}] @var{filename}
14989 @end smallexample
14990
14991 @noindent
14992 where
14993 @itemize @bullet
14994 @item
14995 @var{switches} is an optional sequence of switches defining such properties as
14996 the formatting rules, the source search path, and the destination for the
14997 output source file
14998
14999 @item
15000 @var{filename} is the name (including the extension) of the source file to
15001 reformat; ``wildcards'' or several file names on the same gnatpp command are
15002 allowed.  The file name may contain path information; it does not have to
15003 follow the GNAT file naming rules
15004 @end itemize
15005
15006 @menu
15007 * Switches for gnatpp::
15008 * Formatting Rules::
15009 @end menu
15010
15011 @node Switches for gnatpp
15012 @section Switches for @command{gnatpp}
15013
15014 @noindent
15015 The following subsections describe the various switches accepted by
15016 @command{gnatpp}, organized by category.
15017
15018 @ifclear vms
15019 You specify a switch by supplying a name and generally also a value.
15020 In many cases the values for a switch with a given name are incompatible with
15021 each other
15022 (for example the switch that controls the casing of a reserved word may have
15023 exactly one value: upper case, lower case, or
15024 mixed case) and thus exactly one such switch can be in effect for an
15025 invocation of @command{gnatpp}.
15026 If more than one is supplied, the last one is used.
15027 However, some values for the same switch are mutually compatible.
15028 You may supply several such switches to @command{gnatpp}, but then
15029 each must be specified in full, with both the name and the value.
15030 Abbreviated forms (the name appearing once, followed by each value) are
15031 not permitted.
15032 For example, to set
15033 the alignment of the assignment delimiter both in declarations and in
15034 assignment statements, you must write @option{-A2A3}
15035 (or @option{-A2 -A3}), but not @option{-A23}.
15036 @end ifclear
15037
15038 @ifset vms
15039 In many cases the set of options for a given qualifier are incompatible with
15040 each other (for example the qualifier that controls the casing of a reserved
15041 word may have exactly one option, which specifies either upper case, lower
15042 case, or mixed case), and thus exactly one such option can be in effect for
15043 an invocation of @command{gnatpp}.
15044 If more than one is supplied, the last one is used.
15045 However, some qualifiers have options that are mutually compatible,
15046 and then you may then supply several such options when invoking
15047 @command{gnatpp}.
15048 @end ifset
15049
15050 In most cases, it is obvious whether or not the
15051 ^values for a switch with a given name^options for a given qualifier^
15052 are compatible with each other.
15053 When the semantics might not be evident, the summaries below explicitly
15054 indicate the effect.
15055
15056 @menu
15057 * Alignment Control::
15058 * Casing Control::
15059 * Construct Layout Control::
15060 * General Text Layout Control::
15061 * Other Formatting Options::
15062 * Setting the Source Search Path::
15063 * Output File Control::
15064 * Other gnatpp Switches::
15065 @end menu
15066
15067 @node Alignment Control
15068 @subsection Alignment Control
15069 @cindex Alignment control in @command{gnatpp}
15070
15071 @noindent
15072 Programs can be easier to read if certain constructs are vertically aligned.
15073 By default all alignments are set ON.
15074 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15075 OFF, and then use one or more of the other
15076 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15077 to activate alignment for specific constructs.
15078
15079 @table @option
15080 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15081
15082 @ifset vms
15083 @item /ALIGN=ON
15084 Set all alignments to ON
15085 @end ifset
15086
15087 @item ^-A0^/ALIGN=OFF^
15088 Set all alignments to OFF
15089
15090 @item ^-A1^/ALIGN=COLONS^
15091 Align @code{:} in declarations
15092
15093 @item ^-A2^/ALIGN=DECLARATIONS^
15094 Align @code{:=} in initializations in declarations
15095
15096 @item ^-A3^/ALIGN=STATEMENTS^
15097 Align @code{:=} in assignment statements
15098
15099 @item ^-A4^/ALIGN=ARROWS^
15100 Align @code{=>} in associations
15101
15102 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15103 Align @code{at} keywords in the component clauses in record
15104 representation clauses
15105 @end table
15106
15107 @noindent
15108 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15109 is allowed.
15110
15111 @node Casing Control
15112 @subsection Casing Control
15113 @cindex Casing control in @command{gnatpp}
15114
15115 @noindent
15116 @command{gnatpp} allows you to specify the casing for reserved words,
15117 pragma names, attribute designators and identifiers.
15118 For identifiers you may define a
15119 general rule for name casing but also override this rule
15120 via a set of dictionary files.
15121
15122 Three types of casing are supported: lower case, upper case, and mixed case.
15123 Lower and upper case are self-explanatory (but since some letters in
15124 Latin1 and other GNAT-supported character sets
15125 exist only in lower-case form, an upper case conversion will have no
15126 effect on them.)
15127 ``Mixed case'' means that the first letter, and also each letter immediately
15128 following an underscore, are converted to their uppercase forms;
15129 all the other letters are converted to their lowercase forms.
15130
15131 @table @option
15132 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15133 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15134 Attribute designators are lower case
15135
15136 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15137 Attribute designators are upper case
15138
15139 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15140 Attribute designators are mixed case (this is the default)
15141
15142 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15143 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15144 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15145 lower case (this is the default)
15146
15147 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15148 Keywords are upper case
15149
15150 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15151 @item ^-nD^/NAME_CASING=AS_DECLARED^
15152 Name casing for defining occurrences are as they appear in the source file
15153 (this is the default)
15154
15155 @item ^-nU^/NAME_CASING=UPPER_CASE^
15156 Names are in upper case
15157
15158 @item ^-nL^/NAME_CASING=LOWER_CASE^
15159 Names are in lower case
15160
15161 @item ^-nM^/NAME_CASING=MIXED_CASE^
15162 Names are in mixed case
15163
15164 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15165 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15166 Pragma names are lower case
15167
15168 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15169 Pragma names are upper case
15170
15171 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15172 Pragma names are mixed case (this is the default)
15173
15174 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15175 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15176 Use @var{file} as a @emph{dictionary file} that defines
15177 the casing for a set of specified names,
15178 thereby overriding the effect on these names by
15179 any explicit or implicit
15180 ^-n^/NAME_CASING^ switch.
15181 To supply more than one dictionary file,
15182 use ^several @option{-D} switches^a list of files as options^.
15183
15184 @noindent
15185 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15186 to define the casing for the Ada predefined names and
15187 the names declared in the GNAT libraries.
15188
15189 @item ^-D-^/SPECIFIC_CASING^
15190 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15191 Do not use the default dictionary file;
15192 instead, use the casing
15193 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15194 dictionary file(s)
15195 @end table
15196
15197 @noindent
15198 The structure of a dictionary file, and details on the conventions
15199 used in the default dictionary file, are defined in @ref{Name Casing}.
15200
15201 The @option{^-D-^/SPECIFIC_CASING^} and
15202 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15203 compatible.
15204
15205 @node Construct Layout Control
15206 @subsection Construct Layout Control
15207 @cindex Layout control in @command{gnatpp}
15208
15209 @noindent
15210 This group of @command{gnatpp} switches controls the layout of comments and
15211 complex syntactic constructs.  See @ref{Formatting Comments} for details
15212 on their effect.
15213
15214 @table @option
15215 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15216 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15217 All the comments remain unchanged
15218
15219 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15220 GNAT-style comment line indentation (this is the default).
15221
15222 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15223 Reference-manual comment line indentation.
15224
15225 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15226 GNAT-style comment beginning
15227
15228 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15229 Reformat comment blocks
15230
15231 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15232 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15233 GNAT-style layout (this is the default)
15234
15235 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15236 Compact layout
15237
15238 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15239 Uncompact layout
15240
15241 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15242 @item ^-N^/NOTABS^
15243 All the VT characters are removed from the comment text. All the HT characters
15244 are expanded with the sequences of space characters to get to the next tab
15245 stops.
15246
15247 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15248 @item ^--no-separate-is^/NO_SEPARATE_IS^
15249 Do not place the keyword @code{is} on a separate line in a subprogram body in
15250 case if the specification occupies more then one line.
15251
15252 @end table
15253
15254 @ifclear vms
15255 @noindent
15256 The @option{-c1} and @option{-c2} switches are incompatible.
15257 The @option{-c3} and @option{-c4} switches are compatible with each other and
15258 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15259 the other comment formatting switches.
15260
15261 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15262 @end ifclear
15263
15264 @ifset vms
15265 @noindent
15266 For the @option{/COMMENTS_LAYOUT} qualifier:
15267 @itemize @bullet
15268 @item
15269 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15270 @item
15271 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15272 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15273 @end itemize
15274
15275 @noindent
15276 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15277 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15278 @end ifset
15279
15280 @node General Text Layout Control
15281 @subsection General Text Layout Control
15282
15283 @noindent
15284 These switches allow control over line length and indentation.
15285
15286 @table @option
15287 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15288 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15289 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
15290
15291 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15292 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15293 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15294
15295 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15296 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15297 Indentation level for continuation lines (relative to the line being
15298 continued), @i{nnn} from 1 .. 9.
15299 The default
15300 value is one less then the (normal) indentation level, unless the
15301 indentation is set to 1 (in which case the default value for continuation
15302 line indentation is also 1)
15303 @end table
15304
15305 @node Other Formatting Options
15306 @subsection Other Formatting Options
15307
15308 @noindent
15309 These switches control the inclusion of missing end/exit labels, and
15310 the indentation level in @b{case} statements.
15311
15312 @table @option
15313 @item ^-e^/NO_MISSED_LABELS^
15314 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15315 Do not insert missing end/exit labels. An end label is the name of
15316 a construct that may optionally be repeated at the end of the
15317 construct's declaration;
15318 e.g., the names of packages, subprograms, and tasks.
15319 An exit label is the name of a loop that may appear as target
15320 of an exit statement within the loop.
15321 By default, @command{gnatpp} inserts these end/exit labels when
15322 they are absent from the original source. This option suppresses such
15323 insertion, so that the formatted source reflects the original.
15324
15325 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15326 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15327 Insert a Form Feed character after a pragma Page.
15328
15329 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15330 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15331 Do not use an additional indentation level for @b{case} alternatives
15332 and variants if there are @i{nnn} or more (the default
15333 value is 10).
15334 If @i{nnn} is 0, an additional indentation level is
15335 used for @b{case} alternatives and variants regardless of their number.
15336 @end table
15337
15338 @node Setting the Source Search Path
15339 @subsection Setting the Source Search Path
15340
15341 @noindent
15342 To define the search path for the input source file, @command{gnatpp}
15343 uses the same switches as the GNAT compiler, with the same effects.
15344
15345 @table @option
15346 @item ^-I^/SEARCH=^@var{dir}
15347 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15348 The same as the corresponding gcc switch
15349
15350 @item ^-I-^/NOCURRENT_DIRECTORY^
15351 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15352 The same as the corresponding gcc switch
15353
15354 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15355 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15356 The same as the corresponding gcc switch
15357
15358 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15359 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15360 The same as the corresponding gcc switch
15361
15362 @end table
15363
15364 @node Output File Control
15365 @subsection Output File Control
15366
15367 @noindent
15368 By default the output is sent to the file whose name is obtained by appending
15369 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15370 (if the file with this name already exists, it is unconditionally overwritten).
15371 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15372 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15373 as output file.
15374 The output may be redirected by the following switches:
15375
15376 @table @option
15377 @item ^-pipe^/STANDARD_OUTPUT^
15378 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15379 Send the output to @code{Standard_Output}
15380
15381 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15382 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15383 Write the output into @var{output_file}.
15384 If @var{output_file} already exists, @command{gnatpp} terminates without
15385 reading or processing the input file.
15386
15387 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15388 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15389 Write the output into @var{output_file}, overwriting the existing file
15390 (if one is present).
15391
15392 @item ^-r^/REPLACE^
15393 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15394 Replace the input source file with the reformatted output, and copy the
15395 original input source into the file whose name is obtained by appending the
15396 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15397 If a file with this name already exists, @command{gnatpp} terminates without
15398 reading or processing the input file.
15399
15400 @item ^-rf^/OVERRIDING_REPLACE^
15401 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15402 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15403 already exists, it is overwritten.
15404
15405 @item ^-rnb^/NO_BACKUP^
15406 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15407 Replace the input source file with the reformatted output without
15408 creating any backup copy of the input source.
15409
15410 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15411 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15412 Specifies the format of the reformatted output file. The @var{xxx}
15413 ^string specified with the switch^option^ may be either
15414 @itemize @bullet
15415 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15416 @item ``@option{^crlf^CRLF^}''
15417 the same as @option{^crlf^CRLF^}
15418 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15419 @item ``@option{^lf^LF^}''
15420 the same as @option{^unix^UNIX^}
15421 @end itemize
15422
15423 @end table
15424
15425 @noindent
15426 Options @option{^-pipe^/STANDARD_OUTPUT^},
15427 @option{^-o^/OUTPUT^} and
15428 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15429 contains only one file to reformat.
15430 Option
15431 @option{^--eol^/END_OF_LINE^}
15432 cannot be used together
15433 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15434
15435 @node Other gnatpp Switches
15436 @subsection Other @code{gnatpp} Switches
15437
15438 @noindent
15439 The additional @command{gnatpp} switches are defined in this subsection.
15440
15441 @table @option
15442 @item ^-files @var{filename}^/FILES=@var{output_file}^
15443 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15444 Take the argument source files from the specified file. This file should be an
15445 ordinary textual file containing file names separated by spaces or
15446 line breaks. You can use this switch more then once in the same call to
15447 @command{gnatpp}. You also can combine this switch with explicit list of
15448 files.
15449
15450 @item ^-v^/VERBOSE^
15451 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15452 Verbose mode;
15453 @command{gnatpp} generates version information and then
15454 a trace of the actions it takes to produce or obtain the ASIS tree.
15455
15456 @item ^-w^/WARNINGS^
15457 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15458 Warning mode;
15459 @command{gnatpp} generates a warning whenever it cannot provide
15460 a required layout in the result source.
15461 @end table
15462
15463 @node Formatting Rules
15464 @section Formatting Rules
15465
15466 @noindent
15467 The following subsections show how @command{gnatpp} treats ``white space'',
15468 comments, program layout, and name casing.
15469 They provide the detailed descriptions of the switches shown above.
15470
15471 @menu
15472 * White Space and Empty Lines::
15473 * Formatting Comments::
15474 * Construct Layout::
15475 * Name Casing::
15476 @end menu
15477
15478 @node White Space and Empty Lines
15479 @subsection White Space and Empty Lines
15480
15481 @noindent
15482 @command{gnatpp} does not have an option to control space characters.
15483 It will add or remove spaces according to the style illustrated by the
15484 examples in the @cite{Ada Reference Manual}.
15485
15486 The only format effectors
15487 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15488 that will appear in the output file are platform-specific line breaks,
15489 and also format effectors within (but not at the end of) comments.
15490 In particular, each horizontal tab character that is not inside
15491 a comment will be treated as a space and thus will appear in the
15492 output file as zero or more spaces depending on
15493 the reformatting of the line in which it appears.
15494 The only exception is a Form Feed character, which is inserted after a
15495 pragma @code{Page} when @option{-ff} is set.
15496
15497 The output file will contain no lines with trailing ``white space'' (spaces,
15498 format effectors).
15499
15500 Empty lines in the original source are preserved
15501 only if they separate declarations or statements.
15502 In such contexts, a
15503 sequence of two or more empty lines is replaced by exactly one empty line.
15504 Note that a blank line will be removed if it separates two ``comment blocks''
15505 (a comment block is a sequence of whole-line comments).
15506 In order to preserve a visual separation between comment blocks, use an
15507 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15508 Likewise, if for some reason you wish to have a sequence of empty lines,
15509 use a sequence of empty comments instead.
15510
15511 @node Formatting Comments
15512 @subsection Formatting Comments
15513
15514 @noindent
15515 Comments in Ada code are of two kinds:
15516 @itemize @bullet
15517 @item
15518 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15519 ``white space'') on a line
15520
15521 @item
15522 an @emph{end-of-line comment}, which follows some other Ada lexical element
15523 on the same line.
15524 @end itemize
15525
15526 @noindent
15527 The indentation of a whole-line comment is that of either
15528 the preceding or following line in
15529 the formatted source, depending on switch settings as will be described below.
15530
15531 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15532 between the end of the preceding Ada lexical element and the beginning
15533 of the comment as appear in the original source,
15534 unless either the comment has to be split to
15535 satisfy the line length limitation, or else the next line contains a
15536 whole line comment that is considered a continuation of this end-of-line
15537 comment (because it starts at the same position).
15538 In the latter two
15539 cases, the start of the end-of-line comment is moved right to the nearest
15540 multiple of the indentation level.
15541 This may result in a ``line overflow'' (the right-shifted comment extending
15542 beyond the maximum line length), in which case the comment is split as
15543 described below.
15544
15545 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15546 (GNAT-style comment line indentation)
15547 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15548 (reference-manual comment line indentation).
15549 With reference-manual style, a whole-line comment is indented as if it
15550 were a declaration or statement at the same place
15551 (i.e., according to the indentation of the preceding line(s)).
15552 With GNAT style, a whole-line comment that is immediately followed by an
15553 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15554 word @b{begin}, is indented based on the construct that follows it.
15555
15556 For example:
15557 @smallexample @c ada
15558 @cartouche
15559 if A then
15560     null;
15561        -- some comment
15562 else
15563    null;
15564 end if;
15565 @end cartouche
15566 @end smallexample
15567
15568 @noindent
15569 Reference-manual indentation produces:
15570
15571 @smallexample @c ada
15572 @cartouche
15573 if A then
15574    null;
15575    --  some comment
15576 else
15577    null;
15578 end if;
15579 @end cartouche
15580 @end smallexample
15581
15582 @noindent
15583 while GNAT-style indentation produces:
15584
15585 @smallexample @c ada
15586 @cartouche
15587 if A then
15588    null;
15589 --  some comment
15590 else
15591    null;
15592 end if;
15593 @end cartouche
15594 @end smallexample
15595
15596 @noindent
15597 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15598 (GNAT style comment beginning) has the following
15599 effect:
15600
15601 @itemize @bullet
15602 @item
15603 For each whole-line comment that does not end with two hyphens,
15604 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15605 to ensure that there are at least two spaces between these hyphens and the
15606 first non-blank character of the comment.
15607 @end itemize
15608
15609 @noindent
15610 For an end-of-line comment, if in the original source the next line is a
15611 whole-line comment that starts at the same position
15612 as the end-of-line comment,
15613 then the whole-line comment (and all whole-line comments
15614 that follow it and that start at the same position)
15615 will start at this position in the output file.
15616
15617 @noindent
15618 That is, if in the original source we have:
15619
15620 @smallexample @c ada
15621 @cartouche
15622 begin
15623 A := B + C;            --  B must be in the range Low1..High1
15624                        --  C must be in the range Low2..High2
15625              --B+C will be in the range Low1+Low2..High1+High2
15626 X := X + 1;
15627 @end cartouche
15628 @end smallexample
15629
15630 @noindent
15631 Then in the formatted source we get
15632
15633 @smallexample @c ada
15634 @cartouche
15635 begin
15636    A := B + C;            --  B must be in the range Low1..High1
15637                           --  C must be in the range Low2..High2
15638    --  B+C will be in the range Low1+Low2..High1+High2
15639    X := X + 1;
15640 @end cartouche
15641 @end smallexample
15642
15643 @noindent
15644 A comment that exceeds the line length limit will be split.
15645 Unless switch
15646 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15647 the line belongs to a reformattable block, splitting the line generates a
15648 @command{gnatpp} warning.
15649 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15650 comments may be reformatted in typical
15651 word processor style (that is, moving words between lines and putting as
15652 many words in a line as possible).
15653
15654 @node Construct Layout
15655 @subsection Construct Layout
15656
15657 @noindent
15658 In several cases the suggested layout in the Ada Reference Manual includes
15659 an extra level of indentation that many programmers prefer to avoid. The
15660 affected cases include:
15661
15662 @itemize @bullet
15663
15664 @item Record type declaration (RM 3.8)
15665
15666 @item Record representation clause (RM 13.5.1)
15667
15668 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15669
15670 @item Block statement in case if a block has a statement identifier (RM 5.6)
15671 @end itemize
15672
15673 @noindent
15674 In compact mode (when GNAT style layout or compact layout is set),
15675 the pretty printer uses one level of indentation instead
15676 of two. This is achieved in the record definition and record representation
15677 clause cases by putting the @code{record} keyword on the same line as the
15678 start of the declaration or representation clause, and in the block and loop
15679 case by putting the block or loop header on the same line as the statement
15680 identifier.
15681
15682 @noindent
15683 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15684 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15685 layout on the one hand, and uncompact layout
15686 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15687 can be illustrated by the following examples:
15688
15689 @iftex
15690 @cartouche
15691 @multitable @columnfractions .5 .5
15692 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15693
15694 @item
15695 @smallexample @c ada
15696 type q is record
15697    a : integer;
15698    b : integer;
15699 end record;
15700 @end smallexample
15701 @tab
15702 @smallexample @c ada
15703 type q is
15704    record
15705       a : integer;
15706       b : integer;
15707    end record;
15708 @end smallexample
15709
15710 @item
15711 @smallexample @c ada
15712 for q use record
15713    a at 0 range  0 .. 31;
15714    b at 4 range  0 .. 31;
15715 end record;
15716 @end smallexample
15717 @tab
15718 @smallexample @c ada
15719 for q use
15720    record
15721       a at 0 range  0 .. 31;
15722       b at 4 range  0 .. 31;
15723    end record;
15724 @end smallexample
15725
15726 @item
15727 @smallexample @c ada
15728 Block : declare
15729    A : Integer := 3;
15730 begin
15731    Proc (A, A);
15732 end Block;
15733 @end smallexample
15734 @tab
15735 @smallexample @c ada
15736 Block :
15737    declare
15738       A : Integer := 3;
15739    begin
15740       Proc (A, A);
15741    end Block;
15742 @end smallexample
15743
15744 @item
15745 @smallexample @c ada
15746 Clear : for J in 1 .. 10 loop
15747    A (J) := 0;
15748 end loop Clear;
15749 @end smallexample
15750 @tab
15751 @smallexample @c ada
15752 Clear :
15753    for J in 1 .. 10 loop
15754       A (J) := 0;
15755    end loop Clear;
15756 @end smallexample
15757 @end multitable
15758 @end cartouche
15759 @end iftex
15760
15761 @ifnottex
15762 @smallexample
15763 @cartouche
15764 GNAT style, compact layout              Uncompact layout
15765
15766 type q is record                        type q is
15767    a : integer;                            record
15768    b : integer;                               a : integer;
15769 end record;                                   b : integer;
15770                                            end record;
15771
15772 for q use record                        for q use
15773    a at 0 range  0 .. 31;                  record
15774    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15775 end record;                                   b at 4 range  0 .. 31;
15776                                            end record;
15777
15778 Block : declare                         Block :
15779    A : Integer := 3;                       declare
15780 begin                                         A : Integer := 3;
15781    Proc (A, A);                            begin
15782 end Block;                                    Proc (A, A);
15783                                            end Block;
15784
15785 Clear : for J in 1 .. 10 loop           Clear :
15786    A (J) := 0;                             for J in 1 .. 10 loop
15787 end loop Clear;                               A (J) := 0;
15788                                            end loop Clear;
15789 @end cartouche
15790 @end smallexample
15791 @end ifnottex
15792
15793 @noindent
15794 A further difference between GNAT style layout and compact layout is that
15795 GNAT style layout inserts empty lines as separation for
15796 compound statements, return statements and bodies.
15797
15798 @node Name Casing
15799 @subsection Name Casing
15800
15801 @noindent
15802 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15803 the same casing as the corresponding defining identifier.
15804
15805 You control the casing for defining occurrences via the
15806 @option{^-n^/NAME_CASING^} switch.
15807 @ifclear vms
15808 With @option{-nD} (``as declared'', which is the default),
15809 @end ifclear
15810 @ifset vms
15811 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15812 @end ifset
15813 defining occurrences appear exactly as in the source file
15814 where they are declared.
15815 The other ^values for this switch^options for this qualifier^ ---
15816 @option{^-nU^UPPER_CASE^},
15817 @option{^-nL^LOWER_CASE^},
15818 @option{^-nM^MIXED_CASE^} ---
15819 result in
15820 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15821 If @command{gnatpp} changes the casing of a defining
15822 occurrence, it analogously changes the casing of all the
15823 usage occurrences of this name.
15824
15825 If the defining occurrence of a name is not in the source compilation unit
15826 currently being processed by @command{gnatpp}, the casing of each reference to
15827 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15828 switch (subject to the dictionary file mechanism described below).
15829 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15830 had affected the
15831 casing for the defining occurrence of the name.
15832
15833 Some names may need to be spelled with casing conventions that are not
15834 covered by the upper-, lower-, and mixed-case transformations.
15835 You can arrange correct casing by placing such names in a
15836 @emph{dictionary file},
15837 and then supplying a @option{^-D^/DICTIONARY^} switch.
15838 The casing of names from dictionary files overrides
15839 any @option{^-n^/NAME_CASING^} switch.
15840
15841 To handle the casing of Ada predefined names and the names from GNAT libraries,
15842 @command{gnatpp} assumes a default dictionary file.
15843 The name of each predefined entity is spelled with the same casing as is used
15844 for the entity in the @cite{Ada Reference Manual}.
15845 The name of each entity in the GNAT libraries is spelled with the same casing
15846 as is used in the declaration of that entity.
15847
15848 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15849 default dictionary file.
15850 Instead, the casing for predefined and GNAT-defined names will be established
15851 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15852 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15853 will appear as just shown,
15854 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15855 To ensure that even such names are rendered in uppercase,
15856 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15857 (or else, less conveniently, place these names in upper case in a dictionary
15858 file).
15859
15860 A dictionary file is
15861 a plain text file; each line in this file can be either a blank line
15862 (containing only space characters and ASCII.HT characters), an Ada comment
15863 line, or the specification of exactly one @emph{casing schema}.
15864
15865 A casing schema is a string that has the following syntax:
15866
15867 @smallexample
15868 @cartouche
15869   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15870
15871   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15872 @end cartouche
15873 @end smallexample
15874
15875 @noindent
15876 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15877 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15878
15879 The casing schema string can be followed by white space and/or an Ada-style
15880 comment; any amount of white space is allowed before the string.
15881
15882 If a dictionary file is passed as
15883 @ifclear vms
15884 the value of a @option{-D@var{file}} switch
15885 @end ifclear
15886 @ifset vms
15887 an option to the @option{/DICTIONARY} qualifier
15888 @end ifset
15889 then for every
15890 simple name and every identifier, @command{gnatpp} checks if the dictionary
15891 defines the casing for the name or for some of its parts (the term ``subword''
15892 is used below to denote the part of a name which is delimited by ``_'' or by
15893 the beginning or end of the word and which does not contain any ``_'' inside):
15894
15895 @itemize @bullet
15896 @item
15897 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15898 the casing defined by the dictionary; no subwords are checked for this word
15899
15900 @item
15901 for every subword @command{gnatpp} checks if the dictionary contains the
15902 corresponding string of the form @code{*@var{simple_identifier}*},
15903 and if it does, the casing of this @var{simple_identifier} is used
15904 for this subword
15905
15906 @item
15907 if the whole name does not contain any ``_'' inside, and if for this name
15908 the dictionary contains two entries - one of the form @var{identifier},
15909 and another - of the form *@var{simple_identifier}*, then the first one
15910 is applied to define the casing of this name
15911
15912 @item
15913 if more than one dictionary file is passed as @command{gnatpp} switches, each
15914 dictionary adds new casing exceptions and overrides all the existing casing
15915 exceptions set by the previous dictionaries
15916
15917 @item
15918 when @command{gnatpp} checks if the word or subword is in the dictionary,
15919 this check is not case sensitive
15920 @end itemize
15921
15922 @noindent
15923 For example, suppose we have the following source to reformat:
15924
15925 @smallexample @c ada
15926 @cartouche
15927 procedure test is
15928    name1 : integer := 1;
15929    name4_name3_name2 : integer := 2;
15930    name2_name3_name4 : Boolean;
15931    name1_var : Float;
15932 begin
15933    name2_name3_name4 := name4_name3_name2 > name1;
15934 end;
15935 @end cartouche
15936 @end smallexample
15937
15938 @noindent
15939 And suppose we have two dictionaries:
15940
15941 @smallexample
15942 @cartouche
15943 @i{dict1:}
15944    NAME1
15945    *NaMe3*
15946    *Name1*
15947 @end cartouche
15948
15949 @cartouche
15950 @i{dict2:}
15951   *NAME3*
15952 @end cartouche
15953 @end smallexample
15954
15955 @noindent
15956 If @command{gnatpp} is called with the following switches:
15957
15958 @smallexample
15959 @ifclear vms
15960 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15961 @end ifclear
15962 @ifset vms
15963 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15964 @end ifset
15965 @end smallexample
15966
15967 @noindent
15968 then we will get the following name casing in the @command{gnatpp} output:
15969
15970 @smallexample @c ada
15971 @cartouche
15972 procedure Test is
15973    NAME1             : Integer := 1;
15974    Name4_NAME3_Name2 : Integer := 2;
15975    Name2_NAME3_Name4 : Boolean;
15976    Name1_Var         : Float;
15977 begin
15978    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15979 end Test;
15980 @end cartouche
15981 @end smallexample
15982
15983 @c *********************************
15984 @node The GNAT Metric Tool gnatmetric
15985 @chapter The GNAT Metric Tool @command{gnatmetric}
15986 @findex gnatmetric
15987 @cindex Metric tool
15988
15989 @noindent
15990 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15991 for computing various program metrics.
15992 It takes an Ada source file as input and generates a file containing the
15993 metrics data as output. Various switches control which
15994 metrics are computed and output.
15995
15996 @command{gnatmetric} generates and uses the ASIS
15997 tree for the input source and thus requires the input to be syntactically and
15998 semantically legal.
15999 If this condition is not met, @command{gnatmetric} will generate
16000 an error message; no metric information for this file will be
16001 computed and reported.
16002
16003 If the compilation unit contained in the input source depends semantically
16004 upon units in files located outside the current directory, you have to provide
16005 the source search path when invoking @command{gnatmetric}.
16006 If it depends semantically upon units that are contained
16007 in files with names that do not follow the GNAT file naming rules, you have to
16008 provide the configuration file describing the corresponding naming scheme (see
16009 the description of the @command{gnatmetric} switches below.)
16010 Alternatively, you may use a project file and invoke @command{gnatmetric}
16011 through the @command{gnat} driver.
16012
16013 The @command{gnatmetric} command has the form
16014
16015 @smallexample
16016 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16017 @end smallexample
16018
16019 @noindent
16020 where
16021 @itemize @bullet
16022 @item
16023 @i{switches} specify the metrics to compute and define the destination for
16024 the output
16025
16026 @item
16027 Each @i{filename} is the name (including the extension) of a source
16028 file to process. ``Wildcards'' are allowed, and
16029 the file name may contain path information.
16030 If no @i{filename} is supplied, then the @i{switches} list must contain
16031 at least one
16032 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16033 Including both a @option{-files} switch and one or more
16034 @i{filename} arguments is permitted.
16035
16036 @item
16037 @i{-cargs gcc_switches} is a list of switches for
16038 @command{gcc}. They will be passed on to all compiler invocations made by
16039 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16040 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16041 and use the @option{-gnatec} switch to set the configuration file.
16042 @end itemize
16043
16044 @menu
16045 * Switches for gnatmetric::
16046 @end menu
16047
16048 @node Switches for gnatmetric
16049 @section Switches for @command{gnatmetric}
16050
16051 @noindent
16052 The following subsections describe the various switches accepted by
16053 @command{gnatmetric}, organized by category.
16054
16055 @menu
16056 * Output Files Control::
16057 * Disable Metrics For Local Units::
16058 * Line Metrics Control::
16059 * Syntax Metrics Control::
16060 * Complexity Metrics Control::
16061 * Other gnatmetric Switches::
16062 @end menu
16063
16064 @node Output Files Control
16065 @subsection Output File Control
16066 @cindex Output file control in @command{gnatmetric}
16067
16068 @noindent
16069 @command{gnatmetric} has two output formats. It can generate a
16070 textual (human-readable) form, and also XML. By default only textual
16071 output is generated.
16072
16073 When generating the output in textual form, @command{gnatmetric} creates
16074 for each Ada source file a corresponding text file
16075 containing the computed metrics. By default, this file
16076 is placed in the same directory as where the source file is located, and
16077 its name is obtained
16078 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16079 input file.
16080
16081 All the output information generated in XML format is placed in a single
16082 file. By default this file is placed in the current directory and has the
16083 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16084
16085 Some of the computed metrics are summed over the units passed to
16086 @command{gnatmetric}; for example, the total number of lines of code.
16087 By default this information is sent to @file{stdout}, but a file
16088 can be specified with the @option{-og} switch.
16089
16090 The following switches control the @command{gnatmetric} output:
16091
16092 @table @option
16093 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16094 @item ^-x^/XML^
16095 Generate the XML output
16096
16097 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16098 @item ^-nt^/NO_TEXT^
16099 Do not generate the output in text form (implies @option{^-x^/XML^})
16100
16101 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16102 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16103 Put textual files with detailed metrics into @var{output_dir}
16104
16105 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16106 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16107 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16108 in the name of the output file.
16109
16110 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16111 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16112 Put global metrics into @var{file_name}
16113
16114 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16115 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16116 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16117
16118 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16119 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16120 Use ``short'' source file names in the output.  (The @command{gnatmetric}
16121 output includes the name(s) of the Ada source file(s) from which the metrics
16122 are computed.  By default each name includes the absolute path. The
16123 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16124 to exclude all directory information from the file names that are output.)
16125
16126 @end table
16127
16128 @node Disable Metrics For Local Units
16129 @subsection Disable Metrics For Local Units
16130 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16131
16132 @noindent
16133 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16134 one compilation
16135 unit per one source file. It computes line metrics for the whole source
16136 file, and it also computes syntax
16137 and complexity metrics for the file's outermost unit.
16138
16139 By default, @command{gnatmetric} will also compute all metrics for certain
16140 kinds of locally declared program units:
16141
16142 @itemize @bullet
16143 @item
16144 subprogram (and generic subprogram) bodies;
16145
16146 @item
16147 package (and generic package) specifications and bodies;
16148
16149 @item
16150 task object and type specifications and bodies;
16151
16152 @item
16153 protected object and type specifications and bodies.
16154 @end itemize
16155
16156 @noindent
16157 These kinds of entities will be referred to as
16158 @emph{eligible local program units}, or simply @emph{eligible local units},
16159 @cindex Eligible local unit (for @command{gnatmetric})
16160 in the discussion below.
16161
16162 Note that a subprogram declaration, generic instantiation,
16163 or renaming declaration only receives metrics
16164 computation when it appear as the outermost entity
16165 in a source file.
16166
16167 Suppression of metrics computation for eligible local units can be
16168 obtained via the following switch:
16169
16170 @table @option
16171 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16172 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16173 Do not compute detailed metrics for eligible local program units
16174
16175 @end table
16176
16177 @node Line Metrics Control
16178 @subsection Line Metrics Control
16179 @cindex Line metrics control in @command{gnatmetric}
16180
16181 @noindent
16182 For any (legal) source file, and for each of its
16183 eligible local program units, @command{gnatmetric} computes the following
16184 metrics:
16185
16186 @itemize @bullet
16187 @item
16188 the total number of lines;
16189
16190 @item
16191 the total number of code lines (i.e., non-blank lines that are not comments)
16192
16193 @item
16194 the number of comment lines
16195
16196 @item
16197 the number of code lines containing end-of-line comments;
16198
16199 @item
16200 the number of empty lines and lines containing only space characters and/or
16201 format effectors (blank lines)
16202
16203 @end itemize
16204
16205 If @command{gnatmetric} is invoked on more than one source file, it sums the
16206 values of the line metrics for all the files being processed and then
16207 generates the cumulative results.
16208
16209 By default, all the line metrics are computed and reported. You can use the
16210 following switches to select the specific line metrics to be computed and
16211 reported (if any of these parameters is set, only explicitly specified line
16212 metrics are computed).
16213
16214 @table @option
16215 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
16216 @item ^-la^/LINES_ALL^
16217 The number of all lines
16218
16219 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
16220 @item ^-lcode^/CODE_LINES^
16221 The number of code lines
16222
16223 @cindex @option{^-lcomm^/COMMENT_LINES^} (@command{gnatmetric})
16224 @item ^-lcomm^/COMENT_LINES^
16225 The number of comment lines
16226
16227 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
16228 @item ^-leol^/MIXED_CODE_COMMENTS^
16229 The number of code lines containing
16230 end-of-line comments
16231
16232 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
16233 @item ^-lb^/BLANK_LINES^
16234 The number of blank lines
16235
16236 @end table
16237
16238 @node Syntax Metrics Control
16239 @subsection Syntax Metrics Control
16240 @cindex Syntax metrics control in @command{gnatmetric}
16241
16242 @noindent
16243 @command{gnatmetric} computes various syntactic metrics for the
16244 outermost unit and for each eligible local unit:
16245
16246 @table @emph
16247 @item LSLOC (``Logical Source Lines Of Code'')
16248 The total number of declarations and the total number of statements
16249
16250 @item Maximal static nesting level of inner program units
16251 According to
16252 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
16253 package, a task unit, a protected unit, a
16254 protected entry, a generic unit, or an explicitly declared subprogram other
16255 than an enumeration literal.''
16256
16257 @item Maximal nesting level of composite syntactic constructs
16258 This corresponds to the notion of the
16259 maximum nesting level in the GNAT built-in style checks
16260 (@pxref{Style Checking})
16261 @end table
16262
16263 @noindent
16264 For the outermost unit in the file, @command{gnatmetric} additionally computes
16265 the following metrics:
16266
16267 @table @emph
16268 @item Public subprograms
16269 This metric is computed for package specifications. It is the
16270 number of subprograms and generic subprograms declared in the visible
16271 part (including in nested packages, protected objects, and
16272 protected types).
16273
16274 @item All subprograms
16275 This metric is computed for bodies and subunits. The
16276 metric is equal to a total number of subprogram bodies in the compilation
16277 unit.
16278 Neither generic instantiations nor renamings-as-a-body nor body stubs
16279 are counted. Any subprogram body is counted, independently of its nesting
16280 level and enclosing constructs. Generic bodies and bodies of protected
16281 subprograms are counted in the same way as ``usual'' subprogram bodies.
16282
16283 @item Public types
16284 This metric is computed for package specifications and
16285 generic package declarations. It is the total number of types
16286 that can be referenced from outside this compilation unit, plus the
16287 number of types from all the visible parts of all the visible generic packages.
16288 Generic formal types are not counted.  Only types, not subtypes,
16289 are included.
16290
16291 @noindent
16292 Along with the total number of public types, the following
16293 types are counted and reported separately:
16294
16295 @itemize @bullet
16296 @item
16297 Abstract types
16298
16299 @item
16300 Root tagged types (abstract, non-abstract, private, non-private). Type
16301 extensions are @emph{not} counted
16302
16303 @item
16304 Private types (including private extensions)
16305
16306 @item
16307 Task types
16308
16309 @item
16310 Protected types
16311
16312 @end itemize
16313
16314 @item All types
16315 This metric is computed for any compilation unit. It is equal to the total
16316 number of the declarations of different types given in the compilation unit.
16317 The private and the corresponding full type declaration are counted as one
16318 type declaration. Incomplete type declarations and generic formal types
16319 are not counted.
16320 No distinction is made among different kinds of types (abstract,
16321 private etc.); the total number of types is computed and reported.
16322
16323 @end table
16324
16325 @noindent
16326 By default, all the syntax metrics are computed and reported. You can use the
16327 following switches to select specific syntax metrics;
16328 if any of these is set, only the explicitly specified metrics are computed.
16329
16330 @table @option
16331 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
16332 @item ^-ed^/DECLARATION_TOTAL^
16333 The total number of declarations
16334
16335 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
16336 @item ^-es^/STATEMENT_TOTAL^
16337 The total number of statements
16338
16339 @cindex @option{^-eps^/^} (@command{gnatmetric})
16340 @item ^-eps^/INT_SUBPROGRAMS^
16341 The number of public subprograms in a compilation unit
16342
16343 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
16344 @item ^-eas^/SUBPROGRAMS_ALL^
16345 The number of all the subprograms in a compilation unit
16346
16347 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
16348 @item ^-ept^/INT_TYPES^
16349 The number of public types in a compilation unit
16350
16351 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
16352 @item ^-eat^/TYPES_ALL^
16353 The number of all the types in a compilation unit
16354
16355 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
16356 @item ^-enu^/PROGRAM_NESTING_MAX^
16357 The maximal program unit nesting level
16358
16359 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
16360 @item ^-ec^/CONSTRUCT_NESTING_MAX^
16361 The maximal construct nesting level
16362
16363 @end table
16364
16365 @node Complexity Metrics Control
16366 @subsection Complexity Metrics Control
16367 @cindex Complexity metrics control in @command{gnatmetric}
16368
16369 @noindent
16370 For a program unit that is an executable body (a subprogram body (including
16371 generic bodies), task body, entry body or a package body containing
16372 its own statement sequence ) @command{gnatmetric} computes the following
16373 complexity metrics:
16374
16375 @itemize @bullet
16376 @item
16377 McCabe cyclomatic complexity;
16378
16379 @item
16380 McCabe essential complexity;
16381
16382 @item
16383 maximal loop nesting level
16384
16385 @end itemize
16386
16387 @noindent
16388 The McCabe complexity metrics are defined
16389 in @url{www.mccabe.com/pdf/nist235r.pdf}
16390
16391 According to McCabe, both control statements and short-circuit control forms
16392 should be taken into account when computing cyclomatic complexity. For each
16393 body, we compute three metric values:
16394
16395 @itemize @bullet
16396 @item
16397 the complexity introduced by control
16398 statements only, without taking into account short-circuit forms,
16399
16400 @item
16401 the complexity introduced by short-circuit control forms only, and
16402
16403 @item
16404 the total
16405 cyclomatic complexity, which is the sum of these two values.
16406 @end itemize
16407
16408 @noindent
16409 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16410 the code in the exception handlers and in all the nested program units.
16411
16412 By default, all the complexity metrics are computed and reported.
16413 For more finely-grained control you can use
16414 the following switches:
16415
16416 @table @option
16417 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16418
16419 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
16420 Do not compute the McCabe Cyclomatic Complexity
16421
16422 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
16423 Do not compute the Essential Complexity
16424
16425 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
16426 Do not compute maximal loop nesting level
16427
16428 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
16429 Do not consider @code{exit} statements as @code{goto}s when
16430 computing Essential Complexity
16431
16432 @end table
16433
16434 @node Other gnatmetric Switches
16435 @subsection Other @code{gnatmetric} Switches
16436
16437 @noindent
16438 Additional @command{gnatmetric} switches are as follows:
16439
16440 @table @option
16441 @item ^-files @var{filename}^/FILES=@var{filename}^
16442 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16443 Take the argument source files from the specified file. This file should be an
16444 ordinary textual file containing file names separated by spaces or
16445 line breaks. You can use this switch more then once in the same call to
16446 @command{gnatmetric}. You also can combine this switch with
16447 an explicit list of files.
16448
16449 @item ^-v^/VERBOSE^
16450 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16451 Verbose mode;
16452 @command{gnatmetric} generates version information and then
16453 a trace of sources being processed.
16454
16455 @item ^-dv^/DEBUG_OUTPUT^
16456 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16457 Debug mode;
16458 @command{gnatmetric} generates various messages useful to understand what
16459 happens during the metrics computation
16460
16461 @item ^-q^/QUIET^
16462 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16463 Quiet mode.
16464 @end table
16465
16466 @c ***********************************
16467 @node File Name Krunching Using gnatkr
16468 @chapter File Name Krunching Using @code{gnatkr}
16469 @findex gnatkr
16470
16471 @noindent
16472 This chapter discusses the method used by the compiler to shorten
16473 the default file names chosen for Ada units so that they do not
16474 exceed the maximum length permitted. It also describes the
16475 @code{gnatkr} utility that can be used to determine the result of
16476 applying this shortening.
16477 @menu
16478 * About gnatkr::
16479 * Using gnatkr::
16480 * Krunching Method::
16481 * Examples of gnatkr Usage::
16482 @end menu
16483
16484 @node About gnatkr
16485 @section About @code{gnatkr}
16486
16487 @noindent
16488 The default file naming rule in GNAT
16489 is that the file name must be derived from
16490 the unit name. The exact default rule is as follows:
16491 @itemize @bullet
16492 @item
16493 Take the unit name and replace all dots by hyphens.
16494 @item
16495 If such a replacement occurs in the
16496 second character position of a name, and the first character is
16497 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16498 ^~ (tilde)^$ (dollar sign)^
16499 instead of a minus.
16500 @end itemize
16501 The reason for this exception is to avoid clashes
16502 with the standard names for children of System, Ada, Interfaces,
16503 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16504 respectively.
16505
16506 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16507 switch of the compiler activates a ``krunching''
16508 circuit that limits file names to nn characters (where nn is a decimal
16509 integer). For example, using OpenVMS,
16510 where the maximum file name length is
16511 39, the value of nn is usually set to 39, but if you want to generate
16512 a set of files that would be usable if ported to a system with some
16513 different maximum file length, then a different value can be specified.
16514 The default value of 39 for OpenVMS need not be specified.
16515
16516 The @code{gnatkr} utility can be used to determine the krunched name for
16517 a given file, when krunched to a specified maximum length.
16518
16519 @node Using gnatkr
16520 @section Using @code{gnatkr}
16521
16522 @noindent
16523 The @code{gnatkr} command has the form
16524
16525 @ifclear vms
16526 @smallexample
16527 $ gnatkr @var{name} [@var{length}]
16528 @end smallexample
16529 @end ifclear
16530
16531 @ifset vms
16532 @smallexample
16533 $ gnatkr @var{name} /COUNT=nn
16534 @end smallexample
16535 @end ifset
16536
16537 @noindent
16538 @var{name} is the uncrunched file name, derived from the name of the unit
16539 in the standard manner described in the previous section (i.e. in particular
16540 all dots are replaced by hyphens). The file name may or may not have an
16541 extension (defined as a suffix of the form period followed by arbitrary
16542 characters other than period). If an extension is present then it will
16543 be preserved in the output. For example, when krunching @file{hellofile.ads}
16544 to eight characters, the result will be hellofil.ads.
16545
16546 Note: for compatibility with previous versions of @code{gnatkr} dots may
16547 appear in the name instead of hyphens, but the last dot will always be
16548 taken as the start of an extension. So if @code{gnatkr} is given an argument
16549 such as @file{Hello.World.adb} it will be treated exactly as if the first
16550 period had been a hyphen, and for example krunching to eight characters
16551 gives the result @file{hellworl.adb}.
16552
16553 Note that the result is always all lower case (except on OpenVMS where it is
16554 all upper case). Characters of the other case are folded as required.
16555
16556 @var{length} represents the length of the krunched name. The default
16557 when no argument is given is ^8^39^ characters. A length of zero stands for
16558 unlimited, in other words do not chop except for system files where the
16559 implied crunching length is always eight characters.
16560
16561 @noindent
16562 The output is the krunched name. The output has an extension only if the
16563 original argument was a file name with an extension.
16564
16565 @node Krunching Method
16566 @section Krunching Method
16567
16568 @noindent
16569 The initial file name is determined by the name of the unit that the file
16570 contains. The name is formed by taking the full expanded name of the
16571 unit and replacing the separating dots with hyphens and
16572 using ^lowercase^uppercase^
16573 for all letters, except that a hyphen in the second character position is
16574 replaced by a ^tilde^dollar sign^ if the first character is
16575 ^a, i, g, or s^A, I, G, or S^.
16576 The extension is @code{.ads} for a
16577 specification and @code{.adb} for a body.
16578 Krunching does not affect the extension, but the file name is shortened to
16579 the specified length by following these rules:
16580
16581 @itemize @bullet
16582 @item
16583 The name is divided into segments separated by hyphens, tildes or
16584 underscores and all hyphens, tildes, and underscores are
16585 eliminated. If this leaves the name short enough, we are done.
16586
16587 @item
16588 If the name is too long, the longest segment is located (left-most
16589 if there are two of equal length), and shortened by dropping
16590 its last character. This is repeated until the name is short enough.
16591
16592 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16593 to fit the name into 8 characters as required by some operating systems.
16594
16595 @smallexample
16596 our-strings-wide_fixed 22
16597 our strings wide fixed 19
16598 our string  wide fixed 18
16599 our strin   wide fixed 17
16600 our stri    wide fixed 16
16601 our stri    wide fixe  15
16602 our str     wide fixe  14
16603 our str     wid  fixe  13
16604 our str     wid  fix   12
16605 ou  str     wid  fix   11
16606 ou  st      wid  fix   10
16607 ou  st      wi   fix   9
16608 ou  st      wi   fi    8
16609 Final file name: oustwifi.adb
16610 @end smallexample
16611
16612 @item
16613 The file names for all predefined units are always krunched to eight
16614 characters. The krunching of these predefined units uses the following
16615 special prefix replacements:
16616
16617 @table @file
16618 @item ada-
16619 replaced by @file{^a^A^-}
16620
16621 @item gnat-
16622 replaced by @file{^g^G^-}
16623
16624 @item interfaces-
16625 replaced by @file{^i^I^-}
16626
16627 @item system-
16628 replaced by @file{^s^S^-}
16629 @end table
16630
16631 These system files have a hyphen in the second character position. That
16632 is why normal user files replace such a character with a
16633 ^tilde^dollar sign^, to
16634 avoid confusion with system file names.
16635
16636 As an example of this special rule, consider
16637 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16638
16639 @smallexample
16640 ada-strings-wide_fixed 22
16641 a-  strings wide fixed 18
16642 a-  string  wide fixed 17
16643 a-  strin   wide fixed 16
16644 a-  stri    wide fixed 15
16645 a-  stri    wide fixe  14
16646 a-  str     wide fixe  13
16647 a-  str     wid  fixe  12
16648 a-  str     wid  fix   11
16649 a-  st      wid  fix   10
16650 a-  st      wi   fix   9
16651 a-  st      wi   fi    8
16652 Final file name: a-stwifi.adb
16653 @end smallexample
16654 @end itemize
16655
16656 Of course no file shortening algorithm can guarantee uniqueness over all
16657 possible unit names, and if file name krunching is used then it is your
16658 responsibility to ensure that no name clashes occur. The utility
16659 program @code{gnatkr} is supplied for conveniently determining the
16660 krunched name of a file.
16661
16662 @node Examples of gnatkr Usage
16663 @section Examples of @code{gnatkr} Usage
16664
16665 @smallexample
16666 @iftex
16667 @leftskip=0cm
16668 @end iftex
16669 @ifclear vms
16670 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16671 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16672 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16673 $ gnatkr grandparent-parent-child     --> grparchi
16674 @end ifclear
16675 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16676 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16677 @end smallexample
16678
16679 @node Preprocessing Using gnatprep
16680 @chapter Preprocessing Using @code{gnatprep}
16681 @findex gnatprep
16682
16683 @noindent
16684 The @code{gnatprep} utility provides
16685 a simple preprocessing capability for Ada programs.
16686 It is designed for use with GNAT, but is not dependent on any special
16687 features of GNAT.
16688
16689 @menu
16690 * Using gnatprep::
16691 * Switches for gnatprep::
16692 * Form of Definitions File::
16693 * Form of Input Text for gnatprep::
16694 @end menu
16695
16696 @node Using gnatprep
16697 @section Using @code{gnatprep}
16698
16699 @noindent
16700 To call @code{gnatprep} use
16701
16702 @smallexample
16703 $ gnatprep [switches] infile outfile [deffile]
16704 @end smallexample
16705
16706 @noindent
16707 where
16708 @table @code
16709 @item switches
16710 is an optional sequence of switches as described in the next section.
16711
16712 @item infile
16713 is the full name of the input file, which is an Ada source
16714 file containing preprocessor directives.
16715
16716 @item outfile
16717 is the full name of the output file, which is an Ada source
16718 in standard Ada form. When used with GNAT, this file name will
16719 normally have an ads or adb suffix.
16720
16721 @item deffile
16722 is the full name of a text file containing definitions of
16723 symbols to be referenced by the preprocessor. This argument is
16724 optional, and can be replaced by the use of the @option{-D} switch.
16725
16726 @end table
16727
16728 @node Switches for gnatprep
16729 @section Switches for @code{gnatprep}
16730
16731 @table @option
16732 @c !sort!
16733
16734 @item ^-b^/BLANK_LINES^
16735 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16736 Causes both preprocessor lines and the lines deleted by
16737 preprocessing to be replaced by blank lines in the output source file,
16738 preserving line numbers in the output file.
16739
16740 @item ^-c^/COMMENTS^
16741 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16742 Causes both preprocessor lines and the lines deleted
16743 by preprocessing to be retained in the output source as comments marked
16744 with the special string @code{"--! "}. This option will result in line numbers
16745 being preserved in the output file.
16746
16747 @item ^-C^/REPLACE_IN_COMMENTS^
16748 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16749 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16750 If this option is specified, then comments are scanned and any $symbol
16751 substitutions performed as in program text. This is particularly useful
16752 when structured comments are used (e.g. when writing programs in the
16753 SPARK dialect of Ada). Note that this switch is not available when
16754 doing integrated preprocessing (it would be useless in this context
16755 since comments are ignored by the compiler in any case).
16756
16757 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16758 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16759 Defines a new symbol, associated with value. If no value is given on the
16760 command line, then symbol is considered to be @code{True}. This switch
16761 can be used in place of a definition file.
16762
16763 @ifset vms
16764 @item /REMOVE
16765 @cindex @option{/REMOVE} (@command{gnatprep})
16766 This is the default setting which causes lines deleted by preprocessing
16767 to be entirely removed from the output file.
16768 @end ifset
16769
16770 @item ^-r^/REFERENCE^
16771 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16772 Causes a @code{Source_Reference} pragma to be generated that
16773 references the original input file, so that error messages will use
16774 the file name of this original file. The use of this switch implies
16775 that preprocessor lines are not to be removed from the file, so its
16776 use will force @option{^-b^/BLANK_LINES^} mode if
16777 @option{^-c^/COMMENTS^}
16778 has not been specified explicitly.
16779
16780 Note that if the file to be preprocessed contains multiple units, then
16781 it will be necessary to @code{gnatchop} the output file from
16782 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16783 in the preprocessed file, it will be respected by
16784 @code{gnatchop ^-r^/REFERENCE^}
16785 so that the final chopped files will correctly refer to the original
16786 input source file for @code{gnatprep}.
16787
16788 @item ^-s^/SYMBOLS^
16789 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16790 Causes a sorted list of symbol names and values to be
16791 listed on the standard output file.
16792
16793 @item ^-u^/UNDEFINED^
16794 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16795 Causes undefined symbols to be treated as having the value FALSE in the context
16796 of a preprocessor test. In the absence of this option, an undefined symbol in
16797 a @code{#if} or @code{#elsif} test will be treated as an error.
16798
16799 @end table
16800
16801 @ifclear vms
16802 @noindent
16803 Note: if neither @option{-b} nor @option{-c} is present,
16804 then preprocessor lines and
16805 deleted lines are completely removed from the output, unless -r is
16806 specified, in which case -b is assumed.
16807 @end ifclear
16808
16809 @node Form of Definitions File
16810 @section Form of Definitions File
16811
16812 @noindent
16813 The definitions file contains lines of the form
16814
16815 @smallexample
16816 symbol := value
16817 @end smallexample
16818
16819 @noindent
16820 where symbol is an identifier, following normal Ada (case-insensitive)
16821 rules for its syntax, and value is one of the following:
16822
16823 @itemize @bullet
16824 @item
16825 Empty, corresponding to a null substitution
16826 @item
16827 A string literal using normal Ada syntax
16828 @item
16829 Any sequence of characters from the set
16830 (letters, digits, period, underline).
16831 @end itemize
16832
16833 @noindent
16834 Comment lines may also appear in the definitions file, starting with
16835 the usual @code{--},
16836 and comments may be added to the definitions lines.
16837
16838 @node Form of Input Text for gnatprep
16839 @section Form of Input Text for @code{gnatprep}
16840
16841 @noindent
16842 The input text may contain preprocessor conditional inclusion lines,
16843 as well as general symbol substitution sequences.
16844
16845 The preprocessor conditional inclusion commands have the form
16846
16847 @smallexample
16848 @group
16849 @cartouche
16850 #if @i{expression} [then]
16851    lines
16852 #elsif @i{expression} [then]
16853    lines
16854 #elsif @i{expression} [then]
16855    lines
16856 ...
16857 #else
16858    lines
16859 #end if;
16860 @end cartouche
16861 @end group
16862 @end smallexample
16863
16864 @noindent
16865 In this example, @i{expression} is defined by the following grammar:
16866 @smallexample
16867 @i{expression} ::=  <symbol>
16868 @i{expression} ::=  <symbol> = "<value>"
16869 @i{expression} ::=  <symbol> = <symbol>
16870 @i{expression} ::=  <symbol> 'Defined
16871 @i{expression} ::=  not @i{expression}
16872 @i{expression} ::=  @i{expression} and @i{expression}
16873 @i{expression} ::=  @i{expression} or @i{expression}
16874 @i{expression} ::=  @i{expression} and then @i{expression}
16875 @i{expression} ::=  @i{expression} or else @i{expression}
16876 @i{expression} ::=  ( @i{expression} )
16877 @end smallexample
16878
16879 @noindent
16880 For the first test (@i{expression} ::= <symbol>) the symbol must have
16881 either the value true or false, that is to say the right-hand of the
16882 symbol definition must be one of the (case-insensitive) literals
16883 @code{True} or @code{False}. If the value is true, then the
16884 corresponding lines are included, and if the value is false, they are
16885 excluded.
16886
16887 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16888 the symbol has been defined in the definition file or by a @option{-D}
16889 switch on the command line. Otherwise, the test is false.
16890
16891 The equality tests are case insensitive, as are all the preprocessor lines.
16892
16893 If the symbol referenced is not defined in the symbol definitions file,
16894 then the effect depends on whether or not switch @option{-u}
16895 is specified. If so, then the symbol is treated as if it had the value
16896 false and the test fails. If this switch is not specified, then
16897 it is an error to reference an undefined symbol. It is also an error to
16898 reference a symbol that is defined with a value other than @code{True}
16899 or @code{False}.
16900
16901 The use of the @code{not} operator inverts the sense of this logical test, so
16902 that the lines are included only if the symbol is not defined.
16903 The @code{then} keyword is optional as shown
16904
16905 The @code{#} must be the first non-blank character on a line, but
16906 otherwise the format is free form. Spaces or tabs may appear between
16907 the @code{#} and the keyword. The keywords and the symbols are case
16908 insensitive as in normal Ada code. Comments may be used on a
16909 preprocessor line, but other than that, no other tokens may appear on a
16910 preprocessor line. Any number of @code{elsif} clauses can be present,
16911 including none at all. The @code{else} is optional, as in Ada.
16912
16913 The @code{#} marking the start of a preprocessor line must be the first
16914 non-blank character on the line, i.e. it must be preceded only by
16915 spaces or horizontal tabs.
16916
16917 Symbol substitution outside of preprocessor lines is obtained by using
16918 the sequence
16919
16920 @smallexample
16921 $symbol
16922 @end smallexample
16923
16924 @noindent
16925 anywhere within a source line, except in a comment or within a
16926 string literal. The identifier
16927 following the @code{$} must match one of the symbols defined in the symbol
16928 definition file, and the result is to substitute the value of the
16929 symbol in place of @code{$symbol} in the output file.
16930
16931 Note that although the substitution of strings within a string literal
16932 is not possible, it is possible to have a symbol whose defined value is
16933 a string literal. So instead of setting XYZ to @code{hello} and writing:
16934
16935 @smallexample
16936 Header : String := "$XYZ";
16937 @end smallexample
16938
16939 @noindent
16940 you should set XYZ to @code{"hello"} and write:
16941
16942 @smallexample
16943 Header : String := $XYZ;
16944 @end smallexample
16945
16946 @noindent
16947 and then the substitution will occur as desired.
16948
16949 @ifset vms
16950 @node The GNAT Run-Time Library Builder gnatlbr
16951 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16952 @findex gnatlbr
16953 @cindex Library builder
16954
16955 @noindent
16956 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16957 supplied configuration pragmas.
16958
16959 @menu
16960 * Running gnatlbr::
16961 * Switches for gnatlbr::
16962 * Examples of gnatlbr Usage::
16963 @end menu
16964
16965 @node Running gnatlbr
16966 @section Running @code{gnatlbr}
16967
16968 @noindent
16969 The @code{gnatlbr} command has the form
16970
16971 @smallexample
16972 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16973 @end smallexample
16974
16975 @node Switches for gnatlbr
16976 @section Switches for @code{gnatlbr}
16977
16978 @noindent
16979 @code{gnatlbr} recognizes the following switches:
16980
16981 @table @option
16982 @c !sort!
16983 @item /CREATE=directory
16984 @cindex @code{/CREATE} (@code{gnatlbr})
16985      Create the new run-time library in the specified directory.
16986
16987 @item /SET=directory
16988 @cindex @code{/SET} (@code{gnatlbr})
16989      Make the library in the specified directory the current run-time
16990      library.
16991
16992 @item /DELETE=directory
16993 @cindex @code{/DELETE} (@code{gnatlbr})
16994      Delete the run-time library in the specified directory.
16995
16996 @item /CONFIG=file
16997 @cindex @code{/CONFIG} (@code{gnatlbr})
16998      With /CREATE:
16999      Use the configuration pragmas in the specified file when building
17000      the library.
17001
17002      With /SET:
17003      Use the configuration pragmas in the specified file when compiling.
17004
17005 @end table
17006
17007 @node Examples of gnatlbr Usage
17008 @section Example of @code{gnatlbr} Usage
17009
17010 @smallexample
17011 Contents of VAXFLOAT.ADC:
17012 pragma Float_Representation (VAX_Float);
17013
17014 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17015
17016 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
17017
17018 @end smallexample
17019 @end ifset
17020
17021 @node The GNAT Library Browser gnatls
17022 @chapter The GNAT Library Browser @code{gnatls}
17023 @findex gnatls
17024 @cindex Library browser
17025
17026 @noindent
17027 @code{gnatls} is a tool that outputs information about compiled
17028 units. It gives the relationship between objects, unit names and source
17029 files. It can also be used to check the source dependencies of a unit
17030 as well as various characteristics.
17031
17032 @menu
17033 * Running gnatls::
17034 * Switches for gnatls::
17035 * Examples of gnatls Usage::
17036 @end menu
17037
17038 @node Running gnatls
17039 @section Running @code{gnatls}
17040
17041 @noindent
17042 The @code{gnatls} command has the form
17043
17044 @smallexample
17045 $ gnatls switches @var{object_or_ali_file}
17046 @end smallexample
17047
17048 @noindent
17049 The main argument is the list of object or @file{ali} files
17050 (@pxref{The Ada Library Information Files})
17051 for which information is requested.
17052
17053 In normal mode, without additional option, @code{gnatls} produces a
17054 four-column listing. Each line represents information for a specific
17055 object. The first column gives the full path of the object, the second
17056 column gives the name of the principal unit in this object, the third
17057 column gives the status of the source and the fourth column gives the
17058 full path of the source representing this unit.
17059 Here is a simple example of use:
17060
17061 @smallexample
17062 $ gnatls *.o
17063 ^./^[]^demo1.o            demo1            DIF demo1.adb
17064 ^./^[]^demo2.o            demo2             OK demo2.adb
17065 ^./^[]^hello.o            h1                OK hello.adb
17066 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
17067 ^./^[]^instr.o            instr             OK instr.adb
17068 ^./^[]^tef.o              tef              DIF tef.adb
17069 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
17070 ^./^[]^tgef.o             tgef             DIF tgef.adb
17071 @end smallexample
17072
17073 @noindent
17074 The first line can be interpreted as follows: the main unit which is
17075 contained in
17076 object file @file{demo1.o} is demo1, whose main source is in
17077 @file{demo1.adb}. Furthermore, the version of the source used for the
17078 compilation of demo1 has been modified (DIF). Each source file has a status
17079 qualifier which can be:
17080
17081 @table @code
17082 @item OK (unchanged)
17083 The version of the source file used for the compilation of the
17084 specified unit corresponds exactly to the actual source file.
17085
17086 @item MOK (slightly modified)
17087 The version of the source file used for the compilation of the
17088 specified unit differs from the actual source file but not enough to
17089 require recompilation. If you use gnatmake with the qualifier
17090 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17091 MOK will not be recompiled.
17092
17093 @item DIF (modified)
17094 No version of the source found on the path corresponds to the source
17095 used to build this object.
17096
17097 @item ??? (file not found)
17098 No source file was found for this unit.
17099
17100 @item HID (hidden,  unchanged version not first on PATH)
17101 The version of the source that corresponds exactly to the source used
17102 for compilation has been found on the path but it is hidden by another
17103 version of the same source that has been modified.
17104
17105 @end table
17106
17107 @node Switches for gnatls
17108 @section Switches for @code{gnatls}
17109
17110 @noindent
17111 @code{gnatls} recognizes the following switches:
17112
17113 @table @option
17114 @c !sort!
17115 @item ^-a^/ALL_UNITS^
17116 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17117 Consider all units, including those of the predefined Ada library.
17118 Especially useful with @option{^-d^/DEPENDENCIES^}.
17119
17120 @item ^-d^/DEPENDENCIES^
17121 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17122 List sources from which specified units depend on.
17123
17124 @item ^-h^/OUTPUT=OPTIONS^
17125 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17126 Output the list of options.
17127
17128 @item ^-o^/OUTPUT=OBJECTS^
17129 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17130 Only output information about object files.
17131
17132 @item ^-s^/OUTPUT=SOURCES^
17133 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17134 Only output information about source files.
17135
17136 @item ^-u^/OUTPUT=UNITS^
17137 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17138 Only output information about compilation units.
17139
17140 @item ^-files^/FILES^=@var{file}
17141 @cindex @option{^-files^/FILES^} (@code{gnatls})
17142 Take as arguments the files listed in text file @var{file}.
17143 Text file @var{file} may contain empty lines that are ignored.
17144 Each non empty line should contain the name of an existing file.
17145 Several such switches may be specified simultaneously.
17146
17147 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17148 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17149 @itemx ^-I^/SEARCH=^@var{dir}
17150 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
17151 @itemx -nostdinc
17152 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17153 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17154 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17155 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17156 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17157 flags (@pxref{Switches for gnatmake}).
17158
17159 @item --RTS=@var{rts-path}
17160 @cindex @option{--RTS} (@code{gnatls})
17161 Specifies the default location of the runtime library. Same meaning as the
17162 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17163
17164 @item ^-v^/OUTPUT=VERBOSE^
17165 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17166 Verbose mode. Output the complete source, object and project paths. Do not use
17167 the default column layout but instead use long format giving as much as
17168 information possible on each requested units, including special
17169 characteristics such as:
17170
17171 @table @code
17172 @item  Preelaborable
17173 The unit is preelaborable in the Ada 95 sense.
17174
17175 @item No_Elab_Code
17176 No elaboration code has been produced by the compiler for this unit.
17177
17178 @item Pure
17179 The unit is pure in the Ada 95 sense.
17180
17181 @item Elaborate_Body
17182 The unit contains a pragma Elaborate_Body.
17183
17184 @item Remote_Types
17185 The unit contains a pragma Remote_Types.
17186
17187 @item Shared_Passive
17188 The unit contains a pragma Shared_Passive.
17189
17190 @item Predefined
17191 This unit is part of the predefined environment and cannot be modified
17192 by the user.
17193
17194 @item Remote_Call_Interface
17195 The unit contains a pragma Remote_Call_Interface.
17196
17197 @end table
17198
17199 @end table
17200
17201 @node Examples of gnatls Usage
17202 @section Example of @code{gnatls} Usage
17203 @ifclear vms
17204
17205 @noindent
17206 Example of using the verbose switch. Note how the source and
17207 object paths are affected by the -I switch.
17208
17209 @smallexample
17210 $ gnatls -v -I.. demo1.o
17211
17212 GNATLS 5.03w (20041123-34)
17213 Copyright 1997-2004 Free Software Foundation, Inc.
17214
17215 Source Search Path:
17216    <Current_Directory>
17217    ../
17218    /home/comar/local/adainclude/
17219
17220 Object Search Path:
17221    <Current_Directory>
17222    ../
17223    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17224
17225 Project Search Path:
17226    <Current_Directory>
17227    /home/comar/local/lib/gnat/
17228
17229 ./demo1.o
17230    Unit =>
17231      Name   => demo1
17232      Kind   => subprogram body
17233      Flags  => No_Elab_Code
17234      Source => demo1.adb    modified
17235 @end smallexample
17236
17237 @noindent
17238 The following is an example of use of the dependency list.
17239 Note the use of the -s switch
17240 which gives a straight list of source files. This can be useful for
17241 building specialized scripts.
17242
17243 @smallexample
17244 $ gnatls -d demo2.o
17245 ./demo2.o   demo2        OK demo2.adb
17246                          OK gen_list.ads
17247                          OK gen_list.adb
17248                          OK instr.ads
17249                          OK instr-child.ads
17250
17251 $ gnatls -d -s -a demo1.o
17252 demo1.adb
17253 /home/comar/local/adainclude/ada.ads
17254 /home/comar/local/adainclude/a-finali.ads
17255 /home/comar/local/adainclude/a-filico.ads
17256 /home/comar/local/adainclude/a-stream.ads
17257 /home/comar/local/adainclude/a-tags.ads
17258 gen_list.ads
17259 gen_list.adb
17260 /home/comar/local/adainclude/gnat.ads
17261 /home/comar/local/adainclude/g-io.ads
17262 instr.ads
17263 /home/comar/local/adainclude/system.ads
17264 /home/comar/local/adainclude/s-exctab.ads
17265 /home/comar/local/adainclude/s-finimp.ads
17266 /home/comar/local/adainclude/s-finroo.ads
17267 /home/comar/local/adainclude/s-secsta.ads
17268 /home/comar/local/adainclude/s-stalib.ads
17269 /home/comar/local/adainclude/s-stoele.ads
17270 /home/comar/local/adainclude/s-stratt.ads
17271 /home/comar/local/adainclude/s-tasoli.ads
17272 /home/comar/local/adainclude/s-unstyp.ads
17273 /home/comar/local/adainclude/unchconv.ads
17274 @end smallexample
17275 @end ifclear
17276
17277 @ifset vms
17278 @smallexample
17279 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17280
17281 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17282 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17283 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17284 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17285 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17286 demo1.adb
17287 gen_list.ads
17288 gen_list.adb
17289 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17290 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17291 instr.ads
17292 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17293 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17294 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17295 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17296 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17297 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17298 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17299 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17300 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17301 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17302 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17303 @end smallexample
17304 @end ifset
17305
17306 @node Cleaning Up Using gnatclean
17307 @chapter Cleaning Up Using @code{gnatclean}
17308 @findex gnatclean
17309 @cindex Cleaning tool
17310
17311 @noindent
17312 @code{gnatclean} is a tool that allows the deletion of files produced by the
17313 compiler, binder and linker, including ALI files, object files, tree files,
17314 expanded source files, library files, interface copy source files, binder
17315 generated files and executable files.
17316
17317 @menu
17318 * Running gnatclean::
17319 * Switches for gnatclean::
17320 @c * Examples of gnatclean Usage::
17321 @end menu
17322
17323 @node Running gnatclean
17324 @section Running @code{gnatclean}
17325
17326 @noindent
17327 The @code{gnatclean} command has the form:
17328
17329 @smallexample
17330 $ gnatclean switches @var{names}
17331 @end smallexample
17332
17333 @noindent
17334 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17335 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17336 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17337
17338 @noindent
17339 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17340 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17341 the linker. In informative-only mode, specified by switch
17342 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17343 normal mode is listed, but no file is actually deleted.
17344
17345 @node Switches for gnatclean
17346 @section Switches for @code{gnatclean}
17347
17348 @noindent
17349 @code{gnatclean} recognizes the following switches:
17350
17351 @table @option
17352 @c !sort!
17353 @item ^-c^/COMPILER_FILES_ONLY^
17354 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17355 Only attempt to delete the files produced by the compiler, not those produced
17356 by the binder or the linker. The files that are not to be deleted are library
17357 files, interface copy files, binder generated files and executable files.
17358
17359 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17360 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17361 Indicate that ALI and object files should normally be found in directory
17362 @var{dir}.
17363
17364 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17365 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17366 When using project files, if some errors or warnings are detected during
17367 parsing and verbose mode is not in effect (no use of switch
17368 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17369 file, rather than its simple file name.
17370
17371 @item ^-h^/HELP^
17372 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17373 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17374
17375 @item ^-n^/NODELETE^
17376 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17377 Informative-only mode. Do not delete any files. Output the list of the files
17378 that would have been deleted if this switch was not specified.
17379
17380 @item ^-P^/PROJECT_FILE=^@var{project}
17381 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17382 Use project file @var{project}. Only one such switch can be used.
17383 When cleaning a project file, the files produced by the compilation of the
17384 immediate sources or inherited sources of the project files are to be
17385 deleted. This is not depending on the presence or not of executable names
17386 on the command line.
17387
17388 @item ^-q^/QUIET^
17389 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17390 Quiet output. If there are no errors, do not output anything, except in
17391 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17392 (switch ^-n^/NODELETE^).
17393
17394 @item ^-r^/RECURSIVE^
17395 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17396 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17397 clean all imported and extended project files, recursively. If this switch
17398 is not specified, only the files related to the main project file are to be
17399 deleted. This switch has no effect if no project file is specified.
17400
17401 @item ^-v^/VERBOSE^
17402 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17403 Verbose mode.
17404
17405 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17406 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17407 Indicates the verbosity of the parsing of GNAT project files.
17408 @xref{Switches Related to Project Files}.
17409
17410 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17411 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17412 Indicates that external variable @var{name} has the value @var{value}.
17413 The Project Manager will use this value for occurrences of
17414 @code{external(name)} when parsing the project file.
17415 @xref{Switches Related to Project Files}.
17416
17417 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17418 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17419 When searching for ALI and object files, look in directory
17420 @var{dir}.
17421
17422 @item ^-I^/SEARCH=^@var{dir}
17423 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17424 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17425
17426 @item ^-I-^/NOCURRENT_DIRECTORY^
17427 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17428 @cindex Source files, suppressing search
17429 Do not look for ALI or object files in the directory
17430 where @code{gnatclean} was invoked.
17431
17432 @end table
17433
17434 @c @node Examples of gnatclean Usage
17435 @c @section Examples of @code{gnatclean} Usage
17436
17437 @ifclear vms
17438 @node GNAT and Libraries
17439 @chapter GNAT and Libraries
17440 @cindex Library, building, installing, using
17441
17442 @noindent
17443 This chapter describes how to build and use libraries with GNAT, and also shows
17444 how to recompile the GNAT run-time library. You should be familiar with the
17445 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17446 chapter.
17447
17448 @menu
17449 * Introduction to Libraries in GNAT::
17450 * General Ada Libraries::
17451 * Stand-alone Ada Libraries::
17452 * Rebuilding the GNAT Run-Time Library::
17453 @end menu
17454
17455 @node Introduction to Libraries in GNAT
17456 @section Introduction to Libraries in GNAT
17457
17458 @noindent
17459 A library is, conceptually, a collection of objects which does not have its
17460 own main thread of execution, but rather provides certain services to the
17461 applications that use it. A library can be either statically linked with the
17462 application, in which case its code is directly included in the application,
17463 or, on platforms that support it, be dynamically linked, in which case
17464 its code is shared by all applications making use of this library.
17465
17466 GNAT supports both types of libraries.
17467 In the static case, the compiled code can be provided in different ways. The
17468 simplest approach is to provide directly the set of objects resulting from
17469 compilation of the library source files. Alternatively, you can group the
17470 objects into an archive using whatever commands are provided by the operating
17471 system. For the latter case, the objects are grouped into a shared library.
17472
17473 In the GNAT environment, a library has three types of components:
17474 @itemize @bullet
17475 @item
17476 Source files.
17477 @item
17478 @file{ALI} files.
17479 @xref{The Ada Library Information Files}.
17480 @item
17481 Object files, an archive or a shared library.
17482 @end itemize
17483
17484 @noindent
17485 A GNAT library may expose all its source files, which is useful for
17486 documentation purposes. Alternatively, it may expose only the units needed by
17487 an external user to make use of the library. That is to say, the specs
17488 reflecting the library services along with all the units needed to compile
17489 those specs, which can include generic bodies or any body implementing an
17490 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17491 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17492
17493 All compilation units comprising an application, including those in a library,
17494 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17495 computes the elaboration order from the @file{ALI} files and this is why they
17496 constitute a mandatory part of GNAT libraries. Except in the case of
17497 @emph{stand-alone libraries}, where a specific library elaboration routine is
17498 produced independently of the application(s) using the library.
17499
17500 @node General Ada Libraries
17501 @section General Ada Libraries
17502
17503 @menu
17504 * Building a library::
17505 * Installing a library::
17506 * Using a library::
17507 @end menu
17508
17509 @node Building a library
17510 @subsection Building a library
17511
17512 @noindent
17513 The easiest way to build a library is to use the Project Manager,
17514 which supports a special type of project called a @emph{Library Project}
17515 (@pxref{Library Projects}).
17516
17517 A project is considered a library project, when two project-level attributes
17518 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17519 control different aspects of library configuration, additional optional
17520 project-level attributes can be specified:
17521 @table @code
17522 @item Library_Kind
17523 This attribute controls whether the library is to be static or dynamic
17524
17525 @item Library_Version
17526 This attribute specifies the library version; this value is used
17527 during dynamic linking of shared libraries to determine if the currently
17528 installed versions of the binaries are compatible.
17529
17530 @item Library_Options
17531 @item Library_GCC
17532 These attributes specify additional low-level options to be used during
17533 library generation, and redefine the actual application used to generate
17534 library.
17535 @end table
17536
17537 @noindent
17538 The GNAT Project Manager takes full care of the library maintenance task,
17539 including recompilation of the source files for which objects do not exist
17540 or are not up to date, assembly of the library archive, and installation of
17541 the library (i.e., copying associated source, object and @file{ALI} files
17542 to the specified location).
17543
17544 Here is a simple library project file:
17545 @smallexample @c ada
17546 project My_Lib is
17547    for Source_Dirs use ("src1", "src2");
17548    for Object_Dir use "obj";
17549    for Library_Name use "mylib";
17550    for Library_Dir use "lib";
17551    for Library_Kind use "dynamic";
17552 end My_lib;
17553 @end smallexample
17554
17555 @noindent
17556 and the compilation command to build and install the library:
17557
17558 @smallexample @c ada
17559   $ gnatmake -Pmy_lib
17560 @end smallexample
17561
17562 @noindent
17563 It is not entirely trivial to perform manually all the steps required to
17564 produce a library. We recommend that you use the GNAT Project Manager
17565 for this task. In special cases where this is not desired, the necessary
17566 steps are discussed below.
17567
17568 There are various possibilities for compiling the units that make up the
17569 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17570 with a conventional script. For simple libraries, it is also possible to create
17571 a dummy main program which depends upon all the packages that comprise the
17572 interface of the library. This dummy main program can then be given to
17573 @command{gnatmake}, which will ensure that all necessary objects are built.
17574
17575 After this task is accomplished, you should follow the standard procedure
17576 of the underlying operating system to produce the static or shared library.
17577
17578 Here is an example of such a dummy program:
17579 @smallexample @c ada
17580 @group
17581 with My_Lib.Service1;
17582 with My_Lib.Service2;
17583 with My_Lib.Service3;
17584 procedure My_Lib_Dummy is
17585 begin
17586    null;
17587 end;
17588 @end group
17589 @end smallexample
17590
17591 @noindent
17592 Here are the generic commands that will build an archive or a shared library.
17593
17594 @smallexample
17595 # compiling the library
17596 $ gnatmake -c my_lib_dummy.adb
17597
17598 # we don't need the dummy object itself
17599 $ rm my_lib_dummy.o my_lib_dummy.ali
17600
17601 # create an archive with the remaining objects
17602 $ ar rc libmy_lib.a *.o
17603 # some systems may require "ranlib" to be run as well
17604
17605 # or create a shared library
17606 $ gcc -shared -o libmy_lib.so *.o
17607 # some systems may require the code to have been compiled with -fPIC
17608
17609 # remove the object files that are now in the library
17610 $ rm *.o
17611
17612 # Make the ALI files read-only so that gnatmake will not try to
17613 # regenerate the objects that are in the library
17614 $ chmod -w *.ali
17615 @end smallexample
17616
17617 @noindent
17618 Please note that the library must have a name of the form @file{libxxx.a} or
17619 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17620 the directive @option{-lxxx} at link time.
17621
17622 @node Installing a library
17623 @subsection Installing a library
17624 @cindex @code{ADA_PROJECT_PATH}
17625
17626 @noindent
17627 If you use project files, library installation is part of the library build
17628 process. Thus no further action is needed in order to make use of the
17629 libraries that are built as part of the general application build. A usable
17630 version of the library is installed in the directory specified by the
17631 @code{Library_Dir} attribute of the library project file.
17632
17633 You may want to install a library in a context different from where the library
17634 is built. This situation arises with third party suppliers, who may want
17635 to distribute a library in binary form where the user is not expected to be
17636 able to recompile the library. The simplest option in this case is to provide
17637 a project file slightly different from the one used to build the library, by
17638 using the @code{externally_built} attribute. For instance, the project
17639 file used to build the library in the previous section can be changed into the
17640 following one when the library is installed:
17641
17642 @smallexample @c projectfile
17643 project My_Lib is
17644    for Source_Dirs use ("src1", "src2");
17645    for Library_Name use "mylib";
17646    for Library_Dir use "lib";
17647    for Library_Kind use "dynamic";
17648    for Externally_Built use "true";
17649 end My_lib;
17650 @end smallexample
17651
17652 @noindent
17653 This project file assumes that the directories @file{src1},
17654 @file{src2}, and @file{lib} exist in
17655 the directory containing the project file. The @code{externally_built}
17656 attribute makes it clear to the GNAT builder that it should not attempt to
17657 recompile any of the units from this library. It allows the library provider to
17658 restrict the source set to the minimum necessary for clients to make use of the
17659 library as described in the first section of this chapter. It is the
17660 responsibility of the library provider to install the necessary sources, ALI
17661 files and libraries in the directories mentioned in the project file. For
17662 convenience, the user's library project file should be installed in a location
17663 that will be searched automatically by the GNAT
17664 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
17665 environment variable (@pxref{Importing Projects}), and also the default GNAT
17666 library location that can be queried with @command{gnatls -v} and is usually of
17667 the form $gnat_install_root/lib/gnat.
17668
17669 When project files are not an option, it is also possible, but not recommended,
17670 to install the library so that the sources needed to use the library are on the
17671 Ada source path and the ALI files & libraries be on the Ada Object path (see
17672 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17673 administrator can place general-purpose libraries in the default compiler
17674 paths, by specifying the libraries' location in the configuration files
17675 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17676 must be located in the GNAT installation tree at the same place as the gcc spec
17677 file. The location of the gcc spec file can be determined as follows:
17678 @smallexample
17679 $ gcc -v
17680 @end smallexample
17681
17682 @noindent
17683 The configuration files mentioned above have a simple format: each line
17684 must contain one unique directory name.
17685 Those names are added to the corresponding path
17686 in their order of appearance in the file. The names can be either absolute
17687 or relative; in the latter case, they are relative to where theses files
17688 are located.
17689
17690 The files @file{ada_source_path} and @file{ada_object_path} might not be
17691 present in a
17692 GNAT installation, in which case, GNAT will look for its run-time library in
17693 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17694 objects and @file{ALI} files). When the files exist, the compiler does not
17695 look in @file{adainclude} and @file{adalib}, and thus the
17696 @file{ada_source_path} file
17697 must contain the location for the GNAT run-time sources (which can simply
17698 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17699 contain the location for the GNAT run-time objects (which can simply
17700 be @file{adalib}).
17701
17702 You can also specify a new default path to the run-time library at compilation
17703 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17704 the run-time library you want your program to be compiled with. This switch is
17705 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17706 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17707
17708 It is possible to install a library before or after the standard GNAT
17709 library, by reordering the lines in the configuration files. In general, a
17710 library must be installed before the GNAT library if it redefines
17711 any part of it.
17712
17713 @node Using a library
17714 @subsection Using a library
17715
17716 @noindent Once again, the project facility greatly simplifies the use of
17717 libraries. In this context, using a library is just a matter of adding a
17718 @code{with} clause in the user project. For instance, to make use of the
17719 library @code{My_Lib} shown in examples in earlier sections, you can
17720 write:
17721
17722 @smallexample @c projectfile
17723 with "my_lib";
17724 project My_Proj is
17725   ...
17726 end My_Proj;
17727 @end smallexample
17728
17729 Even if you have a third-party, non-Ada library, you can still use GNAT's
17730 Project Manager facility to provide a wrapper for it. For example, the
17731 following project, when @code{with}ed by your main project, will link with the
17732 third-party library @file{liba.a}:
17733
17734 @smallexample @c projectfile
17735 @group
17736 project Liba is
17737    for Externally_Built use "true";
17738    for Library_Dir use "lib";
17739    for Library_Name use "a";
17740    for Library_Kind use "static";
17741 end Liba;
17742 @end group
17743 @end smallexample
17744 This is an alternative to the use of @code{pragma Linker_Options}. It is
17745 especially interesting in the context of systems with several interdependent
17746 static libraries where finding a proper linker order is not easy and best be
17747 left to the tools having visibility over project dependence information.
17748
17749 @noindent
17750 In order to use an Ada library manually, you need to make sure that this
17751 library is on both your source and object path
17752 (see @ref{Search Paths and the Run-Time Library (RTL)}
17753 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17754 in an archive or a shared library, you need to specify the desired
17755 library at link time.
17756
17757 For example, you can use the library @file{mylib} installed in
17758 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17759
17760 @smallexample
17761 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17762   -largs -lmy_lib
17763 @end smallexample
17764
17765 @noindent
17766 This can be expressed more simply:
17767 @smallexample
17768 $ gnatmake my_appl
17769 @end smallexample
17770 @noindent
17771 when the following conditions are met:
17772 @itemize @bullet
17773 @item
17774 @file{/dir/my_lib_src} has been added by the user to the environment
17775 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17776 @file{ada_source_path}
17777 @item
17778 @file{/dir/my_lib_obj} has been added by the user to the environment
17779 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17780 @file{ada_object_path}
17781 @item
17782 a pragma @code{Linker_Options} has been added to one of the sources.
17783 For example:
17784
17785 @smallexample @c ada
17786 pragma Linker_Options ("-lmy_lib");
17787 @end smallexample
17788 @end itemize
17789
17790 @node Stand-alone Ada Libraries
17791 @section Stand-alone Ada Libraries
17792 @cindex Stand-alone library, building, using
17793
17794 @menu
17795 * Introduction to Stand-alone Libraries::
17796 * Building a Stand-alone Library::
17797 * Creating a Stand-alone Library to be used in a non-Ada context::
17798 * Restrictions in Stand-alone Libraries::
17799 @end menu
17800
17801 @node Introduction to Stand-alone Libraries
17802 @subsection Introduction to Stand-alone Libraries
17803
17804 @noindent
17805 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17806 necessary code to
17807 elaborate the Ada units that are included in the library. In contrast with
17808 an ordinary library, which consists of all sources, objects and @file{ALI}
17809 files of the
17810 library, a SAL may specify a restricted subset of compilation units
17811 to serve as a library interface. In this case, the fully
17812 self-sufficient set of files will normally consist of an objects
17813 archive, the sources of interface units' specs, and the @file{ALI}
17814 files of interface units.
17815 If an interface spec contains a generic unit or an inlined subprogram,
17816 the body's
17817 source must also be provided; if the units that must be provided in the source
17818 form depend on other units, the source and @file{ALI} files of those must
17819 also be provided.
17820
17821 The main purpose of a SAL is to minimize the recompilation overhead of client
17822 applications when a new version of the library is installed. Specifically,
17823 if the interface sources have not changed, client applications do not need to
17824 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17825 version, controlled by @code{Library_Version} attribute, is not changed,
17826 then the clients do not need to be relinked.
17827
17828 SALs also allow the library providers to minimize the amount of library source
17829 text exposed to the clients.  Such ``information hiding'' might be useful or
17830 necessary for various reasons.
17831
17832 Stand-alone libraries are also well suited to be used in an executable whose
17833 main routine is not written in Ada.
17834
17835 @node Building a Stand-alone Library
17836 @subsection Building a Stand-alone Library
17837
17838 @noindent
17839 GNAT's Project facility provides a simple way of building and installing
17840 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17841 To be a Stand-alone Library Project, in addition to the two attributes
17842 that make a project a Library Project (@code{Library_Name} and
17843 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17844 @code{Library_Interface} must be defined.  For example:
17845
17846 @smallexample @c projectfile
17847 @group
17848    for Library_Dir use "lib_dir";
17849    for Library_Name use "dummy";
17850    for Library_Interface use ("int1", "int1.child");
17851 @end group
17852 @end smallexample
17853
17854 @noindent
17855 Attribute @code{Library_Interface} has a non-empty string list value,
17856 each string in the list designating a unit contained in an immediate source
17857 of the project file.
17858
17859 When a Stand-alone Library is built, first the binder is invoked to build
17860 a package whose name depends on the library name
17861 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17862 This binder-generated package includes initialization and
17863 finalization procedures whose
17864 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17865 in the example
17866 above). The object corresponding to this package is included in the library.
17867
17868 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17869 calling of these procedures if a static SAL is built, or if a shared SAL
17870 is built
17871 with the project-level attribute @code{Library_Auto_Init} set to
17872 @code{"false"}.
17873
17874 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17875 (those that are listed in attribute @code{Library_Interface}) are copied to
17876 the Library Directory. As a consequence, only the Interface Units may be
17877 imported from Ada units outside of the library. If other units are imported,
17878 the binding phase will fail.
17879
17880 The attribute @code{Library_Src_Dir} may be specified for a
17881 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17882 single string value. Its value must be the path (absolute or relative to the
17883 project directory) of an existing directory. This directory cannot be the
17884 object directory or one of the source directories, but it can be the same as
17885 the library directory. The sources of the Interface
17886 Units of the library that are needed by an Ada client of the library will be
17887 copied to the designated directory, called the Interface Copy directory.
17888 These sources include the specs of the Interface Units, but they may also
17889 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17890 are used, or when there is a generic unit in the spec. Before the sources
17891 are copied to the Interface Copy directory, an attempt is made to delete all
17892 files in the Interface Copy directory.
17893
17894 Building stand-alone libraries by hand is somewhat tedious, but for those
17895 occasions when it is necessary here are the steps that you need to perform:
17896 @itemize @bullet
17897 @item
17898 Compile all library sources.
17899
17900 @item
17901 Invoke the binder with the switch @option{-n} (No Ada main program),
17902 with all the @file{ALI} files of the interfaces, and
17903 with the switch @option{-L} to give specific names to the @code{init}
17904 and @code{final} procedures.  For example:
17905 @smallexample
17906   gnatbind -n int1.ali int2.ali -Lsal1
17907 @end smallexample
17908
17909 @item
17910 Compile the binder generated file:
17911 @smallexample
17912   gcc -c b~int2.adb
17913 @end smallexample
17914
17915 @item
17916 Link the dynamic library with all the necessary object files,
17917 indicating to the linker the names of the @code{init} (and possibly
17918 @code{final}) procedures for automatic initialization (and finalization).
17919 The built library should be placed in a directory different from
17920 the object directory.
17921
17922 @item
17923 Copy the @code{ALI} files of the interface to the library directory,
17924 add in this copy an indication that it is an interface to a SAL
17925 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17926 with letter ``P'') and make the modified copy of the @file{ALI} file
17927 read-only.
17928 @end itemize
17929
17930 @noindent
17931 Using SALs is not different from using other libraries
17932 (see @ref{Using a library}).
17933
17934 @node Creating a Stand-alone Library to be used in a non-Ada context
17935 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17936
17937 @noindent
17938 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17939 a non-Ada context.
17940
17941 The only extra step required is to ensure that library interface subprograms
17942 are compatible with the main program, by means of @code{pragma Export}
17943 or @code{pragma Convention}.
17944
17945 Here is an example of simple library interface for use with C main program:
17946
17947 @smallexample @c ada
17948 package Interface is
17949
17950    procedure Do_Something;
17951    pragma Export (C, Do_Something, "do_something");
17952
17953    procedure Do_Something_Else;
17954    pragma Export (C, Do_Something_Else, "do_something_else");
17955
17956 end Interface;
17957 @end smallexample
17958
17959 @noindent
17960 On the foreign language side, you must provide a ``foreign'' view of the
17961 library interface; remember that it should contain elaboration routines in
17962 addition to interface subprograms.
17963
17964 The example below shows the content of @code{mylib_interface.h} (note
17965 that there is no rule for the naming of this file, any name can be used)
17966 @smallexample
17967 /* the library elaboration procedure */
17968 extern void mylibinit (void);
17969
17970 /* the library finalization procedure */
17971 extern void mylibfinal (void);
17972
17973 /* the interface exported by the library */
17974 extern void do_something (void);
17975 extern void do_something_else (void);
17976 @end smallexample
17977
17978 @noindent
17979 Libraries built as explained above can be used from any program, provided
17980 that the elaboration procedures (named @code{mylibinit} in the previous
17981 example) are called before the library services are used. Any number of
17982 libraries can be used simultaneously, as long as the elaboration
17983 procedure of each library is called.
17984
17985 Below is an example of a C program that uses the @code{mylib} library.
17986
17987 @smallexample
17988 #include "mylib_interface.h"
17989
17990 int
17991 main (void)
17992 @{
17993    /* First, elaborate the library before using it */
17994    mylibinit ();
17995
17996    /* Main program, using the library exported entities */
17997    do_something ();
17998    do_something_else ();
17999
18000    /* Library finalization at the end of the program */
18001    mylibfinal ();
18002    return 0;
18003 @}
18004 @end smallexample
18005
18006 @noindent
18007 Note that invoking any library finalization procedure generated by
18008 @code{gnatbind} shuts down the Ada run-time environment.
18009 Consequently, the
18010 finalization of all Ada libraries must be performed at the end of the program.
18011 No call to these libraries or to the Ada run-time library should be made
18012 after the finalization phase.
18013
18014 @node Restrictions in Stand-alone Libraries
18015 @subsection Restrictions in Stand-alone Libraries
18016
18017 @noindent
18018 The pragmas listed below should be used with caution inside libraries,
18019 as they can create incompatibilities with other Ada libraries:
18020 @itemize @bullet
18021 @item pragma @code{Locking_Policy}
18022 @item pragma @code{Queuing_Policy}
18023 @item pragma @code{Task_Dispatching_Policy}
18024 @item pragma @code{Unreserve_All_Interrupts}
18025 @end itemize
18026
18027 @noindent
18028 When using a library that contains such pragmas, the user must make sure
18029 that all libraries use the same pragmas with the same values. Otherwise,
18030 @code{Program_Error} will
18031 be raised during the elaboration of the conflicting
18032 libraries. The usage of these pragmas and its consequences for the user
18033 should therefore be well documented.
18034
18035 Similarly, the traceback in the exception occurrence mechanism should be
18036 enabled or disabled in a consistent manner across all libraries.
18037 Otherwise, Program_Error will be raised during the elaboration of the
18038 conflicting libraries.
18039
18040 If the @code{Version} or @code{Body_Version}
18041 attributes are used inside a library, then you need to
18042 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18043 libraries, so that version identifiers can be properly computed.
18044 In practice these attributes are rarely used, so this is unlikely
18045 to be a consideration.
18046
18047 @node  Rebuilding the GNAT Run-Time Library
18048 @section Rebuilding the GNAT Run-Time Library
18049 @cindex GNAT Run-Time Library, rebuilding
18050 @cindex Building the GNAT Run-Time Library
18051 @cindex Rebuilding the GNAT Run-Time Library
18052 @cindex Run-Time Library, rebuilding
18053
18054 @noindent
18055 It may be useful to recompile the GNAT library in various contexts, the
18056 most important one being the use of partition-wide configuration pragmas
18057 such as @code{Normalize_Scalars}. A special Makefile called
18058 @code{Makefile.adalib} is provided to that effect and can be found in
18059 the directory containing the GNAT library. The location of this
18060 directory depends on the way the GNAT environment has been installed and can
18061 be determined by means of the command:
18062
18063 @smallexample
18064 $ gnatls -v
18065 @end smallexample
18066
18067 @noindent
18068 The last entry in the object search path usually contains the
18069 gnat library. This Makefile contains its own documentation and in
18070 particular the set of instructions needed to rebuild a new library and
18071 to use it.
18072
18073 @node Using the GNU make Utility
18074 @chapter Using the GNU @code{make} Utility
18075 @findex make
18076
18077 @noindent
18078 This chapter offers some examples of makefiles that solve specific
18079 problems. It does not explain how to write a makefile (see the GNU make
18080 documentation), nor does it try to replace the @command{gnatmake} utility
18081 (@pxref{The GNAT Make Program gnatmake}).
18082
18083 All the examples in this section are specific to the GNU version of
18084 make. Although @code{make} is a standard utility, and the basic language
18085 is the same, these examples use some advanced features found only in
18086 @code{GNU make}.
18087
18088 @menu
18089 * Using gnatmake in a Makefile::
18090 * Automatically Creating a List of Directories::
18091 * Generating the Command Line Switches::
18092 * Overcoming Command Line Length Limits::
18093 @end menu
18094
18095 @node Using gnatmake in a Makefile
18096 @section Using gnatmake in a Makefile
18097 @findex makefile
18098 @cindex GNU make
18099
18100 @noindent
18101 Complex project organizations can be handled in a very powerful way by
18102 using GNU make combined with gnatmake. For instance, here is a Makefile
18103 which allows you to build each subsystem of a big project into a separate
18104 shared library. Such a makefile allows you to significantly reduce the link
18105 time of very big applications while maintaining full coherence at
18106 each step of the build process.
18107
18108 The list of dependencies are handled automatically by
18109 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18110 the appropriate directories.
18111
18112 Note that you should also read the example on how to automatically
18113 create the list of directories
18114 (@pxref{Automatically Creating a List of Directories})
18115 which might help you in case your project has a lot of subdirectories.
18116
18117 @smallexample
18118 @iftex
18119 @leftskip=0cm
18120 @font@heightrm=cmr8
18121 @heightrm
18122 @end iftex
18123 ## This Makefile is intended to be used with the following directory
18124 ## configuration:
18125 ##  - The sources are split into a series of csc (computer software components)
18126 ##    Each of these csc is put in its own directory.
18127 ##    Their name are referenced by the directory names.
18128 ##    They will be compiled into shared library (although this would also work
18129 ##    with static libraries
18130 ##  - The main program (and possibly other packages that do not belong to any
18131 ##    csc is put in the top level directory (where the Makefile is).
18132 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
18133 ##                    \_ second_csc (sources) __ lib (will contain the library)
18134 ##                    \_ ...
18135 ## Although this Makefile is build for shared library, it is easy to modify
18136 ## to build partial link objects instead (modify the lines with -shared and
18137 ## gnatlink below)
18138 ##
18139 ## With this makefile, you can change any file in the system or add any new
18140 ## file, and everything will be recompiled correctly (only the relevant shared
18141 ## objects will be recompiled, and the main program will be re-linked).
18142
18143 # The list of computer software component for your project. This might be
18144 # generated automatically.
18145 CSC_LIST=aa bb cc
18146
18147 # Name of the main program (no extension)
18148 MAIN=main
18149
18150 # If we need to build objects with -fPIC, uncomment the following line
18151 #NEED_FPIC=-fPIC
18152
18153 # The following variable should give the directory containing libgnat.so
18154 # You can get this directory through 'gnatls -v'. This is usually the last
18155 # directory in the Object_Path.
18156 GLIB=...
18157
18158 # The directories for the libraries
18159 # (This macro expands the list of CSC to the list of shared libraries, you
18160 # could simply use the expanded form :
18161 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18162 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18163
18164 $@{MAIN@}: objects $@{LIB_DIR@}
18165     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18166     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18167
18168 objects::
18169     # recompile the sources
18170     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18171
18172 # Note: In a future version of GNAT, the following commands will be simplified
18173 # by a new tool, gnatmlib
18174 $@{LIB_DIR@}:
18175     mkdir -p $@{dir $@@ @}
18176     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18177     cd $@{dir $@@ @}; cp -f ../*.ali .
18178
18179 # The dependencies for the modules
18180 # Note that we have to force the expansion of *.o, since in some cases
18181 # make won't be able to do it itself.
18182 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18183 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18184 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18185
18186 # Make sure all of the shared libraries are in the path before starting the
18187 # program
18188 run::
18189     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18190
18191 clean::
18192     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18193     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18194     $@{RM@} $@{CSC_LIST:%=%/*.o@}
18195     $@{RM@} *.o *.ali $@{MAIN@}
18196 @end smallexample
18197
18198 @node Automatically Creating a List of Directories
18199 @section Automatically Creating a List of Directories
18200
18201 @noindent
18202 In most makefiles, you will have to specify a list of directories, and
18203 store it in a variable. For small projects, it is often easier to
18204 specify each of them by hand, since you then have full control over what
18205 is the proper order for these directories, which ones should be
18206 included...
18207
18208 However, in larger projects, which might involve hundreds of
18209 subdirectories, it might be more convenient to generate this list
18210 automatically.
18211
18212 The example below presents two methods. The first one, although less
18213 general, gives you more control over the list. It involves wildcard
18214 characters, that are automatically expanded by @code{make}. Its
18215 shortcoming is that you need to explicitly specify some of the
18216 organization of your project, such as for instance the directory tree
18217 depth, whether some directories are found in a separate tree,...
18218
18219 The second method is the most general one. It requires an external
18220 program, called @code{find}, which is standard on all Unix systems. All
18221 the directories found under a given root directory will be added to the
18222 list.
18223
18224 @smallexample
18225 @iftex
18226 @leftskip=0cm
18227 @font@heightrm=cmr8
18228 @heightrm
18229 @end iftex
18230 # The examples below are based on the following directory hierarchy:
18231 # All the directories can contain any number of files
18232 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18233 #                       ->  ab
18234 #                       ->  ac
18235 #                ->  b  ->  ba  ->  baa
18236 #                       ->  bb
18237 #                       ->  bc
18238 # This Makefile creates a variable called DIRS, that can be reused any time
18239 # you need this list (see the other examples in this section)
18240
18241 # The root of your project's directory hierarchy
18242 ROOT_DIRECTORY=.
18243
18244 ####
18245 # First method: specify explicitly the list of directories
18246 # This allows you to specify any subset of all the directories you need.
18247 ####
18248
18249 DIRS := a/aa/ a/ab/ b/ba/
18250
18251 ####
18252 # Second method: use wildcards
18253 # Note that the argument(s) to wildcard below should end with a '/'.
18254 # Since wildcards also return file names, we have to filter them out
18255 # to avoid duplicate directory names.
18256 # We thus use make's @code{dir} and @code{sort} functions.
18257 # It sets DIRs to the following value (note that the directories aaa and baa
18258 # are not given, unless you change the arguments to wildcard).
18259 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18260 ####
18261
18262 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18263                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18264
18265 ####
18266 # Third method: use an external program
18267 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18268 # This is the most complete command: it sets DIRs to the following value:
18269 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18270 ####
18271
18272 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18273
18274 @end smallexample
18275
18276 @node Generating the Command Line Switches
18277 @section Generating the Command Line Switches
18278
18279 @noindent
18280 Once you have created the list of directories as explained in the
18281 previous section (@pxref{Automatically Creating a List of Directories}),
18282 you can easily generate the command line arguments to pass to gnatmake.
18283
18284 For the sake of completeness, this example assumes that the source path
18285 is not the same as the object path, and that you have two separate lists
18286 of directories.
18287
18288 @smallexample
18289 # see "Automatically creating a list of directories" to create
18290 # these variables
18291 SOURCE_DIRS=
18292 OBJECT_DIRS=
18293
18294 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18295 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18296
18297 all:
18298         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18299 @end smallexample
18300
18301 @node Overcoming Command Line Length Limits
18302 @section Overcoming Command Line Length Limits
18303
18304 @noindent
18305 One problem that might be encountered on big projects is that many
18306 operating systems limit the length of the command line. It is thus hard to give
18307 gnatmake the list of source and object directories.
18308
18309 This example shows how you can set up environment variables, which will
18310 make @command{gnatmake} behave exactly as if the directories had been
18311 specified on the command line, but have a much higher length limit (or
18312 even none on most systems).
18313
18314 It assumes that you have created a list of directories in your Makefile,
18315 using one of the methods presented in
18316 @ref{Automatically Creating a List of Directories}.
18317 For the sake of completeness, we assume that the object
18318 path (where the ALI files are found) is different from the sources patch.
18319
18320 Note a small trick in the Makefile below: for efficiency reasons, we
18321 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18322 expanded immediately by @code{make}. This way we overcome the standard
18323 make behavior which is to expand the variables only when they are
18324 actually used.
18325
18326 On Windows, if you are using the standard Windows command shell, you must
18327 replace colons with semicolons in the assignments to these variables.
18328
18329 @smallexample
18330 @iftex
18331 @leftskip=0cm
18332 @font@heightrm=cmr8
18333 @heightrm
18334 @end iftex
18335 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18336 # This is the same thing as putting the -I arguments on the command line.
18337 # (the equivalent of using -aI on the command line would be to define
18338 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18339 # You can of course have different values for these variables.
18340 #
18341 # Note also that we need to keep the previous values of these variables, since
18342 # they might have been set before running 'make' to specify where the GNAT
18343 # library is installed.
18344
18345 # see "Automatically creating a list of directories" to create these
18346 # variables
18347 SOURCE_DIRS=
18348 OBJECT_DIRS=
18349
18350 empty:=
18351 space:=$@{empty@} $@{empty@}
18352 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18353 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18354 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18355 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18356 export ADA_INCLUDE_PATH
18357 export ADA_OBJECT_PATH
18358
18359 all:
18360         gnatmake main_unit
18361 @end smallexample
18362 @end ifclear
18363
18364 @node Memory Management Issues
18365 @chapter Memory Management Issues
18366
18367 @noindent
18368 This chapter describes some useful memory pools provided in the GNAT library
18369 and in particular the GNAT Debug Pool facility, which can be used to detect
18370 incorrect uses of access values (including ``dangling references'').
18371 @ifclear vms
18372 It also describes the @command{gnatmem} tool, which can be used to track down
18373 ``memory leaks''.
18374 @end ifclear
18375
18376 @menu
18377 * Some Useful Memory Pools::
18378 * The GNAT Debug Pool Facility::
18379 @ifclear vms
18380 * The gnatmem Tool::
18381 @end ifclear
18382 @end menu
18383
18384 @node Some Useful Memory Pools
18385 @section Some Useful Memory Pools
18386 @findex Memory Pool
18387 @cindex storage, pool
18388
18389 @noindent
18390 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18391 storage pool. Allocations use the standard system call @code{malloc} while
18392 deallocations use the standard system call @code{free}. No reclamation is
18393 performed when the pool goes out of scope. For performance reasons, the
18394 standard default Ada allocators/deallocators do not use any explicit storage
18395 pools but if they did, they could use this storage pool without any change in
18396 behavior. That is why this storage pool is used  when the user
18397 manages to make the default implicit allocator explicit as in this example:
18398 @smallexample @c ada
18399    type T1 is access Something;
18400     -- no Storage pool is defined for T2
18401    type T2 is access Something_Else;
18402    for T2'Storage_Pool use T1'Storage_Pool;
18403    -- the above is equivalent to
18404    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18405 @end smallexample
18406
18407 @noindent
18408 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18409 pool. The allocation strategy is similar to @code{Pool_Local}'s
18410 except that the all
18411 storage allocated with this pool is reclaimed when the pool object goes out of
18412 scope. This pool provides a explicit mechanism similar to the implicit one
18413 provided by several Ada 83 compilers for allocations performed through a local
18414 access type and whose purpose was to reclaim memory when exiting the
18415 scope of a given local access. As an example, the following program does not
18416 leak memory even though it does not perform explicit deallocation:
18417
18418 @smallexample @c ada
18419 with System.Pool_Local;
18420 procedure Pooloc1 is
18421    procedure Internal is
18422       type A is access Integer;
18423       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18424       for A'Storage_Pool use X;
18425       v : A;
18426    begin
18427       for I in  1 .. 50 loop
18428          v := new Integer;
18429       end loop;
18430    end Internal;
18431 begin
18432    for I in  1 .. 100 loop
18433       Internal;
18434    end loop;
18435 end Pooloc1;
18436 @end smallexample
18437
18438 @noindent
18439 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18440 @code{Storage_Size} is specified for an access type.
18441 The whole storage for the pool is
18442 allocated at once, usually on the stack at the point where the access type is
18443 elaborated. It is automatically reclaimed when exiting the scope where the
18444 access type is defined. This package is not intended to be used directly by the
18445 user and it is implicitly used for each such declaration:
18446
18447 @smallexample @c ada
18448    type T1 is access Something;
18449    for T1'Storage_Size use 10_000;
18450 @end smallexample
18451
18452 @node The GNAT Debug Pool Facility
18453 @section The GNAT Debug Pool Facility
18454 @findex Debug Pool
18455 @cindex storage, pool, memory corruption
18456
18457 @noindent
18458 The use of unchecked deallocation and unchecked conversion can easily
18459 lead to incorrect memory references. The problems generated by such
18460 references are usually difficult to tackle because the symptoms can be
18461 very remote from the origin of the problem. In such cases, it is
18462 very helpful to detect the problem as early as possible. This is the
18463 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18464
18465 In order to use the GNAT specific debugging pool, the user must
18466 associate a debug pool object with each of the access types that may be
18467 related to suspected memory problems. See Ada Reference Manual 13.11.
18468 @smallexample @c ada
18469 type Ptr is access Some_Type;
18470 Pool : GNAT.Debug_Pools.Debug_Pool;
18471 for Ptr'Storage_Pool use Pool;
18472 @end smallexample
18473
18474 @noindent
18475 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18476 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18477 allow the user to redefine allocation and deallocation strategies. They
18478 also provide a checkpoint for each dereference, through the use of
18479 the primitive operation @code{Dereference} which is implicitly called at
18480 each dereference of an access value.
18481
18482 Once an access type has been associated with a debug pool, operations on
18483 values of the type may raise four distinct exceptions,
18484 which correspond to four potential kinds of memory corruption:
18485 @itemize @bullet
18486 @item
18487 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18488 @item
18489 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18490 @item
18491 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18492 @item
18493 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18494 @end itemize
18495
18496 @noindent
18497 For types associated with a Debug_Pool, dynamic allocation is performed using
18498 the standard GNAT allocation routine. References to all allocated chunks of
18499 memory are kept in an internal dictionary. Several deallocation strategies are
18500 provided, whereupon the user can choose to release the memory to the system,
18501 keep it allocated for further invalid access checks, or fill it with an easily
18502 recognizable pattern for debug sessions. The memory pattern is the old IBM
18503 hexadecimal convention: @code{16#DEADBEEF#}.
18504
18505 See the documentation in the file g-debpoo.ads for more information on the
18506 various strategies.
18507
18508 Upon each dereference, a check is made that the access value denotes a
18509 properly allocated memory location. Here is a complete example of use of
18510 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18511 @smallexample @c ada
18512 @iftex
18513 @leftskip=0cm
18514 @end iftex
18515 with Gnat.Io; use Gnat.Io;
18516 with Unchecked_Deallocation;
18517 with Unchecked_Conversion;
18518 with GNAT.Debug_Pools;
18519 with System.Storage_Elements;
18520 with Ada.Exceptions; use Ada.Exceptions;
18521 procedure Debug_Pool_Test is
18522
18523    type T is access Integer;
18524    type U is access all T;
18525
18526    P : GNAT.Debug_Pools.Debug_Pool;
18527    for T'Storage_Pool use P;
18528
18529    procedure Free is new Unchecked_Deallocation (Integer, T);
18530    function UC is new Unchecked_Conversion (U, T);
18531    A, B : aliased T;
18532
18533    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18534
18535 begin
18536    Info (P);
18537    A := new Integer;
18538    B := new Integer;
18539    B := A;
18540    Info (P);
18541    Free (A);
18542    begin
18543       Put_Line (Integer'Image(B.all));
18544    exception
18545       when E : others => Put_Line ("raised: " & Exception_Name (E));
18546    end;
18547    begin
18548       Free (B);
18549    exception
18550       when E : others => Put_Line ("raised: " & Exception_Name (E));
18551    end;
18552    B := UC(A'Access);
18553    begin
18554       Put_Line (Integer'Image(B.all));
18555    exception
18556       when E : others => Put_Line ("raised: " & Exception_Name (E));
18557    end;
18558    begin
18559       Free (B);
18560    exception
18561       when E : others => Put_Line ("raised: " & Exception_Name (E));
18562    end;
18563    Info (P);
18564 end Debug_Pool_Test;
18565 @end smallexample
18566
18567 @noindent
18568 The debug pool mechanism provides the following precise diagnostics on the
18569 execution of this erroneous program:
18570 @smallexample
18571 Debug Pool info:
18572   Total allocated bytes :  0
18573   Total deallocated bytes :  0
18574   Current Water Mark:  0
18575   High Water Mark:  0
18576
18577 Debug Pool info:
18578   Total allocated bytes :  8
18579   Total deallocated bytes :  0
18580   Current Water Mark:  8
18581   High Water Mark:  8
18582
18583 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18584 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18585 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18586 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18587 Debug Pool info:
18588   Total allocated bytes :  8
18589   Total deallocated bytes :  4
18590   Current Water Mark:  4
18591   High Water Mark:  8
18592 @end smallexample
18593
18594 @ifclear vms
18595 @node The gnatmem Tool
18596 @section The @command{gnatmem} Tool
18597 @findex gnatmem
18598
18599 @noindent
18600 The @code{gnatmem} utility monitors dynamic allocation and
18601 deallocation activity in a program, and displays information about
18602 incorrect deallocations and possible sources of memory leaks.
18603 It provides three type of information:
18604 @itemize @bullet
18605 @item
18606 General information concerning memory management, such as the total
18607 number of allocations and deallocations, the amount of allocated
18608 memory and the high water mark, i.e. the largest amount of allocated
18609 memory in the course of program execution.
18610
18611 @item
18612 Backtraces for all incorrect deallocations, that is to say deallocations
18613 which do not correspond to a valid allocation.
18614
18615 @item
18616 Information on each allocation that is potentially the origin of a memory
18617 leak.
18618 @end itemize
18619
18620 @menu
18621 * Running gnatmem::
18622 * Switches for gnatmem::
18623 * Example of gnatmem Usage::
18624 @end menu
18625
18626 @node Running gnatmem
18627 @subsection Running @code{gnatmem}
18628
18629 @noindent
18630 @code{gnatmem} makes use of the output created by the special version of
18631 allocation and deallocation routines that record call information. This
18632 allows to obtain accurate dynamic memory usage history at a minimal cost to
18633 the execution speed. Note however, that @code{gnatmem} is not supported on
18634 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18635 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18636
18637 @noindent
18638 The @code{gnatmem} command has the form
18639
18640 @smallexample
18641    $ gnatmem [switches] user_program
18642 @end smallexample
18643
18644 @noindent
18645 The program must have been linked with the instrumented version of the
18646 allocation and deallocation routines. This is done by linking with the
18647 @file{libgmem.a} library. For correct symbolic backtrace information,
18648 the user program should be compiled with debugging options
18649 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18650
18651 @smallexample
18652 $ gnatmake -g my_program -largs -lgmem
18653 @end smallexample
18654
18655 @noindent
18656 As library @file{libgmem.a} contains an alternate body for package
18657 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18658 when an executable is linked with library @file{libgmem.a}. It is then not
18659 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18660
18661 @noindent
18662 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18663 This file contains information about all allocations and deallocations
18664 performed by the program. It is produced by the instrumented allocations and
18665 deallocations routines and will be used by @code{gnatmem}.
18666
18667 In order to produce symbolic backtrace information for allocations and
18668 deallocations performed by the GNAT run-time library, you need to use a
18669 version of that library that has been compiled with the @option{-g} switch
18670 (see @ref{Rebuilding the GNAT Run-Time Library}).
18671
18672 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18673 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18674 @code{-i} switch, gnatmem will assume that this file can be found in the
18675 current directory. For example, after you have executed @file{my_program},
18676 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18677
18678 @smallexample
18679 $ gnatmem my_program
18680 @end smallexample
18681
18682 @noindent
18683 This will produce the output with the following format:
18684
18685 *************** debut cc
18686 @smallexample
18687 $ gnatmem my_program
18688
18689 Global information
18690 ------------------
18691    Total number of allocations        :  45
18692    Total number of deallocations      :   6
18693    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18694    High Water Mark                    :  11.40 Kilobytes
18695
18696 .
18697 .
18698 .
18699 Allocation Root # 2
18700 -------------------
18701  Number of non freed allocations    :  11
18702  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18703  High Water Mark                    :   1.27 Kilobytes
18704  Backtrace                          :
18705    my_program.adb:23 my_program.alloc
18706 .
18707 .
18708 .
18709 @end smallexample
18710
18711 The first block of output gives general information. In this case, the
18712 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18713 Unchecked_Deallocation routine occurred.
18714
18715 @noindent
18716 Subsequent paragraphs display  information on all allocation roots.
18717 An allocation root is a specific point in the execution of the program
18718 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18719 construct. This root is represented by an execution backtrace (or subprogram
18720 call stack). By default the backtrace depth for allocations roots is 1, so
18721 that a root corresponds exactly to a source location. The backtrace can
18722 be made deeper, to make the root more specific.
18723
18724 @node Switches for gnatmem
18725 @subsection Switches for @code{gnatmem}
18726
18727 @noindent
18728 @code{gnatmem} recognizes the following switches:
18729
18730 @table @option
18731
18732 @item -q
18733 @cindex @option{-q} (@code{gnatmem})
18734 Quiet. Gives the minimum output needed to identify the origin of the
18735 memory leaks. Omits statistical information.
18736
18737 @item @var{N}
18738 @cindex @var{N} (@code{gnatmem})
18739 N is an integer literal (usually between 1 and 10) which controls the
18740 depth of the backtraces defining allocation root. The default value for
18741 N is 1. The deeper the backtrace, the more precise the localization of
18742 the root. Note that the total number of roots can depend on this
18743 parameter. This parameter must be specified @emph{before} the name of the
18744 executable to be analyzed, to avoid ambiguity.
18745
18746 @item -b n
18747 @cindex @option{-b} (@code{gnatmem})
18748 This switch has the same effect as just depth parameter.
18749
18750 @item -i @var{file}
18751 @cindex @option{-i} (@code{gnatmem})
18752 Do the @code{gnatmem} processing starting from @file{file}, rather than
18753 @file{gmem.out} in the current directory.
18754
18755 @item -m n
18756 @cindex @option{-m} (@code{gnatmem})
18757 This switch causes @code{gnatmem} to mask the allocation roots that have less
18758 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18759 examine even the roots that didn't result in leaks.
18760
18761 @item -s order
18762 @cindex @option{-s} (@code{gnatmem})
18763 This switch causes @code{gnatmem} to sort the allocation roots according to the
18764 specified order of sort criteria, each identified by a single letter. The
18765 currently supported criteria are @code{n, h, w} standing respectively for
18766 number of unfreed allocations, high watermark, and final watermark
18767 corresponding to a specific root. The default order is @code{nwh}.
18768
18769 @end table
18770
18771 @node Example of gnatmem Usage
18772 @subsection Example of @code{gnatmem} Usage
18773
18774 @noindent
18775 The following example shows the use of @code{gnatmem}
18776 on a simple memory-leaking program.
18777 Suppose that we have the following Ada program:
18778
18779 @smallexample @c ada
18780 @group
18781 @cartouche
18782 with Unchecked_Deallocation;
18783 procedure Test_Gm is
18784
18785    type T is array (1..1000) of Integer;
18786    type Ptr is access T;
18787    procedure Free is new Unchecked_Deallocation (T, Ptr);
18788    A : Ptr;
18789
18790    procedure My_Alloc is
18791    begin
18792       A := new T;
18793    end My_Alloc;
18794
18795    procedure My_DeAlloc is
18796       B : Ptr := A;
18797    begin
18798       Free (B);
18799    end My_DeAlloc;
18800
18801 begin
18802    My_Alloc;
18803    for I in 1 .. 5 loop
18804       for J in I .. 5 loop
18805          My_Alloc;
18806       end loop;
18807       My_Dealloc;
18808    end loop;
18809 end;
18810 @end cartouche
18811 @end group
18812 @end smallexample
18813
18814 @noindent
18815 The program needs to be compiled with debugging option and linked with
18816 @code{gmem} library:
18817
18818 @smallexample
18819 $ gnatmake -g test_gm -largs -lgmem
18820 @end smallexample
18821
18822 @noindent
18823 Then we execute the program as usual:
18824
18825 @smallexample
18826 $ test_gm
18827 @end smallexample
18828
18829 @noindent
18830 Then @code{gnatmem} is invoked simply with
18831 @smallexample
18832 $ gnatmem test_gm
18833 @end smallexample
18834
18835 @noindent
18836 which produces the following output (result may vary on different platforms):
18837
18838 @smallexample
18839 Global information
18840 ------------------
18841    Total number of allocations        :  18
18842    Total number of deallocations      :   5
18843    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18844    High Water Mark                    :  56.90 Kilobytes
18845
18846 Allocation Root # 1
18847 -------------------
18848  Number of non freed allocations    :  11
18849  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18850  High Water Mark                    :  46.88 Kilobytes
18851  Backtrace                          :
18852    test_gm.adb:11 test_gm.my_alloc
18853
18854 Allocation Root # 2
18855 -------------------
18856  Number of non freed allocations    :   1
18857  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18858  High Water Mark                    :  10.02 Kilobytes
18859  Backtrace                          :
18860    s-secsta.adb:81 system.secondary_stack.ss_init
18861
18862 Allocation Root # 3
18863 -------------------
18864  Number of non freed allocations    :   1
18865  Final Water Mark (non freed mem)   :  12 Bytes
18866  High Water Mark                    :  12 Bytes
18867  Backtrace                          :
18868    s-secsta.adb:181 system.secondary_stack.ss_init
18869 @end smallexample
18870
18871 @noindent
18872 Note that the GNAT run time contains itself a certain number of
18873 allocations that have no  corresponding deallocation,
18874 as shown here for root #2 and root
18875 #3. This is a normal behavior when the number of non freed allocations
18876 is one, it allocates dynamic data structures that the run time needs for
18877 the complete lifetime of the program. Note also that there is only one
18878 allocation root in the user program with a single line back trace:
18879 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18880 program shows that 'My_Alloc' is called at 2 different points in the
18881 source (line 21 and line 24). If those two allocation roots need to be
18882 distinguished, the backtrace depth parameter can be used:
18883
18884 @smallexample
18885 $ gnatmem 3 test_gm
18886 @end smallexample
18887
18888 @noindent
18889 which will give the following output:
18890
18891 @smallexample
18892 Global information
18893 ------------------
18894    Total number of allocations        :  18
18895    Total number of deallocations      :   5
18896    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18897    High Water Mark                    :  56.90 Kilobytes
18898
18899 Allocation Root # 1
18900 -------------------
18901  Number of non freed allocations    :  10
18902  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18903  High Water Mark                    :  42.97 Kilobytes
18904  Backtrace                          :
18905    test_gm.adb:11 test_gm.my_alloc
18906    test_gm.adb:24 test_gm
18907    b_test_gm.c:52 main
18908
18909 Allocation Root # 2
18910 -------------------
18911  Number of non freed allocations    :   1
18912  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18913  High Water Mark                    :  10.02 Kilobytes
18914  Backtrace                          :
18915    s-secsta.adb:81  system.secondary_stack.ss_init
18916    s-secsta.adb:283 <system__secondary_stack___elabb>
18917    b_test_gm.c:33   adainit
18918
18919 Allocation Root # 3
18920 -------------------
18921  Number of non freed allocations    :   1
18922  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18923  High Water Mark                    :   3.91 Kilobytes
18924  Backtrace                          :
18925    test_gm.adb:11 test_gm.my_alloc
18926    test_gm.adb:21 test_gm
18927    b_test_gm.c:52 main
18928
18929 Allocation Root # 4
18930 -------------------
18931  Number of non freed allocations    :   1
18932  Final Water Mark (non freed mem)   :  12 Bytes
18933  High Water Mark                    :  12 Bytes
18934  Backtrace                          :
18935    s-secsta.adb:181 system.secondary_stack.ss_init
18936    s-secsta.adb:283 <system__secondary_stack___elabb>
18937    b_test_gm.c:33   adainit
18938 @end smallexample
18939
18940 @noindent
18941 The allocation root #1 of the first example has been split in 2 roots #1
18942 and #3 thanks to the more precise associated backtrace.
18943
18944 @end ifclear
18945
18946 @node Stack Related Facilities
18947 @chapter Stack Related Facilities
18948
18949 @noindent
18950 This chapter describes some useful tools associated with stack
18951 checking and analysis. In
18952 particular, it deals with dynamic and static stack usage measurements.
18953
18954 @menu
18955 * Stack Overflow Checking::
18956 * Static Stack Usage Analysis::
18957 * Dynamic Stack Usage Analysis::
18958 @end menu
18959
18960 @node Stack Overflow Checking
18961 @section Stack Overflow Checking
18962 @cindex Stack Overflow Checking
18963 @cindex -fstack-check
18964
18965 @noindent
18966 For most operating systems, @command{gcc} does not perform stack overflow
18967 checking by default. This means that if the main environment task or
18968 some other task exceeds the available stack space, then unpredictable
18969 behavior will occur. Most native systems offer some level of protection by
18970 adding a guard page at the end of each task stack. This mechanism is usually
18971 not enough for dealing properly with stack overflow situations because
18972 a large local variable could ``jump'' above the guard page.
18973 Furthermore, when the
18974 guard page is hit, there may not be any space left on the stack for executing
18975 the exception propagation code. Enabling stack checking avoids
18976 such situations.
18977
18978 To activate stack checking, compile all units with the gcc option
18979 @option{-fstack-check}. For example:
18980
18981 @smallexample
18982 gcc -c -fstack-check package1.adb
18983 @end smallexample
18984
18985 @noindent
18986 Units compiled with this option will generate extra instructions to check
18987 that any use of the stack (for procedure calls or for declaring local
18988 variables in declare blocks) does not exceed the available stack space.
18989 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18990
18991 For declared tasks, the stack size is controlled by the size
18992 given in an applicable @code{Storage_Size} pragma or by the value specified
18993 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18994 the default size as defined in the GNAT runtime otherwise.
18995
18996 For the environment task, the stack size depends on
18997 system defaults and is unknown to the compiler. Stack checking
18998 may still work correctly if a fixed
18999 size stack is allocated, but this cannot be guaranteed.
19000 To ensure that a clean exception is signalled for stack
19001 overflow, set the environment variable
19002 @code{GNAT_STACK_LIMIT} to indicate the maximum
19003 stack area that can be used, as in:
19004 @cindex GNAT_STACK_LIMIT
19005
19006 @smallexample
19007 SET GNAT_STACK_LIMIT 1600
19008 @end smallexample
19009
19010 @noindent
19011 The limit is given in kilobytes, so the above declaration would
19012 set the stack limit of the environment task to 1.6 megabytes.
19013 Note that the only purpose of this usage is to limit the amount
19014 of stack used by the environment task. If it is necessary to
19015 increase the amount of stack for the environment task, then this
19016 is an operating systems issue, and must be addressed with the
19017 appropriate operating systems commands.
19018
19019 @node Static Stack Usage Analysis
19020 @section Static Stack Usage Analysis
19021 @cindex Static Stack Usage Analysis
19022 @cindex -fstack-usage
19023
19024 @noindent
19025 A unit compiled with @option{-fstack-usage} will generate an extra file
19026 that specifies
19027 the maximum amount of stack used, on a per-function basis.
19028 The file has the same
19029 basename as the target object file with a @file{.su} extension.
19030 Each line of this file is made up of three fields:
19031
19032 @itemize
19033 @item
19034 The name of the function.
19035 @item
19036 A number of bytes.
19037 @item
19038 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19039 @end itemize
19040
19041 The second field corresponds to the size of the known part of the function
19042 frame.
19043
19044 The qualifier @code{static} means that the function frame size
19045 is purely static.
19046 It usually means that all local variables have a static size.
19047 In this case, the second field is a reliable measure of the function stack
19048 utilization.
19049
19050 The qualifier @code{dynamic} means that the function frame size is not static.
19051 It happens mainly when some local variables have a dynamic size. When this
19052 qualifier appears alone, the second field is not a reliable measure
19053 of the function stack analysis. When it is qualified with  @code{bounded}, it
19054 means that the second field is a reliable maximum of the function stack
19055 utilization.
19056
19057 @node Dynamic Stack Usage Analysis
19058 @section Dynamic Stack Usage Analysis
19059
19060 @noindent
19061 It is possible to measure the maximum amount of stack used by a task, by
19062 adding a switch to @command{gnatbind}, as:
19063
19064 @smallexample
19065 $ gnatbind -u0 file
19066 @end smallexample
19067
19068 @noindent
19069 With this option, at each task termination, its stack usage is  output on
19070 @file{stderr}.
19071 It is not always convenient to output the stack usage when the program
19072 is still running. Hence, it is possible to delay this output until program
19073 termination. for a given number of tasks specified as the argument of the
19074 @code{-u} option. For instance:
19075
19076 @smallexample
19077 $ gnatbind -u100 file
19078 @end smallexample
19079
19080 @noindent
19081 will buffer the stack usage information of the first 100 tasks to terminate and
19082 output this info at program termination. Results are displayed in four
19083 columns:
19084
19085 @noindent
19086 Index | Task Name | Stack Size | Actual Use
19087
19088 @noindent
19089 where:
19090
19091 @table @emph
19092 @item Index
19093 is a number associated with each task.
19094
19095 @item Task Name
19096 is the name of the task analyzed.
19097
19098 @item Stack Size
19099 is the maximum size for the stack. In order to prevent overflow,
19100 the real stack limit  is slightly larger than the Stack Size in order to allow
19101 proper recovery.
19102
19103 @item Actual Use
19104 is the measure done by the stack analyzer.
19105
19106 @end table
19107
19108 @noindent
19109 The environment task stack, e.g. the stack that contains the main unit, is
19110 only processed when the environment variable GNAT_STACK_LIMIT is set.
19111
19112 @c *********************************
19113 @node Verifying properties using gnatcheck
19114 @chapter Verifying properties using @command{gnatcheck}
19115 @findex gnatcheck
19116
19117 @noindent
19118 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19119 of Ada source files according to a given set of semantic rules.
19120
19121 In order to check compliance with a given rule, @command{gnatcheck} has to
19122 semantically analyze the Ada sources.
19123 Therefore, checks can only be performed on
19124 legal Ada units. Moreover, when a unit depends semantically upon units located
19125 outside the current directory, the source search path has to be provided when
19126 calling @command{gnatcheck}, either through a specified project file or
19127 through @command{gnatcheck} switches as described below.
19128
19129 The project support for @command{gnatcheck} is provided by the @command{gnat}
19130 driver.
19131
19132 Several rules are already implemented in @command{gnatcheck}. The list of such
19133 rules can be obtained with option @option{^-h^/HELP^} as described in the next
19134 section. A user can add new rules by modifying the @command{gnatcheck} code and
19135 rebuilding the tool. For adding a simple rule making some local checks, a small
19136 amount of straightforward ASIS-based programming is usually needed.
19137
19138 @noindent
19139 @command{gnatcheck} has the command-line interface of the form
19140
19141 @smallexample
19142 $ gnatcheck [@i{switches}]  @{@i{filename}@}
19143       [@i{^-files^/FILES^=@{arg_list_filename@}}]
19144       [@i{-cargs gcc_switches}] [@i{-rules rule_options}]
19145 @end smallexample
19146
19147 @noindent
19148 where
19149 @itemize @bullet
19150 @item
19151 @i{switches} specify the general tool options
19152
19153 @item
19154 Each @i{filename} is the name (including the extension) of a source
19155 file to process. ``Wildcards'' are allowed, and
19156 the file name may contain path information.
19157
19158 @item
19159 Each @i{arg_list_filename} is the name (including the extension) of a text
19160 file containing the names of the source files to process, separated by spaces
19161 or line breaks.
19162
19163 @item
19164 @i{-cargs gcc_switches} is a list of switches for
19165 @command{gcc}. They will be passed on to all compiler invocations made by
19166 @command{gnatcheck} to generate the ASIS trees. Here you can provide
19167 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19168 and use the @option{-gnatec} switch to set the configuration file.
19169
19170 @item
19171 @i{-rules rule_options} is a list of options for controlling a set of
19172 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options})
19173 @end itemize
19174
19175 @noindent
19176 Either a @i{filename} or an @i{arg_list_filename} needs to be supplied.
19177
19178 @menu
19179 * Format of the Report File::
19180 * General gnatcheck Switches::
19181 * gnatcheck Rule Options::
19182 * Add the Results of Compiler Checks to gnatcheck Output::
19183 @end menu
19184
19185 @node Format of the Report File
19186 @section Format of the Report File
19187
19188 @noindent
19189 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
19190 rule violations.
19191 It also creates, in the current
19192 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
19193 contains the complete report of the last gnatcheck run. This report contains:
19194 @itemize @bullet
19195 @item a list of the Ada source files being checked,
19196 @item a list of enabled and disabled rules,
19197 @item a list of the diagnostic messages, ordered in three different ways
19198 and collected in three separate
19199 sections. Section 1 contains the raw list of diagnostic messages. It
19200 corresponds to the output going to @file{stdout}. Section 2 contains
19201 messages ordered by rules.
19202 Section 3 contains messages ordered by source files.
19203 @end itemize
19204
19205 @node General gnatcheck Switches
19206 @section General @command{gnatcheck} Switches
19207
19208 @noindent
19209 The following switches control the general @command{gnatcheck} behavior
19210
19211 @table @option
19212 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
19213 @item ^-a^/ALL^
19214 Process all units including those with read-only ALI files such as
19215 those from GNAT Run-Time library.
19216
19217 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
19218 @item ^-h^/HELP^
19219 Print out the list of the currently implemented rules. For more details see
19220 the README file in the @command{gnatcheck} sources.
19221
19222 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
19223 @item ^-l^/LOCS^
19224 Use full source locations references in the report file. For a construct from
19225 a generic instantiation a full source location is a chain from the location
19226 of this construct in the generic unit to the place where this unit is
19227 instantiated.
19228
19229 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
19230 @item ^-q^/QUIET^
19231 Quiet mode. All the diagnoses about rule violations are placed in the
19232 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
19233
19234 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19235 @item ^-s^/SHORT^
19236 Short format of the report file (no version information, no list of applied
19237 rules, no list of checked sources is included)
19238
19239 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19240 @item ^-s1^/COMPILER_STYLE^
19241 Include the compiler-style section in the report file
19242
19243 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19244 @item ^-s2^/BY_RULES^
19245 Include the section containing diagnoses ordered by rules in the report file
19246
19247 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19248 @item ^-s3^/BY_FILES_BY_RULES^
19249 Include the section containing diagnoses ordered by files and then by rules
19250 in the report file
19251
19252 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19253 @item ^-v^/VERBOSE^
19254 Verbose mode; @command{gnatcheck} generates version information and then
19255 a trace of sources being processed.
19256
19257 @end table
19258
19259 @noindent
19260 Note, that if either of the options @option{^-s1^/COMPILER_STYLE^},
19261 @option{^-s2^/BY_RULES^} or
19262 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19263 then the  @command{gnatcheck} report file will contain only sections
19264 explicitly stated by these options.
19265
19266 @node gnatcheck Rule Options
19267 @section @command{gnatcheck} Rule Options
19268
19269 @noindent
19270 The following options control the processing performed by
19271 @command{gnatcheck}.
19272
19273 @table @option
19274 @cindex @option{+ALL} (@command{gnatcheck})
19275 @item +ALL
19276 Turn all the rule checks ON
19277
19278 @cindex @option{-ALL} (@command{gnatcheck})
19279 @item -ALL
19280 Turn all the rule checks OFF
19281
19282 @cindex @option{+R} (@command{gnatcheck})
19283 @item +R@i{rule_id[:param]}
19284 Turn on the check for a specified rule with the specified parameter, if any.
19285 @i{rule_id} should be the identifier of one of the currently implemented rules
19286 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19287 are not case-sensitive. The @i{:param} item should
19288 be a string representing a valid parameter(s) for the specified rule.
19289 If it contains any space characters then this string must be enclosed in
19290 quotation marks.
19291
19292 @cindex @option{-R} (@command{gnatcheck})
19293 @item -R@i{rule_id}
19294 Turn off the check for a specified rule
19295
19296 @end table
19297
19298 @node Add the Results of Compiler Checks to gnatcheck Output
19299 @section Add the Results of Compiler Checks to @command{gnatcheck} Output
19300
19301 @noindent
19302 The @command{gnatcheck} tool can include in the generated diagnostic messages
19303 and in
19304 the report file the results of the checks performed by the compiler. Though
19305 disabled by default, this effect may be obtained by using @option{+R} with
19306 the following rule identifiers and parameters:
19307
19308 @table @option
19309 @item Restrictions
19310 To record restrictions violations (that are performed by the compiler if the
19311 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19312 use the rule named
19313 @i{Restrictions} with the same parameters as pragma
19314 @code{Restrictions} or @code{Restriction_Warnings}
19315
19316 @item Style_Checks
19317 To record compiler style checks, use the rule named
19318 @i{Style_Checks}. A parameter of this rule can be either @i{All_Checks}, that
19319 turns ON all the style checks, or a string that has exactly the same structure
19320 and semantics as @code{string_LITERAL} parameter of GNAT pragma
19321 @code{Style_Checks}.
19322
19323 @item Warnings
19324 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19325 named @i{Warnings} with a parameter that is a valid
19326 @code{static_string_expression} argument of GNAT pragma @code{Warnings}.
19327
19328 @end table
19329
19330 @c *********************************
19331 @node Creating Sample Bodies Using gnatstub
19332 @chapter Creating Sample Bodies Using @command{gnatstub}
19333 @findex gnatstub
19334
19335 @noindent
19336 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19337 for library unit declarations.
19338
19339 To create a body stub, @command{gnatstub} has to compile the library
19340 unit declaration. Therefore, bodies can be created only for legal
19341 library units. Moreover, if a library unit depends semantically upon
19342 units located outside the current directory, you have to provide
19343 the source search path when calling @command{gnatstub}, see the description
19344 of @command{gnatstub} switches below.
19345
19346 @menu
19347 * Running gnatstub::
19348 * Switches for gnatstub::
19349 @end menu
19350
19351 @node Running gnatstub
19352 @section Running @command{gnatstub}
19353
19354 @noindent
19355 @command{gnatstub} has the command-line interface of the form
19356
19357 @smallexample
19358 $ gnatstub [switches] filename [directory]
19359 @end smallexample
19360
19361 @noindent
19362 where
19363 @table @emph
19364 @item filename
19365 is the name of the source file that contains a library unit declaration
19366 for which a body must be created. The file name may contain the path
19367 information.
19368 The file name does not have to follow the GNAT file name conventions. If the
19369 name
19370 does not follow GNAT file naming conventions, the name of the body file must
19371 be provided
19372 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19373 If the file name follows the GNAT file naming
19374 conventions and the name of the body file is not provided,
19375 @command{gnatstub}
19376 creates the name
19377 of the body file from the argument file name by replacing the @file{.ads}
19378 suffix
19379 with the @file{.adb} suffix.
19380
19381 @item directory
19382 indicates the directory in which the body stub is to be placed (the default
19383 is the
19384 current directory)
19385
19386 @item switches
19387 is an optional sequence of switches as described in the next section
19388 @end table
19389
19390 @node Switches for gnatstub
19391 @section Switches for @command{gnatstub}
19392
19393 @table @option
19394 @c !sort!
19395
19396 @item ^-f^/FULL^
19397 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19398 If the destination directory already contains a file with the name of the
19399 body file
19400 for the argument spec file, replace it with the generated body stub.
19401
19402 @item ^-hs^/HEADER=SPEC^
19403 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19404 Put the comment header (i.e., all the comments preceding the
19405 compilation unit) from the source of the library unit declaration
19406 into the body stub.
19407
19408 @item ^-hg^/HEADER=GENERAL^
19409 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19410 Put a sample comment header into the body stub.
19411
19412 @ifclear vms
19413 @item -IDIR
19414 @cindex @option{-IDIR} (@command{gnatstub})
19415 @itemx -I-
19416 @cindex @option{-I-} (@command{gnatstub})
19417 @end ifclear
19418 @ifset vms
19419 @item /NOCURRENT_DIRECTORY
19420 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19421 @end ifset
19422 ^These switches have ^This switch has^ the same meaning as in calls to
19423 @command{gcc}.
19424 ^They define ^It defines ^ the source search path in the call to
19425 @command{gcc} issued
19426 by @command{gnatstub} to compile an argument source file.
19427
19428 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19429 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19430 This switch has the same meaning as in calls to @command{gcc}.
19431 It defines the additional configuration file to be passed to the call to
19432 @command{gcc} issued
19433 by @command{gnatstub} to compile an argument source file.
19434
19435 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19436 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19437 (@var{n} is a non-negative integer). Set the maximum line length in the
19438 body stub to @var{n}; the default is 79. The maximum value that can be
19439 specified is 32767. Note that in the special case of configuration
19440 pragma files, the maximum is always 32767 regardless of whether or
19441 not this switch appears.
19442
19443 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19444 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19445 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19446 the generated body sample to @var{n}.
19447 The default indentation is 3.
19448
19449 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19450 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19451 Order local bodies alphabetically. (By default local bodies are ordered
19452 in the same way as the corresponding local specs in the argument spec file.)
19453
19454 @item ^-i^/INDENTATION=^@var{n}
19455 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19456 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19457
19458 @item ^-k^/TREE_FILE=SAVE^
19459 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19460 Do not remove the tree file (i.e., the snapshot of the compiler internal
19461 structures used by @command{gnatstub}) after creating the body stub.
19462
19463 @item ^-l^/LINE_LENGTH=^@var{n}
19464 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19465 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19466
19467 @item ^-o^/BODY=^@var{body-name}
19468 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19469 Body file name.  This should be set if the argument file name does not
19470 follow
19471 the GNAT file naming
19472 conventions. If this switch is omitted the default name for the body will be
19473 obtained
19474 from the argument file name according to the GNAT file naming conventions.
19475
19476 @item ^-q^/QUIET^
19477 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19478 Quiet mode: do not generate a confirmation when a body is
19479 successfully created, and do not generate a message when a body is not
19480 required for an
19481 argument unit.
19482
19483 @item ^-r^/TREE_FILE=REUSE^
19484 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19485 Reuse the tree file (if it exists) instead of creating it.  Instead of
19486 creating the tree file for the library unit declaration, @command{gnatstub}
19487 tries to find it in the current directory and use it for creating
19488 a body. If the tree file is not found, no body is created. This option
19489 also implies @option{^-k^/SAVE^}, whether or not
19490 the latter is set explicitly.
19491
19492 @item ^-t^/TREE_FILE=OVERWRITE^
19493 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19494 Overwrite the existing tree file.  If the current directory already
19495 contains the file which, according to the GNAT file naming rules should
19496 be considered as a tree file for the argument source file,
19497 @command{gnatstub}
19498 will refuse to create the tree file needed to create a sample body
19499 unless this option is set.
19500
19501 @item ^-v^/VERBOSE^
19502 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19503 Verbose mode: generate version information.
19504
19505 @end table
19506
19507 @node Other Utility Programs
19508 @chapter Other Utility Programs
19509
19510 @noindent
19511 This chapter discusses some other utility programs available in the Ada
19512 environment.
19513
19514 @menu
19515 * Using Other Utility Programs with GNAT::
19516 * The External Symbol Naming Scheme of GNAT::
19517 @ifclear vms
19518 * Ada Mode for Glide::
19519 @end ifclear
19520 * Converting Ada Files to html with gnathtml::
19521 * Installing gnathtml::
19522 @ifset vms
19523 * LSE::
19524 * Profiling::
19525 @end ifset
19526 @end menu
19527
19528 @node Using Other Utility Programs with GNAT
19529 @section Using Other Utility Programs with GNAT
19530
19531 @noindent
19532 The object files generated by GNAT are in standard system format and in
19533 particular the debugging information uses this format. This means
19534 programs generated by GNAT can be used with existing utilities that
19535 depend on these formats.
19536
19537 @ifclear vms
19538 In general, any utility program that works with C will also often work with
19539 Ada programs generated by GNAT. This includes software utilities such as
19540 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19541 as Purify.
19542 @end ifclear
19543
19544 @node The External Symbol Naming Scheme of GNAT
19545 @section The External Symbol Naming Scheme of GNAT
19546
19547 @noindent
19548 In order to interpret the output from GNAT, when using tools that are
19549 originally intended for use with other languages, it is useful to
19550 understand the conventions used to generate link names from the Ada
19551 entity names.
19552
19553 All link names are in all lowercase letters. With the exception of library
19554 procedure names, the mechanism used is simply to use the full expanded
19555 Ada name with dots replaced by double underscores. For example, suppose
19556 we have the following package spec:
19557
19558 @smallexample @c ada
19559 @group
19560 @cartouche
19561 package QRS is
19562    MN : Integer;
19563 end QRS;
19564 @end cartouche
19565 @end group
19566 @end smallexample
19567
19568 @noindent
19569 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19570 the corresponding link name is @code{qrs__mn}.
19571 @findex Export
19572 Of course if a @code{pragma Export} is used this may be overridden:
19573
19574 @smallexample @c ada
19575 @group
19576 @cartouche
19577 package Exports is
19578    Var1 : Integer;
19579    pragma Export (Var1, C, External_Name => "var1_name");
19580    Var2 : Integer;
19581    pragma Export (Var2, C, Link_Name => "var2_link_name");
19582 end Exports;
19583 @end cartouche
19584 @end group
19585 @end smallexample
19586
19587 @noindent
19588 In this case, the link name for @var{Var1} is whatever link name the
19589 C compiler would assign for the C function @var{var1_name}. This typically
19590 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19591 system conventions, but other possibilities exist. The link name for
19592 @var{Var2} is @var{var2_link_name}, and this is not operating system
19593 dependent.
19594
19595 @findex _main
19596 One exception occurs for library level procedures. A potential ambiguity
19597 arises between the required name @code{_main} for the C main program,
19598 and the name we would otherwise assign to an Ada library level procedure
19599 called @code{Main} (which might well not be the main program).
19600
19601 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19602 names. So if we have a library level procedure such as
19603
19604 @smallexample @c ada
19605 @group
19606 @cartouche
19607 procedure Hello (S : String);
19608 @end cartouche
19609 @end group
19610 @end smallexample
19611
19612 @noindent
19613 the external name of this procedure will be @var{_ada_hello}.
19614
19615 @ifclear vms
19616 @node Ada Mode for Glide
19617 @section Ada Mode for @code{Glide}
19618 @cindex Ada mode (for Glide)
19619
19620 @noindent
19621 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
19622 user to understand and navigate existing code, and facilitates writing
19623 new code. It furthermore provides some utility functions for easier
19624 integration of standard Emacs features when programming in Ada.
19625
19626 Its general features include:
19627
19628 @itemize @bullet
19629 @item
19630 An Integrated Development Environment with functionality such as the
19631 following
19632
19633 @itemize @bullet
19634 @item
19635 ``Project files'' for configuration-specific aspects
19636 (e.g. directories and compilation options)
19637
19638 @item
19639 Compiling and stepping through error messages.
19640
19641 @item
19642 Running and debugging an applications within Glide.
19643 @end itemize
19644
19645 @item
19646 Pull-down menus
19647
19648 @item
19649 User configurability
19650 @end itemize
19651
19652 Some of the specific Ada mode features are:
19653
19654 @itemize @bullet
19655 @item
19656 Functions for easy and quick stepping through Ada code
19657
19658 @item
19659 Getting cross reference information for identifiers (e.g., finding a
19660 defining occurrence)
19661
19662 @item
19663 Displaying an index menu of types and subprograms, allowing
19664 direct selection for browsing
19665
19666 @item
19667 Automatic color highlighting of the various Ada entities
19668 @end itemize
19669
19670 Glide directly supports writing Ada code, via several facilities:
19671
19672 @itemize @bullet
19673 @item
19674 Switching between spec and body files with possible
19675 autogeneration of body files
19676
19677 @item
19678 Automatic formating of subprogram parameter lists
19679
19680 @item
19681 Automatic indentation according to Ada syntax
19682
19683 @item
19684 Automatic completion of identifiers
19685
19686 @item
19687 Automatic (and configurable) casing of identifiers, keywords, and attributes
19688
19689 @item
19690 Insertion of syntactic templates
19691
19692 @item
19693 Block commenting / uncommenting
19694 @end itemize
19695
19696 @noindent
19697 For more information, please refer to the online documentation
19698 available in the @code{Glide} @result{} @code{Help} menu.
19699 @end ifclear
19700
19701 @node Converting Ada Files to html with gnathtml
19702 @section Converting Ada Files to HTML with @code{gnathtml}
19703
19704 @noindent
19705 This @code{Perl} script allows Ada source files to be browsed using
19706 standard Web browsers. For installation procedure, see the section
19707 @xref{Installing gnathtml}.
19708
19709 Ada reserved keywords are highlighted in a bold font and Ada comments in
19710 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19711 switch to suppress the generation of cross-referencing information, user
19712 defined variables and types will appear in a different color; you will
19713 be able to click on any identifier and go to its declaration.
19714
19715 The command line is as follow:
19716 @smallexample
19717 $ perl gnathtml.pl [^switches^options^] ada-files
19718 @end smallexample
19719
19720 @noindent
19721 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19722 an html file for every ada file, and a global file called @file{index.htm}.
19723 This file is an index of every identifier defined in the files.
19724
19725 The available ^switches^options^ are the following ones :
19726
19727 @table @option
19728 @item -83
19729 @cindex @option{-83} (@code{gnathtml})
19730 Only the subset on the Ada 83 keywords will be highlighted, not the full
19731 Ada 95 keywords set.
19732
19733 @item -cc @var{color}
19734 @cindex @option{-cc} (@code{gnathtml})
19735 This option allows you to change the color used for comments. The default
19736 value is green. The color argument can be any name accepted by html.
19737
19738 @item -d
19739 @cindex @option{-d} (@code{gnathtml})
19740 If the Ada files depend on some other files (for instance through
19741 @code{with} clauses, the latter files will also be converted to html.
19742 Only the files in the user project will be converted to html, not the files
19743 in the run-time library itself.
19744
19745 @item -D
19746 @cindex @option{-D} (@code{gnathtml})
19747 This command is the same as @option{-d} above, but @command{gnathtml} will
19748 also look for files in the run-time library, and generate html files for them.
19749
19750 @item -ext @var{extension}
19751 @cindex @option{-ext} (@code{gnathtml})
19752 This option allows you to change the extension of the generated HTML files.
19753 If you do not specify an extension, it will default to @file{htm}.
19754
19755 @item -f
19756 @cindex @option{-f} (@code{gnathtml})
19757 By default, gnathtml will generate html links only for global entities
19758 ('with'ed units, global variables and types,...). If you specify
19759 @option{-f} on the command line, then links will be generated for local
19760 entities too.
19761
19762 @item -l @var{number}
19763 @cindex @option{-l} (@code{gnathtml})
19764 If this ^switch^option^ is provided and @var{number} is not 0, then
19765 @code{gnathtml} will number the html files every @var{number} line.
19766
19767 @item -I @var{dir}
19768 @cindex @option{-I} (@code{gnathtml})
19769 Specify a directory to search for library files (@file{.ALI} files) and
19770 source files. You can provide several -I switches on the command line,
19771 and the directories will be parsed in the order of the command line.
19772
19773 @item -o @var{dir}
19774 @cindex @option{-o} (@code{gnathtml})
19775 Specify the output directory for html files. By default, gnathtml will
19776 saved the generated html files in a subdirectory named @file{html/}.
19777
19778 @item -p @var{file}
19779 @cindex @option{-p} (@code{gnathtml})
19780 If you are using Emacs and the most recent Emacs Ada mode, which provides
19781 a full Integrated Development Environment for compiling, checking,
19782 running and debugging applications, you may use @file{.gpr} files
19783 to give the directories where Emacs can find sources and object files.
19784
19785 Using this ^switch^option^, you can tell gnathtml to use these files.
19786 This allows you to get an html version of your application, even if it
19787 is spread over multiple directories.
19788
19789 @item -sc @var{color}
19790 @cindex @option{-sc} (@code{gnathtml})
19791 This ^switch^option^ allows you to change the color used for symbol
19792 definitions.
19793 The default value is red. The color argument can be any name accepted by html.
19794
19795 @item -t @var{file}
19796 @cindex @option{-t} (@code{gnathtml})
19797 This ^switch^option^ provides the name of a file. This file contains a list of
19798 file names to be converted, and the effect is exactly as though they had
19799 appeared explicitly on the command line. This
19800 is the recommended way to work around the command line length limit on some
19801 systems.
19802
19803 @end table
19804
19805 @node Installing gnathtml
19806 @section Installing @code{gnathtml}
19807
19808 @noindent
19809 @code{Perl} needs to be installed on your machine to run this script.
19810 @code{Perl} is freely available for almost every architecture and
19811 Operating System via the Internet.
19812
19813 On Unix systems, you  may want to modify  the  first line of  the script
19814 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19815 is. The syntax of this line is :
19816 @smallexample
19817 #!full_path_name_to_perl
19818 @end smallexample
19819
19820 @noindent
19821 Alternatively, you may run the script using the following command line:
19822
19823 @smallexample
19824 $ perl gnathtml.pl [switches] files
19825 @end smallexample
19826
19827 @ifset vms
19828 @node LSE
19829 @section LSE
19830 @findex LSE
19831
19832 @noindent
19833 The GNAT distribution provides an Ada 95 template for the HP Language
19834 Sensitive Editor (LSE), a component of DECset. In order to
19835 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19836
19837 @node Profiling
19838 @section Profiling
19839 @findex PCA
19840
19841 @noindent
19842 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19843 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19844 the collection phase with the /DEBUG qualifier.
19845
19846 @smallexample
19847 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19848 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19849 $ RUN/DEBUG <PROGRAM_NAME>
19850 @end smallexample
19851 @noindent
19852 @end ifset
19853
19854 @node Running and Debugging Ada Programs
19855 @chapter Running and Debugging Ada Programs
19856 @cindex Debugging
19857
19858 @noindent
19859 This chapter discusses how to debug Ada programs.
19860 @ifset vms
19861 It applies to the Alpha OpenVMS platform;
19862 the debugger for I64 OpenVMS is scheduled for a subsequent release.
19863 @end ifset
19864
19865 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19866
19867 @enumerate
19868 @item
19869 The illegality may be a violation of the static semantics of Ada. In
19870 that case GNAT diagnoses the constructs in the program that are illegal.
19871 It is then a straightforward matter for the user to modify those parts of
19872 the program.
19873
19874 @item
19875 The illegality may be a violation of the dynamic semantics of Ada. In
19876 that case the program compiles and executes, but may generate incorrect
19877 results, or may terminate abnormally with some exception.
19878
19879 @item
19880 When presented with a program that contains convoluted errors, GNAT
19881 itself may terminate abnormally without providing full diagnostics on
19882 the incorrect user program.
19883 @end enumerate
19884
19885 @menu
19886 * The GNAT Debugger GDB::
19887 * Running GDB::
19888 * Introduction to GDB Commands::
19889 * Using Ada Expressions::
19890 * Calling User-Defined Subprograms::
19891 * Using the Next Command in a Function::
19892 * Ada Exceptions::
19893 * Ada Tasks::
19894 * Debugging Generic Units::
19895 * GNAT Abnormal Termination or Failure to Terminate::
19896 * Naming Conventions for GNAT Source Files::
19897 * Getting Internal Debugging Information::
19898 * Stack Traceback::
19899 @end menu
19900
19901 @cindex Debugger
19902 @findex gdb
19903
19904 @node The GNAT Debugger GDB
19905 @section The GNAT Debugger GDB
19906
19907 @noindent
19908 @code{GDB} is a general purpose, platform-independent debugger that
19909 can be used to debug mixed-language programs compiled with @command{gcc},
19910 and in particular is capable of debugging Ada programs compiled with
19911 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19912 complex Ada data structures.
19913
19914 The manual @cite{Debugging with GDB}
19915 @ifset vms
19916 , located in the GNU:[DOCS] directory,
19917 @end ifset
19918 contains full details on the usage of @code{GDB}, including a section on
19919 its usage on programs. This manual should be consulted for full
19920 details. The section that follows is a brief introduction to the
19921 philosophy and use of @code{GDB}.
19922
19923 When GNAT programs are compiled, the compiler optionally writes debugging
19924 information into the generated object file, including information on
19925 line numbers, and on declared types and variables. This information is
19926 separate from the generated code. It makes the object files considerably
19927 larger, but it does not add to the size of the actual executable that
19928 will be loaded into memory, and has no impact on run-time performance. The
19929 generation of debug information is triggered by the use of the
19930 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19931 the compilations. It is important to emphasize that the use of these
19932 options does not change the generated code.
19933
19934 The debugging information is written in standard system formats that
19935 are used by many tools, including debuggers and profilers. The format
19936 of the information is typically designed to describe C types and
19937 semantics, but GNAT implements a translation scheme which allows full
19938 details about Ada types and variables to be encoded into these
19939 standard C formats. Details of this encoding scheme may be found in
19940 the file exp_dbug.ads in the GNAT source distribution. However, the
19941 details of this encoding are, in general, of no interest to a user,
19942 since @code{GDB} automatically performs the necessary decoding.
19943
19944 When a program is bound and linked, the debugging information is
19945 collected from the object files, and stored in the executable image of
19946 the program. Again, this process significantly increases the size of
19947 the generated executable file, but it does not increase the size of
19948 the executable program itself. Furthermore, if this program is run in
19949 the normal manner, it runs exactly as if the debug information were
19950 not present, and takes no more actual memory.
19951
19952 However, if the program is run under control of @code{GDB}, the
19953 debugger is activated.  The image of the program is loaded, at which
19954 point it is ready to run.  If a run command is given, then the program
19955 will run exactly as it would have if @code{GDB} were not present. This
19956 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19957 entirely non-intrusive until a breakpoint is encountered.  If no
19958 breakpoint is ever hit, the program will run exactly as it would if no
19959 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19960 the debugging information and can respond to user commands to inspect
19961 variables, and more generally to report on the state of execution.
19962
19963 @c **************
19964 @node Running GDB
19965 @section Running GDB
19966
19967 @noindent
19968 The debugger can be launched directly and simply from @code{glide} or
19969 through its graphical interface: @code{gvd}. It can also be used
19970 directly in text mode. Here is described the basic use of @code{GDB}
19971 in text mode. All the commands described below can be used in the
19972 @code{gvd} console window even though there is usually other more
19973 graphical ways to achieve the same goals.
19974
19975 @ifclear vms
19976 @noindent
19977 The command to run the graphical interface of the debugger is
19978 @smallexample
19979 $ gvd program
19980 @end smallexample
19981 @end ifclear
19982
19983 @noindent
19984 The command to run @code{GDB} in text mode is
19985
19986 @smallexample
19987 $ ^gdb program^$ GDB PROGRAM^
19988 @end smallexample
19989
19990 @noindent
19991 where @code{^program^PROGRAM^} is the name of the executable file. This
19992 activates the debugger and results in a prompt for debugger commands.
19993 The simplest command is simply @code{run}, which causes the program to run
19994 exactly as if the debugger were not present. The following section
19995 describes some of the additional commands that can be given to @code{GDB}.
19996
19997 @c *******************************
19998 @node Introduction to GDB Commands
19999 @section Introduction to GDB Commands
20000
20001 @noindent
20002 @code{GDB} contains a large repertoire of commands. The manual
20003 @cite{Debugging with GDB}
20004 @ifset vms
20005 , located in the GNU:[DOCS] directory,
20006 @end ifset
20007 includes extensive documentation on the use
20008 of these commands, together with examples of their use. Furthermore,
20009 the command @var{help} invoked from within @code{GDB} activates a simple help
20010 facility which summarizes the available commands and their options.
20011 In this section we summarize a few of the most commonly
20012 used commands to give an idea of what @code{GDB} is about. You should create
20013 a simple program with debugging information and experiment with the use of
20014 these @code{GDB} commands on the program as you read through the
20015 following section.
20016
20017 @table @code
20018 @item set args @var{arguments}
20019 The @var{arguments} list above is a list of arguments to be passed to
20020 the program on a subsequent run command, just as though the arguments
20021 had been entered on a normal invocation of the program. The @code{set args}
20022 command is not needed if the program does not require arguments.
20023
20024 @item run
20025 The @code{run} command causes execution of the program to start from
20026 the beginning. If the program is already running, that is to say if
20027 you are currently positioned at a breakpoint, then a prompt will ask
20028 for confirmation that you want to abandon the current execution and
20029 restart.
20030
20031 @item breakpoint @var{location}
20032 The breakpoint command sets a breakpoint, that is to say a point at which
20033 execution will halt and @code{GDB} will await further
20034 commands. @var{location} is
20035 either a line number within a file, given in the format @code{file:linenumber},
20036 or it is the name of a subprogram. If you request that a breakpoint be set on
20037 a subprogram that is overloaded, a prompt will ask you to specify on which of
20038 those subprograms you want to breakpoint. You can also
20039 specify that all of them should be breakpointed. If the program is run
20040 and execution encounters the breakpoint, then the program
20041 stops and @code{GDB} signals that the breakpoint was encountered by
20042 printing the line of code before which the program is halted.
20043
20044 @item breakpoint exception @var{name}
20045 A special form of the breakpoint command which breakpoints whenever
20046 exception @var{name} is raised.
20047 If @var{name} is omitted,
20048 then a breakpoint will occur when any exception is raised.
20049
20050 @item print @var{expression}
20051 This will print the value of the given expression. Most simple
20052 Ada expression formats are properly handled by @code{GDB}, so the expression
20053 can contain function calls, variables, operators, and attribute references.
20054
20055 @item continue
20056 Continues execution following a breakpoint, until the next breakpoint or the
20057 termination of the program.
20058
20059 @item step
20060 Executes a single line after a breakpoint. If the next statement
20061 is a subprogram call, execution continues into (the first statement of)
20062 the called subprogram.
20063
20064 @item next
20065 Executes a single line. If this line is a subprogram call, executes and
20066 returns from the call.
20067
20068 @item list
20069 Lists a few lines around the current source location. In practice, it
20070 is usually more convenient to have a separate edit window open with the
20071 relevant source file displayed. Successive applications of this command
20072 print subsequent lines. The command can be given an argument which is a
20073 line number, in which case it displays a few lines around the specified one.
20074
20075 @item backtrace
20076 Displays a backtrace of the call chain. This command is typically
20077 used after a breakpoint has occurred, to examine the sequence of calls that
20078 leads to the current breakpoint. The display includes one line for each
20079 activation record (frame) corresponding to an active subprogram.
20080
20081 @item up
20082 At a breakpoint, @code{GDB} can display the values of variables local
20083 to the current frame. The command @code{up} can be used to
20084 examine the contents of other active frames, by moving the focus up
20085 the stack, that is to say from callee to caller, one frame at a time.
20086
20087 @item down
20088 Moves the focus of @code{GDB} down from the frame currently being
20089 examined to the frame of its callee (the reverse of the previous command),
20090
20091 @item frame @var{n}
20092 Inspect the frame with the given number. The value 0 denotes the frame
20093 of the current breakpoint, that is to say the top of the call stack.
20094
20095 @end table
20096
20097 The above list is a very short introduction to the commands that
20098 @code{GDB} provides. Important additional capabilities, including conditional
20099 breakpoints, the ability to execute command sequences on a breakpoint,
20100 the ability to debug at the machine instruction level and many other
20101 features are described in detail in @cite{Debugging with GDB}.
20102 Note that most commands can be abbreviated
20103 (for example, c for continue, bt for backtrace).
20104
20105 @node Using Ada Expressions
20106 @section Using Ada Expressions
20107 @cindex Ada expressions
20108
20109 @noindent
20110 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20111 extensions. The philosophy behind the design of this subset is
20112
20113 @itemize @bullet
20114 @item
20115 That @code{GDB} should provide basic literals and access to operations for
20116 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20117 leaving more sophisticated computations to subprograms written into the
20118 program (which therefore may be called from @code{GDB}).
20119
20120 @item
20121 That type safety and strict adherence to Ada language restrictions
20122 are not particularly important to the @code{GDB} user.
20123
20124 @item
20125 That brevity is important to the @code{GDB} user.
20126 @end itemize
20127
20128 Thus, for brevity, the debugger acts as if there were
20129 implicit @code{with} and @code{use} clauses in effect for all user-written
20130 packages, thus making it unnecessary to fully qualify most names with
20131 their packages, regardless of context. Where this causes ambiguity,
20132 @code{GDB} asks the user's intent.
20133
20134 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
20135
20136 @node Calling User-Defined Subprograms
20137 @section Calling User-Defined Subprograms
20138
20139 @noindent
20140 An important capability of @code{GDB} is the ability to call user-defined
20141 subprograms while debugging. This is achieved simply by entering
20142 a subprogram call statement in the form:
20143
20144 @smallexample
20145 call subprogram-name (parameters)
20146 @end smallexample
20147
20148 @noindent
20149 The keyword @code{call} can be omitted in the normal case where the
20150 @code{subprogram-name} does not coincide with any of the predefined
20151 @code{GDB} commands.
20152
20153 The effect is to invoke the given subprogram, passing it the
20154 list of parameters that is supplied. The parameters can be expressions and
20155 can include variables from the program being debugged. The
20156 subprogram must be defined
20157 at the library level within your program, and @code{GDB} will call the
20158 subprogram within the environment of your program execution (which
20159 means that the subprogram is free to access or even modify variables
20160 within your program).
20161
20162 The most important use of this facility is in allowing the inclusion of
20163 debugging routines that are tailored to particular data structures
20164 in your program. Such debugging routines can be written to provide a suitably
20165 high-level description of an abstract type, rather than a low-level dump
20166 of its physical layout. After all, the standard
20167 @code{GDB print} command only knows the physical layout of your
20168 types, not their abstract meaning. Debugging routines can provide information
20169 at the desired semantic level and are thus enormously useful.
20170
20171 For example, when debugging GNAT itself, it is crucial to have access to
20172 the contents of the tree nodes used to represent the program internally.
20173 But tree nodes are represented simply by an integer value (which in turn
20174 is an index into a table of nodes).
20175 Using the @code{print} command on a tree node would simply print this integer
20176 value, which is not very useful. But the PN routine (defined in file
20177 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20178 a useful high level representation of the tree node, which includes the
20179 syntactic category of the node, its position in the source, the integers
20180 that denote descendant nodes and parent node, as well as varied
20181 semantic information. To study this example in more detail, you might want to
20182 look at the body of the PN procedure in the stated file.
20183
20184 @node Using the Next Command in a Function
20185 @section Using the Next Command in a Function
20186
20187 @noindent
20188 When you use the @code{next} command in a function, the current source
20189 location will advance to the next statement as usual. A special case
20190 arises in the case of a @code{return} statement.
20191
20192 Part of the code for a return statement is the ``epilog'' of the function.
20193 This is the code that returns to the caller. There is only one copy of
20194 this epilog code, and it is typically associated with the last return
20195 statement in the function if there is more than one return. In some
20196 implementations, this epilog is associated with the first statement
20197 of the function.
20198
20199 The result is that if you use the @code{next} command from a return
20200 statement that is not the last return statement of the function you
20201 may see a strange apparent jump to the last return statement or to
20202 the start of the function. You should simply ignore this odd jump.
20203 The value returned is always that from the first return statement
20204 that was stepped through.
20205
20206 @node Ada Exceptions
20207 @section Breaking on Ada Exceptions
20208 @cindex Exceptions
20209
20210 @noindent
20211 You can set breakpoints that trip when your program raises
20212 selected exceptions.
20213
20214 @table @code
20215 @item break exception
20216 Set a breakpoint that trips whenever (any task in the) program raises
20217 any exception.
20218
20219 @item break exception @var{name}
20220 Set a breakpoint that trips whenever (any task in the) program raises
20221 the exception @var{name}.
20222
20223 @item break exception unhandled
20224 Set a breakpoint that trips whenever (any task in the) program raises an
20225 exception for which there is no handler.
20226
20227 @item info exceptions
20228 @itemx info exceptions @var{regexp}
20229 The @code{info exceptions} command permits the user to examine all defined
20230 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20231 argument, prints out only those exceptions whose name matches @var{regexp}.
20232 @end table
20233
20234 @node Ada Tasks
20235 @section Ada Tasks
20236 @cindex Tasks
20237
20238 @noindent
20239 @code{GDB} allows the following task-related commands:
20240
20241 @table @code
20242 @item info tasks
20243 This command shows a list of current Ada tasks, as in the following example:
20244
20245 @smallexample
20246 @iftex
20247 @leftskip=0cm
20248 @end iftex
20249 (gdb) info tasks
20250   ID       TID P-ID   Thread Pri State                 Name
20251    1   8088000   0   807e000  15 Child Activation Wait main_task
20252    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20253    3   809a800   1   80a4800  15 Child Activation Wait a
20254 *  4   80ae800   3   80b8000  15 Running               c
20255 @end smallexample
20256
20257 @noindent
20258 In this listing, the asterisk before the first task indicates it to be the
20259 currently running task. The first column lists the task ID that is used
20260 to refer to tasks in the following commands.
20261
20262 @item break @var{linespec} task @var{taskid}
20263 @itemx break @var{linespec} task @var{taskid} if @dots{}
20264 @cindex Breakpoints and tasks
20265 These commands are like the @code{break @dots{} thread @dots{}}.
20266 @var{linespec} specifies source lines.
20267
20268 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20269 to specify that you only want @code{GDB} to stop the program when a
20270 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20271 numeric task identifiers assigned by @code{GDB}, shown in the first
20272 column of the @samp{info tasks} display.
20273
20274 If you do not specify @samp{task @var{taskid}} when you set a
20275 breakpoint, the breakpoint applies to @emph{all} tasks of your
20276 program.
20277
20278 You can use the @code{task} qualifier on conditional breakpoints as
20279 well; in this case, place @samp{task @var{taskid}} before the
20280 breakpoint condition (before the @code{if}).
20281
20282 @item task @var{taskno}
20283 @cindex Task switching
20284
20285 This command allows to switch to the task referred by @var{taskno}. In
20286 particular, This allows to browse the backtrace of the specified
20287 task. It is advised to switch back to the original task before
20288 continuing execution otherwise the scheduling of the program may be
20289 perturbed.
20290 @end table
20291
20292 @noindent
20293 For more detailed information on the tasking support,
20294 see @cite{Debugging with GDB}.
20295
20296 @node Debugging Generic Units
20297 @section Debugging Generic Units
20298 @cindex Debugging Generic Units
20299 @cindex Generics
20300
20301 @noindent
20302 GNAT always uses code expansion for generic instantiation. This means that
20303 each time an instantiation occurs, a complete copy of the original code is
20304 made, with appropriate substitutions of formals by actuals.
20305
20306 It is not possible to refer to the original generic entities in
20307 @code{GDB}, but it is always possible to debug a particular instance of
20308 a generic, by using the appropriate expanded names. For example, if we have
20309
20310 @smallexample @c ada
20311 @group
20312 @cartouche
20313 procedure g is
20314
20315    generic package k is
20316       procedure kp (v1 : in out integer);
20317    end k;
20318
20319    package body k is
20320       procedure kp (v1 : in out integer) is
20321       begin
20322          v1 := v1 + 1;
20323       end kp;
20324    end k;
20325
20326    package k1 is new k;
20327    package k2 is new k;
20328
20329    var : integer := 1;
20330
20331 begin
20332    k1.kp (var);
20333    k2.kp (var);
20334    k1.kp (var);
20335    k2.kp (var);
20336 end;
20337 @end cartouche
20338 @end group
20339 @end smallexample
20340
20341 @noindent
20342 Then to break on a call to procedure kp in the k2 instance, simply
20343 use the command:
20344
20345 @smallexample
20346 (gdb) break g.k2.kp
20347 @end smallexample
20348
20349 @noindent
20350 When the breakpoint occurs, you can step through the code of the
20351 instance in the normal manner and examine the values of local variables, as for
20352 other units.
20353
20354 @node GNAT Abnormal Termination or Failure to Terminate
20355 @section GNAT Abnormal Termination or Failure to Terminate
20356 @cindex GNAT Abnormal Termination or Failure to Terminate
20357
20358 @noindent
20359 When presented with programs that contain serious errors in syntax
20360 or semantics,
20361 GNAT may on rare occasions  experience problems in operation, such
20362 as aborting with a
20363 segmentation fault or illegal memory access, raising an internal
20364 exception, terminating abnormally, or failing to terminate at all.
20365 In such cases, you can activate
20366 various features of GNAT that can help you pinpoint the construct in your
20367 program that is the likely source of the problem.
20368
20369 The following strategies are presented in increasing order of
20370 difficulty, corresponding to your experience in using GNAT and your
20371 familiarity with compiler internals.
20372
20373 @enumerate
20374 @item
20375 Run @command{gcc} with the @option{-gnatf}. This first
20376 switch causes all errors on a given line to be reported. In its absence,
20377 only the first error on a line is displayed.
20378
20379 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20380 are encountered, rather than after compilation is terminated. If GNAT
20381 terminates prematurely or goes into an infinite loop, the last error
20382 message displayed may help to pinpoint the culprit.
20383
20384 @item
20385 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20386 mode, @command{gcc} produces ongoing information about the progress of the
20387 compilation and provides the name of each procedure as code is
20388 generated. This switch allows you to find which Ada procedure was being
20389 compiled when it encountered a code generation problem.
20390
20391 @item
20392 @cindex @option{-gnatdc} switch
20393 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20394 switch that does for the front-end what @option{^-v^VERBOSE^} does
20395 for the back end. The system prints the name of each unit,
20396 either a compilation unit or nested unit, as it is being analyzed.
20397 @item
20398 Finally, you can start
20399 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20400 front-end of GNAT, and can be run independently (normally it is just
20401 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20402 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20403 @code{where} command is the first line of attack; the variable
20404 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20405 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20406 which the execution stopped, and @code{input_file name} indicates the name of
20407 the source file.
20408 @end enumerate
20409
20410 @node Naming Conventions for GNAT Source Files
20411 @section Naming Conventions for GNAT Source Files
20412
20413 @noindent
20414 In order to examine the workings of the GNAT system, the following
20415 brief description of its organization may be helpful:
20416
20417 @itemize @bullet
20418 @item
20419 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20420
20421 @item
20422 All files prefixed with @file{^par^PAR^} are components of the parser. The
20423 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
20424 parsing of select statements can be found in @file{par-ch9.adb}.
20425
20426 @item
20427 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20428 numbers correspond to chapters of the Ada standard. For example, all
20429 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20430 addition, some features of the language require sufficient special processing
20431 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20432 dynamic dispatching, etc.
20433
20434 @item
20435 All files prefixed with @file{^exp^EXP^} perform normalization and
20436 expansion of the intermediate representation (abstract syntax tree, or AST).
20437 these files use the same numbering scheme as the parser and semantics files.
20438 For example, the construction of record initialization procedures is done in
20439 @file{exp_ch3.adb}.
20440
20441 @item
20442 The files prefixed with @file{^bind^BIND^} implement the binder, which
20443 verifies the consistency of the compilation, determines an order of
20444 elaboration, and generates the bind file.
20445
20446 @item
20447 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20448 data structures used by the front-end.
20449
20450 @item
20451 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20452 the abstract syntax tree as produced by the parser.
20453
20454 @item
20455 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20456 all entities, computed during semantic analysis.
20457
20458 @item
20459 Library management issues are dealt with in files with prefix
20460 @file{^lib^LIB^}.
20461
20462 @item
20463 @findex Ada
20464 @cindex Annex A
20465 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20466 defined in Annex A.
20467
20468 @item
20469 @findex Interfaces
20470 @cindex Annex B
20471 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20472 defined in Annex B.
20473
20474 @item
20475 @findex System
20476 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20477 both language-defined children and GNAT run-time routines.
20478
20479 @item
20480 @findex GNAT
20481 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20482 general-purpose packages, fully documented in their specifications. All
20483 the other @file{.c} files are modifications of common @command{gcc} files.
20484 @end itemize
20485
20486 @node Getting Internal Debugging Information
20487 @section Getting Internal Debugging Information
20488
20489 @noindent
20490 Most compilers have internal debugging switches and modes. GNAT
20491 does also, except GNAT internal debugging switches and modes are not
20492 secret. A summary and full description of all the compiler and binder
20493 debug flags are in the file @file{debug.adb}. You must obtain the
20494 sources of the compiler to see the full detailed effects of these flags.
20495
20496 The switches that print the source of the program (reconstructed from
20497 the internal tree) are of general interest for user programs, as are the
20498 options to print
20499 the full internal tree, and the entity table (the symbol table
20500 information). The reconstructed source provides a readable version of the
20501 program after the front-end has completed analysis and  expansion,
20502 and is useful when studying the performance of specific constructs.
20503 For example, constraint checks are indicated, complex aggregates
20504 are replaced with loops and assignments, and tasking primitives
20505 are replaced with run-time calls.
20506
20507 @node Stack Traceback
20508 @section Stack Traceback
20509 @cindex traceback
20510 @cindex stack traceback
20511 @cindex stack unwinding
20512
20513 @noindent
20514 Traceback is a mechanism to display the sequence of subprogram calls that
20515 leads to a specified execution point in a program. Often (but not always)
20516 the execution point is an instruction at which an exception has been raised.
20517 This mechanism is also known as @i{stack unwinding} because it obtains
20518 its information by scanning the run-time stack and recovering the activation
20519 records of all active subprograms. Stack unwinding is one of the most
20520 important tools for program debugging.
20521
20522 The first entry stored in traceback corresponds to the deepest calling level,
20523 that is to say the subprogram currently executing the instruction
20524 from which we want to obtain the traceback.
20525
20526 Note that there is no runtime performance penalty when stack traceback
20527 is enabled, and no exception is raised during program execution.
20528
20529 @menu
20530 * Non-Symbolic Traceback::
20531 * Symbolic Traceback::
20532 @end menu
20533
20534 @node Non-Symbolic Traceback
20535 @subsection Non-Symbolic Traceback
20536 @cindex traceback, non-symbolic
20537
20538 @noindent
20539 Note: this feature is not supported on all platforms. See
20540 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20541 platforms.
20542
20543 @menu
20544 * Tracebacks From an Unhandled Exception::
20545 * Tracebacks From Exception Occurrences (non-symbolic)::
20546 * Tracebacks From Anywhere in a Program (non-symbolic)::
20547 @end menu
20548
20549 @node Tracebacks From an Unhandled Exception
20550 @subsubsection Tracebacks From an Unhandled Exception
20551
20552 @noindent
20553 A runtime non-symbolic traceback is a list of addresses of call instructions.
20554 To enable this feature you must use the @option{-E}
20555 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20556 of exception information. You can retrieve this information using the
20557 @code{addr2line} tool.
20558
20559 Here is a simple example:
20560
20561 @smallexample @c ada
20562 @cartouche
20563 procedure STB is
20564
20565    procedure P1 is
20566    begin
20567       raise Constraint_Error;
20568    end P1;
20569
20570    procedure P2 is
20571    begin
20572       P1;
20573    end P2;
20574
20575 begin
20576    P2;
20577 end STB;
20578 @end cartouche
20579 @end smallexample
20580
20581 @smallexample
20582 $ gnatmake stb -bargs -E
20583 $ stb
20584
20585 Execution terminated by unhandled exception
20586 Exception name: CONSTRAINT_ERROR
20587 Message: stb.adb:5
20588 Call stack traceback locations:
20589 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20590 @end smallexample
20591
20592 @noindent
20593 As we see the traceback lists a sequence of addresses for the unhandled
20594 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20595 guess that this exception come from procedure P1. To translate these
20596 addresses into the source lines where the calls appear, the
20597 @code{addr2line} tool, described below, is invaluable. The use of this tool
20598 requires the program to be compiled with debug information.
20599
20600 @smallexample
20601 $ gnatmake -g stb -bargs -E
20602 $ stb
20603
20604 Execution terminated by unhandled exception
20605 Exception name: CONSTRAINT_ERROR
20606 Message: stb.adb:5
20607 Call stack traceback locations:
20608 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20609
20610 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20611    0x4011f1 0x77e892a4
20612
20613 00401373 at d:/stb/stb.adb:5
20614 0040138B at d:/stb/stb.adb:10
20615 0040139C at d:/stb/stb.adb:14
20616 00401335 at d:/stb/b~stb.adb:104
20617 004011C4 at /build/.../crt1.c:200
20618 004011F1 at /build/.../crt1.c:222
20619 77E892A4 in ?? at ??:0
20620 @end smallexample
20621
20622 @noindent
20623 The @code{addr2line} tool has several other useful options:
20624
20625 @table @code
20626 @item --functions
20627 to get the function name corresponding to any location
20628
20629 @item --demangle=gnat
20630 to use the gnat decoding mode for the function names. Note that
20631 for binutils version 2.9.x the option is simply @option{--demangle}.
20632 @end table
20633
20634 @smallexample
20635 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20636    0x40139c 0x401335 0x4011c4 0x4011f1
20637
20638 00401373 in stb.p1 at d:/stb/stb.adb:5
20639 0040138B in stb.p2 at d:/stb/stb.adb:10
20640 0040139C in stb at d:/stb/stb.adb:14
20641 00401335 in main at d:/stb/b~stb.adb:104
20642 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20643 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20644 @end smallexample
20645
20646 @noindent
20647 From this traceback we can see that the exception was raised in
20648 @file{stb.adb} at line 5, which was reached from a procedure call in
20649 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20650 which contains the call to the main program.
20651 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20652 and the output will vary from platform to platform.
20653
20654 It is also possible to use @code{GDB} with these traceback addresses to debug
20655 the program. For example, we can break at a given code location, as reported
20656 in the stack traceback:
20657
20658 @smallexample
20659 $ gdb -nw stb
20660 @ifclear vms
20661 @noindent
20662 Furthermore, this feature is not implemented inside Windows DLL. Only
20663 the non-symbolic traceback is reported in this case.
20664 @end ifclear
20665
20666 (gdb) break *0x401373
20667 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20668 @end smallexample
20669
20670 @noindent
20671 It is important to note that the stack traceback addresses
20672 do not change when debug information is included. This is particularly useful
20673 because it makes it possible to release software without debug information (to
20674 minimize object size), get a field report that includes a stack traceback
20675 whenever an internal bug occurs, and then be able to retrieve the sequence
20676 of calls with the same program compiled with debug information.
20677
20678 @node Tracebacks From Exception Occurrences (non-symbolic)
20679 @subsubsection Tracebacks From Exception Occurrences
20680
20681 @noindent
20682 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20683 The stack traceback is attached to the exception information string, and can
20684 be retrieved in an exception handler within the Ada program, by means of the
20685 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20686
20687 @smallexample @c ada
20688 with Ada.Text_IO;
20689 with Ada.Exceptions;
20690
20691 procedure STB is
20692
20693    use Ada;
20694    use Ada.Exceptions;
20695
20696    procedure P1 is
20697       K : Positive := 1;
20698    begin
20699       K := K - 1;
20700    exception
20701       when E : others =>
20702          Text_IO.Put_Line (Exception_Information (E));
20703    end P1;
20704
20705    procedure P2 is
20706    begin
20707       P1;
20708    end P2;
20709
20710 begin
20711    P2;
20712 end STB;
20713 @end smallexample
20714
20715 @noindent
20716 This program will output:
20717
20718 @smallexample
20719 $ stb
20720
20721 Exception name: CONSTRAINT_ERROR
20722 Message: stb.adb:12
20723 Call stack traceback locations:
20724 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20725 @end smallexample
20726
20727 @node Tracebacks From Anywhere in a Program (non-symbolic)
20728 @subsubsection Tracebacks From Anywhere in a Program
20729
20730 @noindent
20731 It is also possible to retrieve a stack traceback from anywhere in a
20732 program. For this you need to
20733 use the @code{GNAT.Traceback} API. This package includes a procedure called
20734 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20735 display procedures described below. It is not necessary to use the
20736 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20737 is invoked explicitly.
20738
20739 @noindent
20740 In the following example we compute a traceback at a specific location in
20741 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20742 convert addresses to strings:
20743
20744 @smallexample @c ada
20745 with Ada.Text_IO;
20746 with GNAT.Traceback;
20747 with GNAT.Debug_Utilities;
20748
20749 procedure STB is
20750
20751    use Ada;
20752    use GNAT;
20753    use GNAT.Traceback;
20754
20755    procedure P1 is
20756       TB  : Tracebacks_Array (1 .. 10);
20757       --  We are asking for a maximum of 10 stack frames.
20758       Len : Natural;
20759       --  Len will receive the actual number of stack frames returned.
20760    begin
20761       Call_Chain (TB, Len);
20762
20763       Text_IO.Put ("In STB.P1 : ");
20764
20765       for K in 1 .. Len loop
20766          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20767          Text_IO.Put (' ');
20768       end loop;
20769
20770       Text_IO.New_Line;
20771    end P1;
20772
20773    procedure P2 is
20774    begin
20775       P1;
20776    end P2;
20777
20778 begin
20779    P2;
20780 end STB;
20781 @end smallexample
20782
20783 @smallexample
20784 $ gnatmake -g stb
20785 $ stb
20786
20787 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20788 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20789 @end smallexample
20790
20791 @noindent
20792 You can then get further information by invoking the @code{addr2line}
20793 tool as described earlier (note that the hexadecimal addresses
20794 need to be specified in C format, with a leading ``0x'').
20795
20796 @node Symbolic Traceback
20797 @subsection Symbolic Traceback
20798 @cindex traceback, symbolic
20799
20800 @noindent
20801 A symbolic traceback is a stack traceback in which procedure names are
20802 associated with each code location.
20803
20804 @noindent
20805 Note that this feature is not supported on all platforms. See
20806 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20807 list of currently supported platforms.
20808
20809 @noindent
20810 Note that the symbolic traceback requires that the program be compiled
20811 with debug information. If it is not compiled with debug information
20812 only the non-symbolic information will be valid.
20813
20814 @menu
20815 * Tracebacks From Exception Occurrences (symbolic)::
20816 * Tracebacks From Anywhere in a Program (symbolic)::
20817 @end menu
20818
20819 @node Tracebacks From Exception Occurrences (symbolic)
20820 @subsubsection Tracebacks From Exception Occurrences
20821
20822 @smallexample @c ada
20823 with Ada.Text_IO;
20824 with GNAT.Traceback.Symbolic;
20825
20826 procedure STB is
20827
20828    procedure P1 is
20829    begin
20830       raise Constraint_Error;
20831    end P1;
20832
20833    procedure P2 is
20834    begin
20835       P1;
20836    end P2;
20837
20838    procedure P3 is
20839    begin
20840       P2;
20841    end P3;
20842
20843 begin
20844    P3;
20845 exception
20846    when E : others =>
20847       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20848 end STB;
20849 @end smallexample
20850
20851 @smallexample
20852 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20853 $ stb
20854
20855 0040149F in stb.p1 at stb.adb:8
20856 004014B7 in stb.p2 at stb.adb:13
20857 004014CF in stb.p3 at stb.adb:18
20858 004015DD in ada.stb at stb.adb:22
20859 00401461 in main at b~stb.adb:168
20860 004011C4 in __mingw_CRTStartup at crt1.c:200
20861 004011F1 in mainCRTStartup at crt1.c:222
20862 77E892A4 in ?? at ??:0
20863 @end smallexample
20864
20865 @noindent
20866 In the above example the ``.\'' syntax in the @command{gnatmake} command
20867 is currently required by @command{addr2line} for files that are in
20868 the current working directory.
20869 Moreover, the exact sequence of linker options may vary from platform
20870 to platform.
20871 The above @option{-largs} section is for Windows platforms. By contrast,
20872 under Unix there is no need for the @option{-largs} section.
20873 Differences across platforms are due to details of linker implementation.
20874
20875 @node Tracebacks From Anywhere in a Program (symbolic)
20876 @subsubsection Tracebacks From Anywhere in a Program
20877
20878 @noindent
20879 It is possible to get a symbolic stack traceback
20880 from anywhere in a program, just as for non-symbolic tracebacks.
20881 The first step is to obtain a non-symbolic
20882 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20883 information. Here is an example:
20884
20885 @smallexample @c ada
20886 with Ada.Text_IO;
20887 with GNAT.Traceback;
20888 with GNAT.Traceback.Symbolic;
20889
20890 procedure STB is
20891
20892    use Ada;
20893    use GNAT.Traceback;
20894    use GNAT.Traceback.Symbolic;
20895
20896    procedure P1 is
20897       TB  : Tracebacks_Array (1 .. 10);
20898       --  We are asking for a maximum of 10 stack frames.
20899       Len : Natural;
20900       --  Len will receive the actual number of stack frames returned.
20901    begin
20902       Call_Chain (TB, Len);
20903       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20904    end P1;
20905
20906    procedure P2 is
20907    begin
20908       P1;
20909    end P2;
20910
20911 begin
20912    P2;
20913 end STB;
20914 @end smallexample
20915
20916 @c ******************************
20917 @ifset vms
20918 @node Compatibility with HP Ada
20919 @chapter Compatibility with HP Ada
20920 @cindex Compatibility
20921
20922 @noindent
20923 @cindex DEC Ada
20924 @cindex HP Ada
20925 @cindex Compatibility between GNAT and HP Ada
20926 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20927 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20928 GNAT is highly compatible
20929 with HP Ada, and it should generally be straightforward to port code
20930 from the HP Ada environment to GNAT. However, there are a few language
20931 and implementation differences of which the user must be aware. These
20932 differences are discussed in this chapter. In
20933 addition, the operating environment and command structure for the
20934 compiler are different, and these differences are also discussed.
20935
20936 For further details on these and other compatibility issues,
20937 see Appendix E of the HP publication
20938 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20939
20940 Except where otherwise indicated, the description of GNAT for OpenVMS
20941 applies to both the Alpha and I64 platforms.
20942
20943 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20944 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20945
20946 The discussion in this chapter addresses specifically the implementation
20947 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20948 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20949 GNAT always follows the Alpha implementation.
20950
20951 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20952 attributes are recognized, although only a subset of them can sensibly
20953 be implemented.  The description of pragmas in the
20954 @cite{GNAT Reference Manual} indicates whether or not they are applicable
20955 to non-VMS systems.
20956
20957 @menu
20958 * Ada 95 Compatibility::
20959 * Differences in the Definition of Package System::
20960 * Language-Related Features::
20961 * The Package STANDARD::
20962 * The Package SYSTEM::
20963 * Tasking and Task-Related Features::
20964 * Pragmas and Pragma-Related Features::
20965 * Library of Predefined Units::
20966 * Bindings::
20967 * Main Program Definition::
20968 * Implementation-Defined Attributes::
20969 * Compiler and Run-Time Interfacing::
20970 * Program Compilation and Library Management::
20971 * Input-Output::
20972 * Implementation Limits::
20973 * Tools and Utilities::
20974 @end menu
20975
20976 @node Ada 95 Compatibility
20977 @section Ada 95 Compatibility
20978
20979 @noindent
20980 GNAT is an Ada 95 compiler, and HP Ada is an Ada 83
20981 compiler. Ada 95 is almost completely upwards compatible
20982 with Ada 83, and therefore Ada 83 programs will compile
20983 and run under GNAT with
20984 no changes or only minor changes. The Ada 95 Reference
20985 Manual provides details on specific incompatibilities.
20986
20987 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20988 as well as the pragma @code{ADA_83}, to force the compiler to
20989 operate in Ada 83 mode. This mode does not guarantee complete
20990 conformance to Ada 83, but in practice is sufficient to
20991 eliminate most sources of incompatibilities.
20992 In particular, it eliminates the recognition of the
20993 additional Ada 95 keywords, so that their use as identifiers
20994 in Ada 83 programs is legal, and handles the cases of packages
20995 with optional bodies, and generics that instantiate unconstrained
20996 types without the use of @code{(<>)}.
20997
20998 @node Differences in the Definition of Package System
20999 @section Differences in the Definition of Package @code{System}
21000
21001 @noindent
21002 Both Ada 95 and Ada 83 permit a compiler to add
21003 implementation-dependent declarations to package @code{System}.
21004 In normal mode,
21005 GNAT does not take advantage of this permission, and the version of
21006 @code{System} provided by GNAT exactly matches that in Ada 95.
21007
21008 However, HP Ada adds an extensive set of declarations to package
21009 @code{System},
21010 as fully documented in the HP Ada manuals. To minimize changes required
21011 for programs that make use of these extensions, GNAT provides the pragma
21012 @code{Extend_System} for extending the definition of package System. By using:
21013 @cindex pragma @code{Extend_System}
21014 @cindex @code{Extend_System} pragma
21015
21016 @smallexample @c ada
21017 @group
21018 @cartouche
21019 pragma Extend_System (Aux_DEC);
21020 @end cartouche
21021 @end group
21022 @end smallexample
21023
21024 @noindent
21025 the set of definitions in @code{System} is extended to include those in
21026 package @code{System.Aux_DEC}.
21027 @cindex @code{System.Aux_DEC} package
21028 @cindex @code{Aux_DEC} package (child of @code{System})
21029 These definitions are incorporated directly into package @code{System},
21030 as though they had been declared there. For a
21031 list of the declarations added, see the specification of this package,
21032 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21033 @cindex @file{s-auxdec.ads} file
21034 The pragma @code{Extend_System} is a configuration pragma, which means that
21035 it can be placed in the file @file{gnat.adc}, so that it will automatically
21036 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21037 for further details.
21038
21039 An alternative approach that avoids the use of the non-standard
21040 @code{Extend_System} pragma is to add a context clause to the unit that
21041 references these facilities:
21042
21043 @smallexample @c ada
21044 @cartouche
21045 with System.Aux_DEC;
21046 use  System.Aux_DEC;
21047 @end cartouche
21048 @end smallexample
21049
21050 @noindent
21051 The effect is not quite semantically identical to incorporating
21052 the declarations directly into package @code{System},
21053 but most programs will not notice a difference
21054 unless they use prefix notation (e.g. @code{System.Integer_8})
21055 to reference the entities directly in package @code{System}.
21056 For units containing such references,
21057 the prefixes must either be removed, or the pragma @code{Extend_System}
21058 must be used.
21059
21060 @node Language-Related Features
21061 @section Language-Related Features
21062
21063 @noindent
21064 The following sections highlight differences in types,
21065 representations of types, operations, alignment, and
21066 related topics.
21067
21068 @menu
21069 * Integer Types and Representations::
21070 * Floating-Point Types and Representations::
21071 * Pragmas Float_Representation and Long_Float::
21072 * Fixed-Point Types and Representations::
21073 * Record and Array Component Alignment::
21074 * Address Clauses::
21075 * Other Representation Clauses::
21076 @end menu
21077
21078 @node Integer Types and Representations
21079 @subsection Integer Types and Representations
21080
21081 @noindent
21082 The set of predefined integer types is identical in HP Ada and GNAT.
21083 Furthermore the representation of these integer types is also identical,
21084 including the capability of size clauses forcing biased representation.
21085
21086 In addition,
21087 HP Ada for OpenVMS Alpha systems has defined the
21088 following additional integer types in package @code{System}:
21089
21090 @itemize @bullet
21091
21092 @item
21093 @code{INTEGER_8}
21094
21095 @item
21096 @code{INTEGER_16}
21097
21098 @item
21099 @code{INTEGER_32}
21100
21101 @item
21102 @code{INTEGER_64}
21103
21104 @item
21105 @code{LARGEST_INTEGER}
21106 @end itemize
21107
21108 @noindent
21109 In GNAT, the first four of these types may be obtained from the
21110 standard Ada 95 package @code{Interfaces}.
21111 Alternatively, by use of the pragma @code{Extend_System}, identical
21112 declarations can be referenced directly in package @code{System}.
21113 On both GNAT and HP Ada, the maximum integer size is 64 bits.
21114
21115 @node Floating-Point Types and Representations
21116 @subsection Floating-Point Types and Representations
21117 @cindex Floating-Point types
21118
21119 @noindent
21120 The set of predefined floating-point types is identical in HP Ada and GNAT.
21121 Furthermore the representation of these floating-point
21122 types is also identical. One important difference is that the default
21123 representation for HP Ada is @code{VAX_Float}, but the default representation
21124 for GNAT is IEEE.
21125
21126 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
21127 pragma @code{Float_Representation} as described in the HP Ada
21128 documentation.
21129 For example, the declarations:
21130
21131 @smallexample @c ada
21132 @cartouche
21133 type F_Float is digits 6;
21134 pragma Float_Representation (VAX_Float, F_Float);
21135 @end cartouche
21136 @end smallexample
21137
21138 @noindent
21139 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
21140 format.
21141 This set of declarations actually appears in @code{System.Aux_DEC},
21142 which contains
21143 the full set of additional floating-point declarations provided in
21144 the HP Ada version of package @code{System}.
21145 This and similar declarations may be accessed in a user program
21146 by using pragma @code{Extend_System}. The use of this
21147 pragma, and the related pragma @code{Long_Float} is described in further
21148 detail in the following section.
21149
21150 @node Pragmas Float_Representation and Long_Float
21151 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
21152
21153 @noindent
21154 HP Ada provides the pragma @code{Float_Representation}, which
21155 acts as a program library switch to allow control over
21156 the internal representation chosen for the predefined
21157 floating-point types declared in the package @code{Standard}.
21158 The format of this pragma is as follows:
21159
21160 @smallexample @c ada
21161 @cartouche
21162 pragma Float_Representation(VAX_Float | IEEE_Float);
21163 @end cartouche
21164 @end smallexample
21165
21166 @noindent
21167 This pragma controls the representation of floating-point
21168 types as follows:
21169
21170 @itemize @bullet
21171 @item
21172 @code{VAX_Float} specifies that floating-point
21173 types are represented by default with the VAX system hardware types
21174 @code{F-floating}, @code{D-floating}, @code{G-floating}.
21175 Note that the @code{H-floating}
21176 type was available only on VAX systems, and is not available
21177 in either HP Ada or GNAT.
21178
21179 @item
21180 @code{IEEE_Float} specifies that floating-point
21181 types are represented by default with the IEEE single and
21182 double floating-point types.
21183 @end itemize
21184
21185 @noindent
21186 GNAT provides an identical implementation of the pragma
21187 @code{Float_Representation}, except that it functions as a
21188 configuration pragma. Note that the
21189 notion of configuration pragma corresponds closely to the
21190 HP Ada notion of a program library switch.
21191
21192 When no pragma is used in GNAT, the default is @code{IEEE_Float},
21193 which is different
21194 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
21195 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
21196 advisable to change the format of numbers passed to standard library
21197 routines, and if necessary explicit type conversions may be needed.
21198
21199 The use of @code{IEEE_Float} is recommended in GNAT since it is more
21200 efficient, and (given that it conforms to an international standard)
21201 potentially more portable.
21202 The situation in which @code{VAX_Float} may be useful is in interfacing
21203 to existing code and data that expect the use of @code{VAX_Float}.
21204 In such a situation use the predefined @code{VAX_Float}
21205 types in package @code{System}, as extended by
21206 @code{Extend_System}. For example, use @code{System.F_Float}
21207 to specify the 32-bit @code{F-Float} format.
21208
21209 @noindent
21210 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
21211 to allow control over the internal representation chosen
21212 for the predefined type @code{Long_Float} and for floating-point
21213 type declarations with digits specified in the range 7 .. 15.
21214 The format of this pragma is as follows:
21215
21216 @smallexample @c ada
21217 @cartouche
21218 pragma Long_Float (D_FLOAT | G_FLOAT);
21219 @end cartouche
21220 @end smallexample
21221
21222 @node Fixed-Point Types and Representations
21223 @subsection Fixed-Point Types and Representations
21224
21225 @noindent
21226 On HP Ada for OpenVMS Alpha systems, rounding is
21227 away from zero for both positive and negative numbers.
21228 Therefore, @code{+0.5} rounds to @code{1},
21229 and @code{-0.5} rounds to @code{-1}.
21230
21231 On GNAT the results of operations
21232 on fixed-point types are in accordance with the Ada 95
21233 rules. In particular, results of operations on decimal
21234 fixed-point types are truncated.
21235
21236 @node Record and Array Component Alignment
21237 @subsection Record and Array Component Alignment
21238
21239 @noindent
21240 On HP Ada for OpenVMS Alpha, all non composite components
21241 are aligned on natural boundaries. For example, 1-byte
21242 components are aligned on byte boundaries, 2-byte
21243 components on 2-byte boundaries, 4-byte components on 4-byte
21244 byte boundaries, and so on. The OpenVMS Alpha hardware
21245 runs more efficiently with naturally aligned data.
21246
21247 On GNAT, alignment rules are compatible
21248 with HP Ada for OpenVMS Alpha.
21249
21250 @node Address Clauses
21251 @subsection Address Clauses
21252
21253 @noindent
21254 In HP Ada and GNAT, address clauses are supported for
21255 objects and imported subprograms.
21256 The predefined type @code{System.Address} is a private type
21257 in both compilers on Alpha OpenVMS, with the same representation
21258 (it is simply a machine pointer). Addition, subtraction, and comparison
21259 operations are available in the standard Ada 95 package
21260 @code{System.Storage_Elements}, or in package @code{System}
21261 if it is extended to include @code{System.Aux_DEC} using a
21262 pragma @code{Extend_System} as previously described.
21263
21264 Note that code that @code{with}'s both this extended package @code{System}
21265 and the package @code{System.Storage_Elements} should not @code{use}
21266 both packages, or ambiguities will result. In general it is better
21267 not to mix these two sets of facilities. The Ada 95 package was
21268 designed specifically to provide the kind of features that HP Ada
21269 adds directly to package @code{System}.
21270
21271 The type @code{System.Address} is a 64-bit integer type in GNAT for
21272 I64 OpenVMS.  For more information,
21273 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21274
21275 GNAT is compatible with HP Ada in its handling of address
21276 clauses, except for some limitations in
21277 the form of address clauses for composite objects with
21278 initialization. Such address clauses are easily replaced
21279 by the use of an explicitly-defined constant as described
21280 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
21281 of declarations:
21282
21283 @smallexample @c ada
21284 @cartouche
21285 X, Y : Integer := Init_Func;
21286 Q : String (X .. Y) := "abc";
21287 ...
21288 for Q'Address use Compute_Address;
21289 @end cartouche
21290 @end smallexample
21291
21292 @noindent
21293 will be rejected by GNAT, since the address cannot be computed at the time
21294 that @code{Q} is declared. To achieve the intended effect, write instead:
21295
21296 @smallexample @c ada
21297 @group
21298 @cartouche
21299 X, Y : Integer := Init_Func;
21300 Q_Address : constant Address := Compute_Address;
21301 Q : String (X .. Y) := "abc";
21302 ...
21303 for Q'Address use Q_Address;
21304 @end cartouche
21305 @end group
21306 @end smallexample
21307
21308 @noindent
21309 which will be accepted by GNAT (and other Ada 95 compilers), and is also
21310 compatible with Ada 83. A fuller description of the restrictions
21311 on address specifications is found in the @cite{GNAT Reference Manual}.
21312
21313 @node Other Representation Clauses
21314 @subsection Other Representation Clauses
21315
21316 @noindent
21317 GNAT implements in a compatible manner all the representation
21318 clauses supported by HP Ada. In addition, GNAT
21319 implements the representation clause forms that were introduced in Ada 95,
21320 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21321
21322 @node The Package STANDARD
21323 @section The Package @code{STANDARD}
21324
21325 @noindent
21326 The package @code{STANDARD}, as implemented by HP Ada, is fully
21327 described in the Ada 95 Reference Manual and in the HP Ada
21328 Language Reference Manual. As implemented by GNAT, the
21329 package @code{STANDARD} is described in the Ada 95 Reference
21330 Manual.
21331
21332 In addition, HP Ada supports the Latin-1 character set in
21333 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21334 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21335 the type @code{WIDE_CHARACTER}.
21336
21337 The floating-point types supported by GNAT are those
21338 supported by HP Ada, but the defaults are different, and are controlled by
21339 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21340
21341 @node The Package SYSTEM
21342 @section The Package @code{SYSTEM}
21343
21344 @noindent
21345 HP Ada provides a specific version of the package
21346 @code{SYSTEM} for each platform on which the language is implemented.
21347 For the complete specification of the package @code{SYSTEM}, see
21348 Appendix F of the @cite{HP Ada Language Reference Manual}.
21349
21350 On HP Ada, the package @code{SYSTEM} includes the following conversion
21351 functions:
21352 @itemize @bullet
21353 @item @code{TO_ADDRESS(INTEGER)}
21354
21355 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21356
21357 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21358
21359 @item @code{TO_INTEGER(ADDRESS)}
21360
21361 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21362
21363 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21364               functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21365 @end itemize
21366
21367 @noindent
21368 By default, GNAT supplies a version of @code{SYSTEM} that matches
21369 the definition given in the Ada 95 Reference Manual.
21370 This
21371 is a subset of the HP system definitions, which is as
21372 close as possible to the original definitions. The only difference
21373 is that the definition of @code{SYSTEM_NAME} is different:
21374
21375 @smallexample @c ada
21376 @cartouche
21377 type Name is (SYSTEM_NAME_GNAT);
21378 System_Name : constant Name := SYSTEM_NAME_GNAT;
21379 @end cartouche
21380 @end smallexample
21381
21382 @noindent
21383 Also, GNAT adds the new Ada 95 declarations for
21384 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21385
21386 However, the use of the following pragma causes GNAT
21387 to extend the definition of package @code{SYSTEM} so that it
21388 encompasses the full set of HP-specific extensions,
21389 including the functions listed above:
21390
21391 @smallexample @c ada
21392 @cartouche
21393 pragma Extend_System (Aux_DEC);
21394 @end cartouche
21395 @end smallexample
21396
21397 @noindent
21398 The pragma @code{Extend_System} is a configuration pragma that
21399 is most conveniently placed in the @file{gnat.adc} file. See the
21400 @cite{GNAT Reference Manual} for further details.
21401
21402 HP Ada does not allow the recompilation of the package
21403 @code{SYSTEM}. Instead HP Ada provides several pragmas
21404 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21405 to modify values in the package @code{SYSTEM}.
21406 On OpenVMS Alpha systems, the pragma
21407 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21408 its single argument.
21409
21410 GNAT does permit the recompilation of package @code{SYSTEM} using
21411 the special switch @option{-gnatg}, and this switch can be used if
21412 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21413 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21414 or @code{MEMORY_SIZE} by any other means.
21415
21416 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21417 enumeration literal @code{SYSTEM_NAME_GNAT}.
21418
21419 The definitions provided by the use of
21420
21421 @smallexample @c ada
21422 pragma Extend_System (AUX_Dec);
21423 @end smallexample
21424
21425 @noindent
21426 are virtually identical to those provided by the HP Ada 83 package
21427 @code{SYSTEM}. One important difference is that the name of the
21428 @code{TO_ADDRESS}
21429 function for type @code{UNSIGNED_LONGWORD} is changed to
21430 @code{TO_ADDRESS_LONG}.
21431 See the @cite{GNAT Reference Manual} for a discussion of why this change was
21432 necessary.
21433
21434 @noindent
21435 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21436 is in fact
21437 an extension to Ada 83 not strictly compatible with the reference manual.
21438 GNAT, in order to be exactly compatible with the standard,
21439 does not provide this capability. In HP Ada 83, the
21440 point of this definition is to deal with a call like:
21441
21442 @smallexample @c ada
21443 TO_ADDRESS (16#12777#);
21444 @end smallexample
21445
21446 @noindent
21447 Normally, according to Ada 83 semantics, one would expect this to be
21448 ambiguous, since it matches both the @code{INTEGER} and
21449 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21450 However, in HP Ada 83, there is no ambiguity, since the
21451 definition using @i{universal_integer} takes precedence.
21452
21453 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21454 it is
21455 not possible to be 100% compatible. Since there are many programs using
21456 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21457 GNAT was
21458 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21459 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21460
21461 @smallexample @c ada
21462 function To_Address (X : Integer) return Address;
21463 pragma Pure_Function (To_Address);
21464
21465 function To_Address_Long (X : Unsigned_Longword) return Address;
21466 pragma Pure_Function (To_Address_Long);
21467 @end smallexample
21468
21469 @noindent
21470 This means that programs using @code{TO_ADDRESS} for
21471 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21472
21473 @node Tasking and Task-Related Features
21474 @section Tasking and Task-Related Features
21475
21476 @noindent
21477 This section compares the treatment of tasking in GNAT
21478 and in HP Ada for OpenVMS Alpha.
21479 The GNAT description applies to both Alpha and I64 OpenVMS.
21480 For detailed information on tasking in
21481 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21482 relevant run-time reference manual.
21483
21484 @menu
21485 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21486 * Assigning Task IDs::
21487 * Task IDs and Delays::
21488 * Task-Related Pragmas::
21489 * Scheduling and Task Priority::
21490 * The Task Stack::
21491 * External Interrupts::
21492 @end menu
21493
21494 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21495 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21496
21497 @noindent
21498 On OpenVMS Alpha systems, each Ada task (except a passive
21499 task) is implemented as a single stream of execution
21500 that is created and managed by the kernel. On these
21501 systems, HP Ada tasking support is based on DECthreads,
21502 an implementation of the POSIX standard for threads.
21503
21504 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21505 code that calls DECthreads routines can be used together.
21506 The interaction between Ada tasks and DECthreads routines
21507 can have some benefits. For example when on OpenVMS Alpha,
21508 HP Ada can call C code that is already threaded.
21509
21510 GNAT uses the facilities of DECthreads,
21511 and Ada tasks are mapped to threads.
21512
21513 @node Assigning Task IDs
21514 @subsection Assigning Task IDs
21515
21516 @noindent
21517 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21518 the environment task that executes the main program. On
21519 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21520 that have been created but are not yet activated.
21521
21522 On OpenVMS Alpha systems, task IDs are assigned at
21523 activation. On GNAT systems, task IDs are also assigned at
21524 task creation but do not have the same form or values as
21525 task ID values in HP Ada. There is no null task, and the
21526 environment task does not have a specific task ID value.
21527
21528 @node Task IDs and Delays
21529 @subsection Task IDs and Delays
21530
21531 @noindent
21532 On OpenVMS Alpha systems, tasking delays are implemented
21533 using Timer System Services. The Task ID is used for the
21534 identification of the timer request (the @code{REQIDT} parameter).
21535 If Timers are used in the application take care not to use
21536 @code{0} for the identification, because cancelling such a timer
21537 will cancel all timers and may lead to unpredictable results.
21538
21539 @node Task-Related Pragmas
21540 @subsection Task-Related Pragmas
21541
21542 @noindent
21543 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21544 specification of the size of the guard area for a task
21545 stack. (The guard area forms an area of memory that has no
21546 read or write access and thus helps in the detection of
21547 stack overflow.) On OpenVMS Alpha systems, if the pragma
21548 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21549 area is created. In the absence of a pragma @code{TASK_STORAGE},
21550 a default guard area is created.
21551
21552 GNAT supplies the following task-related pragmas:
21553
21554 @itemize @bullet
21555 @item  @code{TASK_INFO}
21556
21557               This pragma appears within a task definition and
21558               applies to the task in which it appears. The argument
21559               must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21560
21561 @item  @code{TASK_STORAGE}
21562
21563               GNAT implements pragma @code{TASK_STORAGE} in the same way as
21564               HP Ada.
21565               Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21566               @code{SUPPRESS}, and @code{VOLATILE}.
21567 @end itemize
21568 @node Scheduling and Task Priority
21569 @subsection Scheduling and Task Priority
21570
21571 @noindent
21572 HP Ada implements the Ada language requirement that
21573 when two tasks are eligible for execution and they have
21574 different priorities, the lower priority task does not
21575 execute while the higher priority task is waiting. The HP
21576 Ada Run-Time Library keeps a task running until either the
21577 task is suspended or a higher priority task becomes ready.
21578
21579 On OpenVMS Alpha systems, the default strategy is round-
21580 robin with preemption. Tasks of equal priority take turns
21581 at the processor. A task is run for a certain period of
21582 time and then placed at the tail of the ready queue for
21583 its priority level.
21584
21585 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21586 which can be used to enable or disable round-robin
21587 scheduling of tasks with the same priority.
21588 See the relevant HP Ada run-time reference manual for
21589 information on using the pragmas to control HP Ada task
21590 scheduling.
21591
21592 GNAT follows the scheduling rules of Annex D (Real-Time
21593 Annex) of the Ada 95 Reference Manual. In general, this
21594 scheduling strategy is fully compatible with HP Ada
21595 although it provides some additional constraints (as
21596 fully documented in Annex D).
21597 GNAT implements time slicing control in a manner compatible with
21598 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21599 are identical to the HP Ada 83 pragma of the same name.
21600 Note that it is not possible to mix GNAT tasking and
21601 HP Ada 83 tasking in the same program, since the two run-time
21602 libraries are not compatible.
21603
21604 @node The Task Stack
21605 @subsection The Task Stack
21606
21607 @noindent
21608 In HP Ada, a task stack is allocated each time a
21609 non-passive task is activated. As soon as the task is
21610 terminated, the storage for the task stack is deallocated.
21611 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21612 a default stack size is used. Also, regardless of the size
21613 specified, some additional space is allocated for task
21614 management purposes. On OpenVMS Alpha systems, at least
21615 one page is allocated.
21616
21617 GNAT handles task stacks in a similar manner. In accordance with
21618 the Ada 95 rules, it provides the pragma @code{STORAGE_SIZE} as
21619 an alternative method for controlling the task stack size.
21620 The specification of the attribute @code{T'STORAGE_SIZE} is also
21621 supported in a manner compatible with HP Ada.
21622
21623 @node External Interrupts
21624 @subsection External Interrupts
21625
21626 @noindent
21627 On HP Ada, external interrupts can be associated with task entries.
21628 GNAT is compatible with HP Ada in its handling of external interrupts.
21629
21630 @node Pragmas and Pragma-Related Features
21631 @section Pragmas and Pragma-Related Features
21632
21633 @noindent
21634 Both HP Ada and GNAT supply all language-defined pragmas
21635 as specified by the Ada 83 standard. GNAT also supplies all
21636 language-defined pragmas specified in the Ada 95 Reference Manual.
21637 In addition, GNAT implements the implementation-defined pragmas
21638 from HP Ada 83.
21639
21640 @itemize @bullet
21641 @item  @code{AST_ENTRY}
21642
21643 @item  @code{COMMON_OBJECT}
21644
21645 @item  @code{COMPONENT_ALIGNMENT}
21646
21647 @item  @code{EXPORT_EXCEPTION}
21648
21649 @item  @code{EXPORT_FUNCTION}
21650
21651 @item  @code{EXPORT_OBJECT}
21652
21653 @item  @code{EXPORT_PROCEDURE}
21654
21655 @item  @code{EXPORT_VALUED_PROCEDURE}
21656
21657 @item  @code{FLOAT_REPRESENTATION}
21658
21659 @item  @code{IDENT}
21660
21661 @item  @code{IMPORT_EXCEPTION}
21662
21663 @item  @code{IMPORT_FUNCTION}
21664
21665 @item  @code{IMPORT_OBJECT}
21666
21667 @item  @code{IMPORT_PROCEDURE}
21668
21669 @item  @code{IMPORT_VALUED_PROCEDURE}
21670
21671 @item  @code{INLINE_GENERIC}
21672
21673 @item  @code{INTERFACE_NAME}
21674
21675 @item  @code{LONG_FLOAT}
21676
21677 @item  @code{MAIN_STORAGE}
21678
21679 @item  @code{PASSIVE}
21680
21681 @item  @code{PSET_OBJECT}
21682
21683 @item  @code{SHARE_GENERIC}
21684
21685 @item  @code{SUPPRESS_ALL}
21686
21687 @item  @code{TASK_STORAGE}
21688
21689 @item  @code{TIME_SLICE}
21690
21691 @item  @code{TITLE}
21692 @end itemize
21693
21694 @noindent
21695 These pragmas are all fully implemented, with the exception of @code{TITLE},
21696 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21697 recognized, but which have no
21698 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21699 use of protected objects in Ada 95. In GNAT, all generics are inlined.
21700
21701 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21702 a separate subprogram specification which must appear before the
21703 subprogram body.
21704
21705 GNAT also supplies a number of implementation-defined pragmas as follows:
21706 @itemize @bullet
21707 @item  @code{ABORT_DEFER}
21708
21709 @item  @code{ADA_83}
21710
21711 @item  @code{ADA_95}
21712
21713 @item  @code{ADA_05}
21714
21715 @item  @code{ANNOTATE}
21716
21717 @item  @code{ASSERT}
21718
21719 @item  @code{C_PASS_BY_COPY}
21720
21721 @item  @code{CPP_CLASS}
21722
21723 @item  @code{CPP_CONSTRUCTOR}
21724
21725 @item  @code{CPP_DESTRUCTOR}
21726
21727 @item  @code{CPP_VIRTUAL}
21728
21729 @item  @code{CPP_VTABLE}
21730
21731 @item  @code{DEBUG}
21732
21733 @item  @code{EXTEND_SYSTEM}
21734
21735 @item  @code{LINKER_ALIAS}
21736
21737 @item  @code{LINKER_SECTION}
21738
21739 @item  @code{MACHINE_ATTRIBUTE}
21740
21741 @item  @code{NO_RETURN}
21742
21743 @item  @code{PURE_FUNCTION}
21744
21745 @item  @code{SOURCE_FILE_NAME}
21746
21747 @item  @code{SOURCE_REFERENCE}
21748
21749 @item  @code{TASK_INFO}
21750
21751 @item  @code{UNCHECKED_UNION}
21752
21753 @item  @code{UNIMPLEMENTED_UNIT}
21754
21755 @item  @code{UNIVERSAL_DATA}
21756
21757 @item  @code{UNSUPPRESS}
21758
21759 @item  @code{WARNINGS}
21760
21761 @item  @code{WEAK_EXTERNAL}
21762 @end itemize
21763
21764 @noindent
21765 For full details on these GNAT implementation-defined pragmas, see
21766 the GNAT Reference Manual.
21767
21768 @menu
21769 * Restrictions on the Pragma INLINE::
21770 * Restrictions on the Pragma INTERFACE::
21771 * Restrictions on the Pragma SYSTEM_NAME::
21772 @end menu
21773
21774 @node Restrictions on the Pragma INLINE
21775 @subsection Restrictions on Pragma @code{INLINE}
21776
21777 @noindent
21778 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21779 @itemize @bullet
21780 @item  Parameters cannot have a task type.
21781
21782 @item  Function results cannot be task types, unconstrained
21783 array types, or unconstrained types with discriminants.
21784
21785 @item  Bodies cannot declare the following:
21786 @itemize @bullet
21787 @item  Subprogram body or stub (imported subprogram is allowed)
21788
21789 @item  Tasks
21790
21791 @item  Generic declarations
21792
21793 @item  Instantiations
21794
21795 @item  Exceptions
21796
21797 @item  Access types (types derived from access types allowed)
21798
21799 @item  Array or record types
21800
21801 @item  Dependent tasks
21802
21803 @item  Direct recursive calls of subprogram or containing
21804 subprogram, directly or via a renaming
21805
21806 @end itemize
21807 @end itemize
21808
21809 @noindent
21810 In GNAT, the only restriction on pragma @code{INLINE} is that the
21811 body must occur before the call if both are in the same
21812 unit, and the size must be appropriately small. There are
21813 no other specific restrictions which cause subprograms to
21814 be incapable of being inlined.
21815
21816 @node  Restrictions on the Pragma INTERFACE
21817 @subsection  Restrictions on Pragma @code{INTERFACE}
21818
21819 @noindent
21820 The following restrictions on pragma @code{INTERFACE}
21821 are enforced by both HP Ada and GNAT:
21822 @itemize @bullet
21823 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21824 Default is the default on OpenVMS Alpha systems.
21825
21826 @item  Parameter passing: Language specifies default
21827 mechanisms but can be overridden with an @code{EXPORT} pragma.
21828
21829 @itemize @bullet
21830 @item  Ada: Use internal Ada rules.
21831
21832 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21833 record or task type. Result cannot be a string, an
21834 array, or a record.
21835
21836 @item  Fortran: Parameters cannot have a task type. Result cannot
21837 be a string, an array, or a record.
21838 @end itemize
21839 @end itemize
21840
21841 @noindent
21842 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21843 record parameters for all languages.
21844
21845 @node  Restrictions on the Pragma SYSTEM_NAME
21846 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21847
21848 @noindent
21849 For HP Ada for OpenVMS Alpha, the enumeration literal
21850 for the type @code{NAME} is @code{OPENVMS_AXP}.
21851 In GNAT, the enumeration
21852 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21853
21854 @node  Library of Predefined Units
21855 @section  Library of Predefined Units
21856
21857 @noindent
21858 A library of predefined units is provided as part of the
21859 HP Ada and GNAT implementations. HP Ada does not provide
21860 the package @code{MACHINE_CODE} but instead recommends importing
21861 assembler code.
21862
21863 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21864 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21865 version.
21866 The HP Ada Predefined Library units are modified to remove Ada 95
21867 incompatibilities and to make them interoperable with GNAT
21868 (@pxref{Changes to DECLIB}, for details).
21869 The units are located in the @file{DECLIB} directory.
21870
21871 The GNAT RTL is contained in
21872 the @file{ADALIB} directory, and
21873 the default search path is set up to find @code{DECLIB} units in preference
21874 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21875 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21876
21877 @menu
21878 * Changes to DECLIB::
21879 @end menu
21880
21881 @node Changes to DECLIB
21882 @subsection Changes to @code{DECLIB}
21883
21884 @noindent
21885 The changes made to the HP Ada predefined library for GNAT and Ada 95
21886 compatibility are minor and include the following:
21887
21888 @itemize @bullet
21889 @item  Adjusting the location of pragmas and record representation
21890 clauses to obey Ada 95 rules
21891
21892 @item  Adding the proper notation to generic formal parameters
21893 that take unconstrained types in instantiation
21894
21895 @item  Adding pragma @code{ELABORATE_BODY} to package specifications
21896 that have package bodies not otherwise allowed
21897
21898 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21899 ``@code{PROTECTD}''.
21900 Currently these are found only in the @code{STARLET} package spec.
21901
21902 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21903 where the address size is constrained to 32 bits.
21904 @end itemize
21905
21906 @noindent
21907 None of the above changes is visible to users.
21908
21909 @node Bindings
21910 @section Bindings
21911
21912 @noindent
21913 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21914 @itemize @bullet
21915
21916 @item  Command Language Interpreter (CLI interface)
21917
21918 @item  DECtalk Run-Time Library (DTK interface)
21919
21920 @item  Librarian utility routines (LBR interface)
21921
21922 @item  General Purpose Run-Time Library (LIB interface)
21923
21924 @item  Math Run-Time Library (MTH interface)
21925
21926 @item  National Character Set Run-Time Library (NCS interface)
21927
21928 @item  Compiled Code Support Run-Time Library (OTS interface)
21929
21930 @item  Parallel Processing Run-Time Library (PPL interface)
21931
21932 @item  Screen Management Run-Time Library (SMG interface)
21933
21934 @item  Sort Run-Time Library (SOR interface)
21935
21936 @item  String Run-Time Library (STR interface)
21937
21938 @item STARLET System Library
21939 @findex Starlet
21940
21941 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21942
21943 @item  X Windows Toolkit (XT interface)
21944
21945 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21946 @end itemize
21947
21948 @noindent
21949 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21950 directory.
21951
21952 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21953 in the
21954 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21955 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21956 @code{Xt}, and @code{X_Lib}
21957 causing the default X/Motif sharable image libraries to be linked in. This
21958 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21959 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21960
21961 It may be necessary to edit these options files to update or correct the
21962 library names if, for example, the newer X/Motif bindings from
21963 @file{ADA$EXAMPLES}
21964 had been (previous to installing GNAT) copied and renamed to supersede the
21965 default @file{ADA$PREDEFINED} versions.
21966
21967 @menu
21968 * Shared Libraries and Options Files::
21969 * Interfaces to C::
21970 @end menu
21971
21972 @node Shared Libraries and Options Files
21973 @subsection Shared Libraries and Options Files
21974
21975 @noindent
21976 When using the HP Ada
21977 predefined X and Motif bindings, the linking with their sharable images is
21978 done automatically by @command{GNAT LINK}.
21979 When using other X and Motif bindings, you need
21980 to add the corresponding sharable images to the command line for
21981 @code{GNAT LINK}. When linking with shared libraries, or with
21982 @file{.OPT} files, you must
21983 also add them to the command line for @command{GNAT LINK}.
21984
21985 A shared library to be used with GNAT is built in the same way as other
21986 libraries under VMS. The VMS Link command can be used in standard fashion.
21987
21988 @node Interfaces to C
21989 @subsection Interfaces to C
21990
21991 @noindent
21992 HP Ada
21993 provides the following Ada types and operations:
21994
21995 @itemize @bullet
21996 @item C types package (@code{C_TYPES})
21997
21998 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21999
22000 @item Other_types (@code{SHORT_INT})
22001 @end itemize
22002
22003 @noindent
22004 Interfacing to C with GNAT, you can use the above approach
22005 described for HP Ada or the facilities of Annex B of
22006 the Ada 95 Reference Manual (packages @code{INTERFACES.C},
22007 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22008 information, see the section ``Interfacing to C'' in the
22009 @cite{GNAT Reference Manual}.
22010
22011 The @option{-gnatF} qualifier forces default and explicit
22012 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22013 to be uppercased for compatibility with the default behavior
22014 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22015
22016 @node Main Program Definition
22017 @section Main Program Definition
22018
22019 @noindent
22020 The following section discusses differences in the
22021 definition of main programs on HP Ada and GNAT.
22022 On HP Ada, main programs are defined to meet the
22023 following conditions:
22024 @itemize @bullet
22025 @item  Procedure with no formal parameters (returns @code{0} upon
22026        normal completion)
22027
22028 @item  Procedure with no formal parameters (returns @code{42} when
22029        an unhandled exception is raised)
22030
22031 @item  Function with no formal parameters whose returned value
22032        is of a discrete type
22033
22034 @item  Procedure with one @code{out} formal of a discrete type for
22035        which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
22036        is given.
22037
22038 @end itemize
22039
22040 @noindent
22041 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22042 a main function or main procedure returns a discrete
22043 value whose size is less than 64 bits (32 on VAX systems),
22044 the value is zero- or sign-extended as appropriate.
22045 On GNAT, main programs are defined as follows:
22046 @itemize @bullet
22047 @item  Must be a non-generic, parameterless subprogram that
22048 is either a procedure or function returning an Ada
22049 @code{STANDARD.INTEGER} (the predefined type)
22050
22051 @item  Cannot be a generic subprogram or an instantiation of a
22052 generic subprogram
22053 @end itemize
22054
22055 @node Implementation-Defined Attributes
22056 @section Implementation-Defined Attributes
22057
22058 @noindent
22059 GNAT provides all HP Ada implementation-defined
22060 attributes.
22061
22062 @node Compiler and Run-Time Interfacing
22063 @section Compiler and Run-Time Interfacing
22064
22065 @noindent
22066 HP Ada provides the following qualifiers to pass options to the linker
22067 (ACS LINK):
22068 @itemize @bullet
22069 @item  @option{/WAIT} and @option{/SUBMIT}
22070
22071 @item  @option{/COMMAND}
22072
22073 @item  @option{/[NO]MAP}
22074
22075 @item  @option{/OUTPUT=@i{file-spec}}
22076
22077 @item  @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
22078 @end itemize
22079
22080 @noindent
22081 To pass options to the linker, GNAT provides the following
22082 switches:
22083
22084 @itemize @bullet
22085 @item   @option{/EXECUTABLE=@i{exec-name}}
22086
22087 @item   @option{/VERBOSE}
22088
22089 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
22090 @end itemize
22091
22092 @noindent
22093 For more information on these switches, see
22094 @ref{Switches for gnatlink}.
22095 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
22096 to control optimization. HP Ada also supplies the
22097 following pragmas:
22098 @itemize @bullet
22099 @item  @code{OPTIMIZE}
22100
22101 @item  @code{INLINE}
22102
22103 @item  @code{INLINE_GENERIC}
22104
22105 @item  @code{SUPPRESS_ALL}
22106
22107 @item  @code{PASSIVE}
22108 @end itemize
22109
22110 @noindent
22111 In GNAT, optimization is controlled strictly by command
22112 line parameters, as described in the corresponding section of this guide.
22113 The HP pragmas for control of optimization are
22114 recognized but ignored.
22115
22116 Note that in GNAT, the default is optimization off, whereas in HP Ada
22117 the default is that optimization is turned on.
22118
22119 @node Program Compilation and Library Management
22120 @section Program Compilation and Library Management
22121
22122 @noindent
22123 HP Ada and GNAT provide a comparable set of commands to
22124 build programs. HP Ada also provides a program library,
22125 which is a concept that does not exist on GNAT. Instead,
22126 GNAT provides directories of sources that are compiled as
22127 needed.
22128
22129 The following table summarizes
22130 the HP Ada commands and provides
22131 equivalent GNAT commands. In this table, some GNAT
22132 equivalents reflect the fact that GNAT does not use the
22133 concept of a program library. Instead, it uses a model
22134 in which collections of source and object files are used
22135 in a manner consistent with other languages like C and
22136 Fortran. Therefore, standard system file commands are used
22137 to manipulate these elements. Those GNAT commands are marked with
22138 an asterisk.
22139 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
22140
22141 @need 1500
22142 @multitable @columnfractions .35 .65
22143
22144 @item @emph{HP Ada Command}
22145 @tab @emph{GNAT Equivalent / Description}
22146
22147 @item @command{ADA}
22148 @tab @command{GNAT COMPILE}@*
22149 Invokes the compiler to compile one or more Ada source files.
22150
22151 @item @command{ACS ATTACH}@*
22152 @tab [No equivalent]@*
22153 Switches control of terminal from current process running the program
22154 library manager.
22155
22156 @item @command{ACS CHECK}
22157 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
22158 Forms the execution closure of one
22159 or more compiled units and checks completeness and currency.
22160
22161 @item @command{ACS COMPILE}
22162 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22163 Forms the execution closure of one or
22164 more specified units, checks completeness and currency,
22165 identifies units that have revised source files, compiles same,
22166 and recompiles units that are or will become obsolete.
22167 Also completes incomplete generic instantiations.
22168
22169 @item @command{ACS COPY FOREIGN}
22170 @tab Copy (*)@*
22171 Copies a foreign object file into the program library as a
22172 library unit body.
22173
22174 @item @command{ACS COPY UNIT}
22175 @tab Copy (*)@*
22176 Copies a compiled unit from one program library to another.
22177
22178 @item @command{ACS CREATE LIBRARY}
22179 @tab Create /directory (*)@*
22180 Creates a program library.
22181
22182 @item @command{ACS CREATE SUBLIBRARY}
22183 @tab Create /directory (*)@*
22184 Creates a program sublibrary.
22185
22186 @item @command{ACS DELETE LIBRARY}
22187 @tab @*
22188 Deletes a program library and its contents.
22189
22190 @item @command{ACS DELETE SUBLIBRARY}
22191 @tab @*
22192 Deletes a program sublibrary and its contents.
22193
22194 @item @command{ACS DELETE UNIT}
22195 @tab Delete file (*)@*
22196 On OpenVMS systems, deletes one or more compiled units from
22197 the current program library.
22198
22199 @item @command{ACS DIRECTORY}
22200 @tab Directory (*)@*
22201 On OpenVMS systems, lists units contained in the current
22202 program library.
22203
22204 @item @command{ACS ENTER FOREIGN}
22205 @tab Copy (*)@*
22206 Allows the import of a foreign body as an Ada library
22207 specification and enters a reference to a pointer.
22208
22209 @item @command{ACS ENTER UNIT}
22210 @tab Copy (*)@*
22211 Enters a reference (pointer) from the current program library to
22212 a unit compiled into another program library.
22213
22214 @item @command{ACS EXIT}
22215 @tab [No equivalent]@*
22216 Exits from the program library manager.
22217
22218 @item @command{ACS EXPORT}
22219 @tab Copy (*)@*
22220 Creates an object file that contains system-specific object code
22221 for one or more units. With GNAT, object files can simply be copied
22222 into the desired directory.
22223
22224 @item @command{ACS EXTRACT SOURCE}
22225 @tab Copy (*)@*
22226 Allows access to the copied source file for each Ada compilation unit
22227
22228 @item @command{ACS HELP}
22229 @tab @command{HELP GNAT}@*
22230 Provides online help.
22231
22232 @item @command{ACS LINK}
22233 @tab @command{GNAT LINK}@*
22234 Links an object file containing Ada units into an executable file.
22235
22236 @item @command{ACS LOAD}
22237 @tab Copy (*)@*
22238 Loads (partially compiles) Ada units into the program library.
22239 Allows loading a program from a collection of files into a library
22240 without knowing the relationship among units.
22241
22242 @item @command{ACS MERGE}
22243 @tab Copy (*)@*
22244 Merges into the current program library, one or more units from
22245 another library where they were modified.
22246
22247 @item @command{ACS RECOMPILE}
22248 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22249 Recompiles from   external or copied source files any obsolete
22250 unit in the closure. Also, completes any incomplete generic
22251 instantiations.
22252
22253 @item @command{ACS REENTER}
22254 @tab @command{GNAT MAKE}@*
22255 Reenters current references to units compiled after last entered
22256 with the @command{ACS ENTER UNIT} command.
22257
22258 @item @command{ACS SET LIBRARY}
22259 @tab Set default (*)@*
22260 Defines a program library to be the compilation context as well
22261 as the target library for compiler output and commands in general.
22262
22263 @item @command{ACS SET PRAGMA}
22264 @tab Edit @file{gnat.adc} (*)@*
22265 Redefines specified  values of the library characteristics
22266 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22267 and @code{Float_Representation}.
22268
22269 @item @command{ACS SET SOURCE}
22270 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22271 Defines the source file search list for the @command{ACS COMPILE} command.
22272
22273 @item @command{ACS SHOW LIBRARY}
22274 @tab Directory (*)@*
22275 Lists information about one or more program libraries.
22276
22277 @item @command{ACS SHOW PROGRAM}
22278 @tab [No equivalent]@*
22279 Lists information about the execution closure of one or
22280 more units in the program library.
22281
22282 @item @command{ACS SHOW SOURCE}
22283 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22284 Shows the source file search used when compiling units.
22285
22286 @item @command{ACS SHOW VERSION}
22287 @tab Compile with @option{VERBOSE} option
22288 Displays the version number of the compiler and program library
22289 manager used.
22290
22291 @item @command{ACS SPAWN}
22292 @tab [No equivalent]@*
22293 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22294 command).
22295
22296 @item @command{ACS VERIFY}
22297 @tab [No equivalent]@*
22298 Performs a series of consistency checks on a program library to
22299 determine whether the library structure and library files are in
22300 valid form.
22301 @end multitable
22302
22303 @noindent
22304
22305 @node Input-Output
22306 @section Input-Output
22307
22308 @noindent
22309 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22310 Management Services (RMS) to perform operations on
22311 external files.
22312
22313 @noindent
22314 HP Ada and GNAT predefine an identical set of input-
22315 output packages. To make the use of the
22316 generic @code{TEXT_IO} operations more convenient, HP Ada
22317 provides predefined library packages that instantiate the
22318 integer and floating-point operations for the predefined
22319 integer and floating-point types as shown in the following table.
22320
22321 @multitable @columnfractions .45 .55
22322 @item @emph{Package Name} @tab Instantiation
22323
22324 @item @code{INTEGER_TEXT_IO}
22325 @tab @code{INTEGER_IO(INTEGER)}
22326
22327 @item @code{SHORT_INTEGER_TEXT_IO}
22328 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22329
22330 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22331 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22332
22333 @item @code{FLOAT_TEXT_IO}
22334 @tab @code{FLOAT_IO(FLOAT)}
22335
22336 @item @code{LONG_FLOAT_TEXT_IO}
22337 @tab @code{FLOAT_IO(LONG_FLOAT)}
22338 @end multitable
22339
22340 @noindent
22341 The HP Ada predefined packages and their operations
22342 are implemented using OpenVMS Alpha files and input-output
22343 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22344 Familiarity with the following is recommended:
22345 @itemize @bullet
22346 @item  RMS file organizations and access methods
22347
22348 @item  OpenVMS file specifications and directories
22349
22350 @item  OpenVMS File Definition Language (FDL)
22351 @end itemize
22352
22353 @noindent
22354 GNAT provides I/O facilities that are completely
22355 compatible with HP Ada. The distribution includes the
22356 standard HP Ada versions of all I/O packages, operating
22357 in a manner compatible with HP Ada. In particular, the
22358 following packages are by default the HP Ada (Ada 83)
22359 versions of these packages rather than the renamings
22360 suggested in Annex J of the Ada 95 Reference Manual:
22361 @itemize @bullet
22362 @item  @code{TEXT_IO}
22363
22364 @item  @code{SEQUENTIAL_IO}
22365
22366 @item  @code{DIRECT_IO}
22367 @end itemize
22368
22369 @noindent
22370 The use of the standard Ada 95 syntax for child packages (for
22371 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
22372 packages, as defined in the Ada 95 Reference Manual.
22373 GNAT provides HP-compatible predefined instantiations
22374 of the @code{TEXT_IO} packages, and also
22375 provides the standard predefined instantiations required
22376 by the Ada 95 Reference Manual.
22377
22378 For further information on how GNAT interfaces to the file
22379 system or how I/O is implemented in programs written in
22380 mixed languages, see the chapter ``Implementation of the
22381 Standard I/O'' in the @cite{GNAT Reference Manual}.
22382 This chapter covers the following:
22383 @itemize @bullet
22384 @item  Standard I/O packages
22385
22386 @item  @code{FORM} strings
22387
22388 @item  @code{ADA.DIRECT_IO}
22389
22390 @item  @code{ADA.SEQUENTIAL_IO}
22391
22392 @item  @code{ADA.TEXT_IO}
22393
22394 @item  Stream pointer positioning
22395
22396 @item  Reading and writing non-regular files
22397
22398 @item  @code{GET_IMMEDIATE}
22399
22400 @item  Treating @code{TEXT_IO} files as streams
22401
22402 @item  Shared files
22403
22404 @item  Open modes
22405 @end itemize
22406
22407 @node Implementation Limits
22408 @section Implementation Limits
22409
22410 @noindent
22411 The following table lists implementation limits for HP Ada
22412 and GNAT systems.
22413 @multitable @columnfractions .60 .20 .20
22414 @sp 1
22415 @item  @emph{Compilation Parameter}
22416 @tab   @emph{HP Ada}
22417 @tab   @emph{GNAT}
22418 @sp 1
22419
22420 @item  In a subprogram or entry  declaration, maximum number of
22421        formal parameters that are of an unconstrained record type
22422 @tab   32
22423 @tab   No set limit
22424 @sp 1
22425
22426 @item  Maximum identifier length (number of characters)
22427 @tab   255
22428 @tab   255
22429 @sp 1
22430
22431 @item  Maximum number of characters in a source line
22432 @tab   255
22433 @tab   255
22434 @sp 1
22435
22436 @item  Maximum collection size   (number of bytes)
22437 @tab   2**31-1
22438 @tab   2**31-1
22439 @sp 1
22440
22441 @item  Maximum number of discriminants for a record type
22442 @tab   245
22443 @tab   No set limit
22444 @sp 1
22445
22446 @item  Maximum number of formal parameters in an entry or
22447        subprogram declaration
22448 @tab   246
22449 @tab    No set limit
22450 @sp 1
22451
22452 @item  Maximum number of dimensions in an array type
22453 @tab   255
22454 @tab   No set limit
22455 @sp 1
22456
22457 @item  Maximum number of library  units and subunits in a compilation.
22458 @tab   4095
22459 @tab   No set limit
22460 @sp 1
22461
22462 @item  Maximum number of library units and subunits in an execution.
22463 @tab   16383
22464 @tab   No set limit
22465 @sp 1
22466
22467 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22468        or @code{PSECT_OBJECT}
22469 @tab   32757
22470 @tab   No set limit
22471 @sp 1
22472
22473 @item  Maximum number of enumeration literals in an enumeration type
22474        definition
22475 @tab   65535
22476 @tab   No set limit
22477 @sp 1
22478
22479 @item  Maximum number of lines in a source file
22480 @tab   65534
22481 @tab   No set limit
22482 @sp 1
22483
22484 @item  Maximum number of bits in any object
22485 @tab   2**31-1
22486 @tab   2**31-1
22487 @sp 1
22488
22489 @item  Maximum size of the static portion of a stack frame (approximate)
22490 @tab   2**31-1
22491 @tab   2**31-1
22492 @end multitable
22493
22494 @node Tools and Utilities
22495 @section Tools and Utilities
22496
22497 @noindent
22498 The following table lists some of the OpenVMS development tools
22499 available for HP Ada, and the corresponding tools for
22500 use with @value{EDITION} on Alpha and I64 platforms.
22501 Aside from the debugger, all the OpenVMS tools identified are part
22502 of the DECset package.
22503
22504 @iftex
22505 @c Specify table in TeX since Texinfo does a poor job
22506 @tex
22507 \smallskip
22508 \smallskip
22509 \settabs\+Language-Sensitive Editor\quad
22510    &Product with HP Ada\quad
22511    &\cr
22512 \+\it Tool
22513    &\it Product with HP Ada
22514    & \it Product with GNAT Pro\cr
22515 \smallskip
22516 \+Code Management System
22517    &HP CMS
22518    & HP CMS\cr
22519 \smallskip
22520 \+Language-Sensitive Editor
22521    &HP LSE
22522    & emacs or HP LSE (Alpha)\cr
22523 \+
22524    &
22525    & HP LSE (I64)\cr
22526 \smallskip
22527 \+Debugger
22528    &OpenVMS Debug
22529    & gdb (Alpha),\cr
22530 \+
22531    &
22532    & OpenVMS Debug (I64)\cr
22533 \smallskip
22534 \+Source Code Analyzer /
22535    &HP SCA
22536    & GNAT XREF\cr
22537 \+Cross Referencer
22538    &
22539    &\cr
22540 \smallskip
22541 \+Test Manager
22542    &HP Digital Test
22543    & HP DTM\cr
22544 \+
22545    &Manager (DTM)
22546    &\cr
22547 \smallskip
22548 \+Performance and
22549    & HP PCA
22550    & HP PCA\cr
22551 \+Coverage Analyzer
22552    &
22553    &\cr
22554 \smallskip
22555 \+Module Management
22556    & HP MMS
22557    & Not applicable\cr
22558 \+ System
22559    &
22560    &\cr
22561 \smallskip
22562 \smallskip
22563 @end tex
22564 @end iftex
22565
22566 @ifnottex
22567 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22568 @c the TeX version above for the printed version
22569 @flushleft
22570 @c @multitable @columnfractions .3 .4 .4
22571 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
22572 @item @i{Tool}
22573  @tab @i{Tool with HP Ada}
22574  @tab @i{Tool with @value{EDITION}}
22575 @item Code Management@*System
22576  @tab HP CMS
22577  @tab HP CMS
22578 @item Language-Sensitive@*Editor
22579  @tab HP LSE
22580  @tab emacs or HP LSE (Alpha)
22581 @item
22582  @tab
22583  @tab HP LSE (I64)
22584 @item Debugger
22585  @tab OpenVMS Debug
22586  @tab gdb (Alpha),
22587 @item
22588  @tab
22589  @tab OpenVMS Debug (I64)
22590 @item Source Code Analyzer /@*Cross Referencer
22591  @tab HP SCA
22592  @tab GNAT XREF
22593 @item Test Manager
22594  @tab HP Digital Test@*Manager (DTM)
22595  @tab HP DTM
22596 @item Performance and@*Coverage Analyzer
22597  @tab HP PCA
22598  @tab HP PCA
22599 @item Module Management@*System
22600  @tab HP MMS
22601  @tab Not applicable
22602 @end multitable
22603 @end flushleft
22604 @end ifnottex
22605
22606 @end ifset
22607
22608 @c **************************************
22609 @node Platform-Specific Information for the Run-Time Libraries
22610 @appendix Platform-Specific Information for the Run-Time Libraries
22611 @cindex Tasking and threads libraries
22612 @cindex Threads libraries and tasking
22613 @cindex Run-time libraries (platform-specific information)
22614
22615 @noindent
22616 The GNAT run-time implementation may vary with respect to both the
22617 underlying threads library and the exception handling scheme.
22618 For threads support, one or more of the following are supplied:
22619 @itemize @bullet
22620 @item @b{native threads library}, a binding to the thread package from
22621 the underlying operating system
22622
22623 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22624 POSIX thread package
22625 @end itemize
22626
22627 @noindent
22628 For exception handling, either or both of two models are supplied:
22629 @itemize @bullet
22630 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22631 Most programs should experience a substantial speed improvement by
22632 being compiled with a ZCX run-time.
22633 This is especially true for
22634 tasking applications or applications with many exception handlers.}
22635 @cindex Zero-Cost Exceptions
22636 @cindex ZCX (Zero-Cost Exceptions)
22637 which uses binder-generated tables that
22638 are interrogated at run time to locate a handler
22639
22640 @item @b{setjmp / longjmp} (``SJLJ''),
22641 @cindex setjmp/longjmp Exception Model
22642 @cindex SJLJ (setjmp/longjmp Exception Model)
22643 which uses dynamically-set data to establish
22644 the set of handlers
22645 @end itemize
22646
22647 @noindent
22648 This appendix summarizes which combinations of threads and exception support
22649 are supplied on various GNAT platforms.
22650 It then shows how to select a particular library either
22651 permanently or temporarily,
22652 explains the properties of (and tradeoffs among) the various threads
22653 libraries, and provides some additional
22654 information about several specific platforms.
22655
22656 @menu
22657 * Summary of Run-Time Configurations::
22658 * Specifying a Run-Time Library::
22659 * Choosing the Scheduling Policy::
22660 * Solaris-Specific Considerations::
22661 * Linux-Specific Considerations::
22662 * AIX-Specific Considerations::
22663 @end menu
22664
22665 @node Summary of Run-Time Configurations
22666 @section Summary of Run-Time Configurations
22667
22668 @multitable @columnfractions .30 .70
22669 @item @b{alpha-openvms}
22670 @item @code{@ @ }@i{rts-native (default)}
22671 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22672 @item @code{@ @ @ @ }Exceptions @tab ZCX
22673 @*
22674 @item @b{alpha-tru64}
22675 @item @code{@ @ }@i{rts-native (default)}
22676 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22677 @item @code{@ @ @ @ }Exceptions @tab ZCX
22678 @*
22679 @item @code{@ @ }@i{rts-sjlj}
22680 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22681 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22682 @*
22683 @item @b{ia64-hp_linux}
22684 @item @code{@ @ }@i{rts-native (default)}
22685 @item @code{@ @ @ @ }Tasking    @tab pthread library
22686 @item @code{@ @ @ @ }Exceptions @tab ZCX
22687 @*
22688 @item @b{ia64-hpux}
22689 @item @code{@ @ }@i{rts-native (default)}
22690 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22691 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22692 @*
22693 @item @b{ia64-openvms}
22694 @item @code{@ @ }@i{rts-native (default)}
22695 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22696 @item @code{@ @ @ @ }Exceptions @tab ZCX
22697 @*
22698 @item @b{ia64-sgi_linux}
22699 @item @code{@ @ }@i{rts-native (default)}
22700 @item @code{@ @ @ @ }Tasking    @tab pthread library
22701 @item @code{@ @ @ @ }Exceptions @tab ZCX
22702 @*
22703 @item @b{mips-irix}
22704 @item @code{@ @ }@i{rts-native (default)}
22705 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
22706 @item @code{@ @ @ @ }Exceptions @tab ZCX
22707 @*
22708 @item @b{pa-hpux}
22709 @item @code{@ @ }@i{rts-native (default)}
22710 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22711 @item @code{@ @ @ @ }Exceptions @tab ZCX
22712 @*
22713 @item @code{@ @ }@i{rts-sjlj}
22714 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22715 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22716 @*
22717 @item @b{ppc-aix}
22718 @item @code{@ @ }@i{rts-native (default)}
22719 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22720 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22721 @*
22722 @item @b{ppc-darwin}
22723 @item @code{@ @ }@i{rts-native (default)}
22724 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22725 @item @code{@ @ @ @ }Exceptions @tab ZCX
22726 @*
22727 @item @b{sparc-solaris}  @tab
22728 @item @code{@ @ }@i{rts-native (default)}
22729 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22730 @item @code{@ @ @ @ }Exceptions @tab ZCX
22731 @*
22732 @item @code{@ @ }@i{rts-m64}
22733 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
22734 @item @code{@ @ @ @ }Exceptions  @tab ZCX
22735 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
22736 @item    @tab Use only on Solaris 8 or later.
22737 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
22738 @*
22739 @item @code{@ @ }@i{rts-pthread}
22740 @item @code{@ @ @ @ }Tasking    @tab pthread library
22741 @item @code{@ @ @ @ }Exceptions @tab ZCX
22742 @*
22743 @item @code{@ @ }@i{rts-sjlj}
22744 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22745 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22746 @*
22747 @item @b{x86-linux}
22748 @item @code{@ @ }@i{rts-native (default)}
22749 @item @code{@ @ @ @ }Tasking    @tab pthread library
22750 @item @code{@ @ @ @ }Exceptions @tab ZCX
22751 @*
22752 @item @code{@ @ }@i{rts-sjlj}
22753 @item @code{@ @ @ @ }Tasking    @tab pthread library
22754 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22755 @*
22756 @item @b{x86-lynx}
22757 @item @code{@ @ }@i{rts-native (default)}
22758 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22759 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22760 @*
22761 @item @b{x86-windows}
22762 @item @code{@ @ }@i{rts-native (default)}
22763 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22764 @item @code{@ @ @ @ }Exceptions @tab ZCX
22765 @*
22766 @item @code{@ @ }@i{rts-sjlj (default)}
22767 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22768 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22769 @*
22770 @item @b{x86_64-linux}
22771 @item @code{@ @ }@i{rts-native (default)}
22772 @item @code{@ @ @ @ }Tasking    @tab pthread library
22773 @item @code{@ @ @ @ }Exceptions @tab ZCX
22774 @*
22775 @item @code{@ @ }@i{rts-sjlj}
22776 @item @code{@ @ @ @ }Tasking    @tab pthread library
22777 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22778 @*
22779 @end multitable
22780
22781 @node Specifying a Run-Time Library
22782 @section Specifying a Run-Time Library
22783
22784 @noindent
22785 The @file{adainclude} subdirectory containing the sources of the GNAT
22786 run-time library, and the @file{adalib} subdirectory containing the
22787 @file{ALI} files and the static and/or shared GNAT library, are located
22788 in the gcc target-dependent area:
22789
22790 @smallexample
22791 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22792 @end smallexample
22793
22794 @noindent
22795 As indicated above, on some platforms several run-time libraries are supplied.
22796 These libraries are installed in the target dependent area and
22797 contain a complete source and binary subdirectory. The detailed description
22798 below explains the differences between the different libraries in terms of
22799 their thread support.
22800
22801 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22802 This default run time is selected by the means of soft links.
22803 For example on x86-linux:
22804
22805 @smallexample
22806 @group
22807  $(target-dir)
22808      |
22809      +--- adainclude----------+
22810      |                        |
22811      +--- adalib-----------+  |
22812      |                     |  |
22813      +--- rts-native       |  |
22814      |    |                |  |
22815      |    +--- adainclude <---+
22816      |    |                |
22817      |    +--- adalib <----+
22818      |
22819      +--- rts-sjlj
22820           |
22821           +--- adainclude
22822           |
22823           +--- adalib
22824 @end group
22825 @end smallexample
22826
22827 @noindent
22828 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22829 these soft links can be modified with the following commands:
22830
22831 @smallexample
22832 $ cd $target
22833 $ rm -f adainclude adalib
22834 $ ln -s rts-sjlj/adainclude adainclude
22835 $ ln -s rts-sjlj/adalib adalib
22836 @end smallexample
22837
22838 @noindent
22839 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22840 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22841 @file{$target/ada_object_path}.
22842
22843 Selecting another run-time library temporarily can be
22844 achieved by the regular mechanism for GNAT object or source path selection:
22845
22846 @itemize @bullet
22847 @item
22848 Set the environment variables:
22849
22850 @smallexample
22851 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
22852 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
22853 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
22854 @end smallexample
22855
22856 @item
22857 Use @option{-aI$target/rts-sjlj/adainclude}
22858 and @option{-aO$target/rts-sjlj/adalib}
22859 on the @command{gnatmake} command line
22860
22861 @item
22862 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
22863 @cindex @option{--RTS} option
22864 @end itemize
22865
22866 @node Choosing the Scheduling Policy
22867 @section Choosing the Scheduling Policy
22868
22869 @noindent
22870 When using a POSIX threads implementation, you have a choice of several
22871 scheduling policies: @code{SCHED_FIFO},
22872 @cindex @code{SCHED_FIFO} scheduling policy
22873 @code{SCHED_RR}
22874 @cindex @code{SCHED_RR} scheduling policy
22875 and @code{SCHED_OTHER}.
22876 @cindex @code{SCHED_OTHER} scheduling policy
22877 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22878 or @code{SCHED_RR} requires special (e.g., root) privileges.
22879
22880 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22881 @code{SCHED_FIFO},
22882 @cindex @code{SCHED_FIFO} scheduling policy
22883 you can use one of the following:
22884
22885 @itemize @bullet
22886 @item
22887 @code{pragma Time_Slice (0.0)}
22888 @cindex pragma Time_Slice
22889 @item
22890 the corresponding binder option @option{-T0}
22891 @cindex @option{-T0} option
22892 @item
22893 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22894 @cindex pragma Task_Dispatching_Policy
22895 @end itemize
22896
22897 @noindent
22898 To specify @code{SCHED_RR},
22899 @cindex @code{SCHED_RR} scheduling policy
22900 you should use @code{pragma Time_Slice} with a
22901 value greater than @code{0.0}, or else use the corresponding @option{-T}
22902 binder option.
22903
22904 @node Solaris-Specific Considerations
22905 @section Solaris-Specific Considerations
22906 @cindex Solaris Sparc threads libraries
22907
22908 @noindent
22909 This section addresses some topics related to the various threads libraries
22910 on Sparc Solaris and then provides some information on building and
22911 debugging 64-bit applications.
22912
22913 @menu
22914 * Solaris Threads Issues::
22915 * Building and Debugging 64-bit Applications::
22916 @end menu
22917
22918 @node Solaris Threads Issues
22919 @subsection Solaris Threads Issues
22920
22921 @noindent
22922 GNAT under Solaris comes with an alternate tasking run-time library
22923 based on POSIX threads --- @emph{rts-pthread}.
22924 @cindex rts-pthread threads library
22925 This run-time library has the advantage of being mostly shared across all
22926 POSIX-compliant thread implementations, and it also provides under
22927 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22928 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22929 and @code{PTHREAD_PRIO_PROTECT}
22930 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22931 semantics that can be selected using the predefined pragma
22932 @code{Locking_Policy}
22933 @cindex pragma Locking_Policy (under rts-pthread)
22934 with respectively
22935 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22936 @cindex @code{Inheritance_Locking} (under rts-pthread)
22937 @cindex @code{Ceiling_Locking} (under rts-pthread)
22938
22939 As explained above, the native run-time library is based on the Solaris thread
22940 library (@code{libthread}) and is the default library.
22941
22942 When the Solaris threads library is used (this is the default), programs
22943 compiled with GNAT can automatically take advantage of
22944 and can thus execute on multiple processors.
22945 The user can alternatively specify a processor on which the program should run
22946 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22947 is made by
22948 setting the environment variable @code{GNAT_PROCESSOR}
22949 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22950 to one of the following:
22951
22952 @table @code
22953 @item -2
22954 Use the default configuration (run the program on all
22955          available processors) - this is the same as having
22956          @code{GNAT_PROCESSOR} unset
22957
22958 @item -1
22959 Let the run-time implementation choose one processor and run the program on
22960          that processor
22961
22962 @item 0 .. Last_Proc
22963 Run the program on the specified processor.
22964   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22965 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22966 @end table
22967
22968 @node Building and Debugging 64-bit Applications
22969 @subsection Building and Debugging 64-bit Applications
22970
22971 @noindent
22972 In a 64-bit application, all the sources involved must be compiled with the
22973 @option{-m64} command-line option, and a specific GNAT library (compiled with
22974 this option) is required.
22975 The easiest way to build a 64bit application is to add
22976 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
22977
22978 To debug these applications, a special version of gdb called @command{gdb64}
22979 needs to be used.
22980
22981 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
22982 amounts to:
22983
22984 @smallexample
22985      $ gnatmake -m64 -g --RTS=m64 hello.adb
22986      $ gdb64 hello
22987 @end smallexample
22988
22989 @node Linux-Specific Considerations
22990 @section Linux-Specific Considerations
22991 @cindex Linux threads libraries
22992
22993 @noindent
22994 On GNU/Linux without NPTL support (usually system with GNU C Library
22995 older than 2.3), the signal model is not POSIX compliant, which means
22996 that to send a signal to the process, you need to send the signal to all
22997 threads, e.g. by using @code{killpg()}.
22998
22999 @node AIX-Specific Considerations
23000 @section AIX-Specific Considerations
23001 @cindex AIX resolver library
23002
23003 @noindent
23004 On AIX, the resolver library initializes some internal structure on
23005 the first call to @code{get*by*} functions, which are used to implement
23006 @code{GNAT.Sockets.Get_Host_By_Name} and
23007 @code{GNAT.Sockets.Get_Host_By_Addrss}.
23008 If such initialization occurs within an Ada task, and the stack size for
23009 the task is the default size, a stack overflow may occur.
23010
23011 To avoid this overflow, the user should either ensure that the first call
23012 to @code{GNAT.Sockets.Get_Host_By_Name} or
23013 @code{GNAT.Sockets.Get_Host_By_Addrss}
23014 occurs in the environment task, or use @code{pragma Storage_Size} to
23015 specify a sufficiently large size for the stack of the task that contains
23016 this call.
23017
23018 @c *******************************
23019 @node Example of Binder Output File
23020 @appendix Example of Binder Output File
23021
23022 @noindent
23023 This Appendix displays the source code for @command{gnatbind}'s output
23024 file generated for a simple ``Hello World'' program.
23025 Comments have been added for clarification purposes.
23026
23027 @smallexample @c adanocomment
23028 @iftex
23029 @leftskip=0cm
23030 @end iftex
23031 --  The package is called Ada_Main unless this name is actually used
23032 --  as a unit name in the partition, in which case some other unique
23033 --  name is used.
23034
23035 with System;
23036 package ada_main is
23037
23038    Elab_Final_Code : Integer;
23039    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
23040
23041    --  The main program saves the parameters (argument count,
23042    --  argument values, environment pointer) in global variables
23043    --  for later access by other units including
23044    --  Ada.Command_Line.
23045
23046    gnat_argc : Integer;
23047    gnat_argv : System.Address;
23048    gnat_envp : System.Address;
23049
23050    --  The actual variables are stored in a library routine. This
23051    --  is useful for some shared library situations, where there
23052    --  are problems if variables are not in the library.
23053
23054    pragma Import (C, gnat_argc);
23055    pragma Import (C, gnat_argv);
23056    pragma Import (C, gnat_envp);
23057
23058    --  The exit status is similarly an external location
23059
23060    gnat_exit_status : Integer;
23061    pragma Import (C, gnat_exit_status);
23062
23063    GNAT_Version : constant String :=
23064                     "GNAT Version: 3.15w (20010315)";
23065    pragma Export (C, GNAT_Version, "__gnat_version");
23066
23067    --  This is the generated adafinal routine that performs
23068    --  finalization at the end of execution. In the case where
23069    --  Ada is the main program, this main program makes a call
23070    --  to adafinal at program termination.
23071
23072    procedure adafinal;
23073    pragma Export (C, adafinal, "adafinal");
23074
23075    --  This is the generated adainit routine that performs
23076    --  initialization at the start of execution. In the case
23077    --  where Ada is the main program, this main program makes
23078    --  a call to adainit at program startup.
23079
23080    procedure adainit;
23081    pragma Export (C, adainit, "adainit");
23082
23083    --  This routine is called at the start of execution. It is
23084    --  a dummy routine that is used by the debugger to breakpoint
23085    --  at the start of execution.
23086
23087    procedure Break_Start;
23088    pragma Import (C, Break_Start, "__gnat_break_start");
23089
23090    --  This is the actual generated main program (it would be
23091    --  suppressed if the no main program switch were used). As
23092    --  required by standard system conventions, this program has
23093    --  the external name main.
23094
23095    function main
23096      (argc : Integer;
23097       argv : System.Address;
23098       envp : System.Address)
23099       return Integer;
23100    pragma Export (C, main, "main");
23101
23102    --  The following set of constants give the version
23103    --  identification values for every unit in the bound
23104    --  partition. This identification is computed from all
23105    --  dependent semantic units, and corresponds to the
23106    --  string that would be returned by use of the
23107    --  Body_Version or Version attributes.
23108
23109    type Version_32 is mod 2 ** 32;
23110    u00001 : constant Version_32 := 16#7880BEB3#;
23111    u00002 : constant Version_32 := 16#0D24CBD0#;
23112    u00003 : constant Version_32 := 16#3283DBEB#;
23113    u00004 : constant Version_32 := 16#2359F9ED#;
23114    u00005 : constant Version_32 := 16#664FB847#;
23115    u00006 : constant Version_32 := 16#68E803DF#;
23116    u00007 : constant Version_32 := 16#5572E604#;
23117    u00008 : constant Version_32 := 16#46B173D8#;
23118    u00009 : constant Version_32 := 16#156A40CF#;
23119    u00010 : constant Version_32 := 16#033DABE0#;
23120    u00011 : constant Version_32 := 16#6AB38FEA#;
23121    u00012 : constant Version_32 := 16#22B6217D#;
23122    u00013 : constant Version_32 := 16#68A22947#;
23123    u00014 : constant Version_32 := 16#18CC4A56#;
23124    u00015 : constant Version_32 := 16#08258E1B#;
23125    u00016 : constant Version_32 := 16#367D5222#;
23126    u00017 : constant Version_32 := 16#20C9ECA4#;
23127    u00018 : constant Version_32 := 16#50D32CB6#;
23128    u00019 : constant Version_32 := 16#39A8BB77#;
23129    u00020 : constant Version_32 := 16#5CF8FA2B#;
23130    u00021 : constant Version_32 := 16#2F1EB794#;
23131    u00022 : constant Version_32 := 16#31AB6444#;
23132    u00023 : constant Version_32 := 16#1574B6E9#;
23133    u00024 : constant Version_32 := 16#5109C189#;
23134    u00025 : constant Version_32 := 16#56D770CD#;
23135    u00026 : constant Version_32 := 16#02F9DE3D#;
23136    u00027 : constant Version_32 := 16#08AB6B2C#;
23137    u00028 : constant Version_32 := 16#3FA37670#;
23138    u00029 : constant Version_32 := 16#476457A0#;
23139    u00030 : constant Version_32 := 16#731E1B6E#;
23140    u00031 : constant Version_32 := 16#23C2E789#;
23141    u00032 : constant Version_32 := 16#0F1BD6A1#;
23142    u00033 : constant Version_32 := 16#7C25DE96#;
23143    u00034 : constant Version_32 := 16#39ADFFA2#;
23144    u00035 : constant Version_32 := 16#571DE3E7#;
23145    u00036 : constant Version_32 := 16#5EB646AB#;
23146    u00037 : constant Version_32 := 16#4249379B#;
23147    u00038 : constant Version_32 := 16#0357E00A#;
23148    u00039 : constant Version_32 := 16#3784FB72#;
23149    u00040 : constant Version_32 := 16#2E723019#;
23150    u00041 : constant Version_32 := 16#623358EA#;
23151    u00042 : constant Version_32 := 16#107F9465#;
23152    u00043 : constant Version_32 := 16#6843F68A#;
23153    u00044 : constant Version_32 := 16#63305874#;
23154    u00045 : constant Version_32 := 16#31E56CE1#;
23155    u00046 : constant Version_32 := 16#02917970#;
23156    u00047 : constant Version_32 := 16#6CCBA70E#;
23157    u00048 : constant Version_32 := 16#41CD4204#;
23158    u00049 : constant Version_32 := 16#572E3F58#;
23159    u00050 : constant Version_32 := 16#20729FF5#;
23160    u00051 : constant Version_32 := 16#1D4F93E8#;
23161    u00052 : constant Version_32 := 16#30B2EC3D#;
23162    u00053 : constant Version_32 := 16#34054F96#;
23163    u00054 : constant Version_32 := 16#5A199860#;
23164    u00055 : constant Version_32 := 16#0E7F912B#;
23165    u00056 : constant Version_32 := 16#5760634A#;
23166    u00057 : constant Version_32 := 16#5D851835#;
23167
23168    --  The following Export pragmas export the version numbers
23169    --  with symbolic names ending in B (for body) or S
23170    --  (for spec) so that they can be located in a link. The
23171    --  information provided here is sufficient to track down
23172    --  the exact versions of units used in a given build.
23173
23174    pragma Export (C, u00001, "helloB");
23175    pragma Export (C, u00002, "system__standard_libraryB");
23176    pragma Export (C, u00003, "system__standard_libraryS");
23177    pragma Export (C, u00004, "adaS");
23178    pragma Export (C, u00005, "ada__text_ioB");
23179    pragma Export (C, u00006, "ada__text_ioS");
23180    pragma Export (C, u00007, "ada__exceptionsB");
23181    pragma Export (C, u00008, "ada__exceptionsS");
23182    pragma Export (C, u00009, "gnatS");
23183    pragma Export (C, u00010, "gnat__heap_sort_aB");
23184    pragma Export (C, u00011, "gnat__heap_sort_aS");
23185    pragma Export (C, u00012, "systemS");
23186    pragma Export (C, u00013, "system__exception_tableB");
23187    pragma Export (C, u00014, "system__exception_tableS");
23188    pragma Export (C, u00015, "gnat__htableB");
23189    pragma Export (C, u00016, "gnat__htableS");
23190    pragma Export (C, u00017, "system__exceptionsS");
23191    pragma Export (C, u00018, "system__machine_state_operationsB");
23192    pragma Export (C, u00019, "system__machine_state_operationsS");
23193    pragma Export (C, u00020, "system__machine_codeS");
23194    pragma Export (C, u00021, "system__storage_elementsB");
23195    pragma Export (C, u00022, "system__storage_elementsS");
23196    pragma Export (C, u00023, "system__secondary_stackB");
23197    pragma Export (C, u00024, "system__secondary_stackS");
23198    pragma Export (C, u00025, "system__parametersB");
23199    pragma Export (C, u00026, "system__parametersS");
23200    pragma Export (C, u00027, "system__soft_linksB");
23201    pragma Export (C, u00028, "system__soft_linksS");
23202    pragma Export (C, u00029, "system__stack_checkingB");
23203    pragma Export (C, u00030, "system__stack_checkingS");
23204    pragma Export (C, u00031, "system__tracebackB");
23205    pragma Export (C, u00032, "system__tracebackS");
23206    pragma Export (C, u00033, "ada__streamsS");
23207    pragma Export (C, u00034, "ada__tagsB");
23208    pragma Export (C, u00035, "ada__tagsS");
23209    pragma Export (C, u00036, "system__string_opsB");
23210    pragma Export (C, u00037, "system__string_opsS");
23211    pragma Export (C, u00038, "interfacesS");
23212    pragma Export (C, u00039, "interfaces__c_streamsB");
23213    pragma Export (C, u00040, "interfaces__c_streamsS");
23214    pragma Export (C, u00041, "system__file_ioB");
23215    pragma Export (C, u00042, "system__file_ioS");
23216    pragma Export (C, u00043, "ada__finalizationB");
23217    pragma Export (C, u00044, "ada__finalizationS");
23218    pragma Export (C, u00045, "system__finalization_rootB");
23219    pragma Export (C, u00046, "system__finalization_rootS");
23220    pragma Export (C, u00047, "system__finalization_implementationB");
23221    pragma Export (C, u00048, "system__finalization_implementationS");
23222    pragma Export (C, u00049, "system__string_ops_concat_3B");
23223    pragma Export (C, u00050, "system__string_ops_concat_3S");
23224    pragma Export (C, u00051, "system__stream_attributesB");
23225    pragma Export (C, u00052, "system__stream_attributesS");
23226    pragma Export (C, u00053, "ada__io_exceptionsS");
23227    pragma Export (C, u00054, "system__unsigned_typesS");
23228    pragma Export (C, u00055, "system__file_control_blockS");
23229    pragma Export (C, u00056, "ada__finalization__list_controllerB");
23230    pragma Export (C, u00057, "ada__finalization__list_controllerS");
23231
23232    -- BEGIN ELABORATION ORDER
23233    -- ada (spec)
23234    -- gnat (spec)
23235    -- gnat.heap_sort_a (spec)
23236    -- gnat.heap_sort_a (body)
23237    -- gnat.htable (spec)
23238    -- gnat.htable (body)
23239    -- interfaces (spec)
23240    -- system (spec)
23241    -- system.machine_code (spec)
23242    -- system.parameters (spec)
23243    -- system.parameters (body)
23244    -- interfaces.c_streams (spec)
23245    -- interfaces.c_streams (body)
23246    -- system.standard_library (spec)
23247    -- ada.exceptions (spec)
23248    -- system.exception_table (spec)
23249    -- system.exception_table (body)
23250    -- ada.io_exceptions (spec)
23251    -- system.exceptions (spec)
23252    -- system.storage_elements (spec)
23253    -- system.storage_elements (body)
23254    -- system.machine_state_operations (spec)
23255    -- system.machine_state_operations (body)
23256    -- system.secondary_stack (spec)
23257    -- system.stack_checking (spec)
23258    -- system.soft_links (spec)
23259    -- system.soft_links (body)
23260    -- system.stack_checking (body)
23261    -- system.secondary_stack (body)
23262    -- system.standard_library (body)
23263    -- system.string_ops (spec)
23264    -- system.string_ops (body)
23265    -- ada.tags (spec)
23266    -- ada.tags (body)
23267    -- ada.streams (spec)
23268    -- system.finalization_root (spec)
23269    -- system.finalization_root (body)
23270    -- system.string_ops_concat_3 (spec)
23271    -- system.string_ops_concat_3 (body)
23272    -- system.traceback (spec)
23273    -- system.traceback (body)
23274    -- ada.exceptions (body)
23275    -- system.unsigned_types (spec)
23276    -- system.stream_attributes (spec)
23277    -- system.stream_attributes (body)
23278    -- system.finalization_implementation (spec)
23279    -- system.finalization_implementation (body)
23280    -- ada.finalization (spec)
23281    -- ada.finalization (body)
23282    -- ada.finalization.list_controller (spec)
23283    -- ada.finalization.list_controller (body)
23284    -- system.file_control_block (spec)
23285    -- system.file_io (spec)
23286    -- system.file_io (body)
23287    -- ada.text_io (spec)
23288    -- ada.text_io (body)
23289    -- hello (body)
23290    -- END ELABORATION ORDER
23291
23292 end ada_main;
23293
23294 --  The following source file name pragmas allow the generated file
23295 --  names to be unique for different main programs. They are needed
23296 --  since the package name will always be Ada_Main.
23297
23298 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23299 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23300
23301 --  Generated package body for Ada_Main starts here
23302
23303 package body ada_main is
23304
23305    --  The actual finalization is performed by calling the
23306    --  library routine in System.Standard_Library.Adafinal
23307
23308    procedure Do_Finalize;
23309    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23310
23311    -------------
23312    -- adainit --
23313    -------------
23314
23315 @findex adainit
23316    procedure adainit is
23317
23318       --  These booleans are set to True once the associated unit has
23319       --  been elaborated. It is also used to avoid elaborating the
23320       --  same unit twice.
23321
23322       E040 : Boolean;
23323       pragma Import (Ada, E040, "interfaces__c_streams_E");
23324
23325       E008 : Boolean;
23326       pragma Import (Ada, E008, "ada__exceptions_E");
23327
23328       E014 : Boolean;
23329       pragma Import (Ada, E014, "system__exception_table_E");
23330
23331       E053 : Boolean;
23332       pragma Import (Ada, E053, "ada__io_exceptions_E");
23333
23334       E017 : Boolean;
23335       pragma Import (Ada, E017, "system__exceptions_E");
23336
23337       E024 : Boolean;
23338       pragma Import (Ada, E024, "system__secondary_stack_E");
23339
23340       E030 : Boolean;
23341       pragma Import (Ada, E030, "system__stack_checking_E");
23342
23343       E028 : Boolean;
23344       pragma Import (Ada, E028, "system__soft_links_E");
23345
23346       E035 : Boolean;
23347       pragma Import (Ada, E035, "ada__tags_E");
23348
23349       E033 : Boolean;
23350       pragma Import (Ada, E033, "ada__streams_E");
23351
23352       E046 : Boolean;
23353       pragma Import (Ada, E046, "system__finalization_root_E");
23354
23355       E048 : Boolean;
23356       pragma Import (Ada, E048, "system__finalization_implementation_E");
23357
23358       E044 : Boolean;
23359       pragma Import (Ada, E044, "ada__finalization_E");
23360
23361       E057 : Boolean;
23362       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23363
23364       E055 : Boolean;
23365       pragma Import (Ada, E055, "system__file_control_block_E");
23366
23367       E042 : Boolean;
23368       pragma Import (Ada, E042, "system__file_io_E");
23369
23370       E006 : Boolean;
23371       pragma Import (Ada, E006, "ada__text_io_E");
23372
23373       --  Set_Globals is a library routine that stores away the
23374       --  value of the indicated set of global values in global
23375       --  variables within the library.
23376
23377       procedure Set_Globals
23378         (Main_Priority            : Integer;
23379          Time_Slice_Value         : Integer;
23380          WC_Encoding              : Character;
23381          Locking_Policy           : Character;
23382          Queuing_Policy           : Character;
23383          Task_Dispatching_Policy  : Character;
23384          Adafinal                 : System.Address;
23385          Unreserve_All_Interrupts : Integer;
23386          Exception_Tracebacks     : Integer);
23387 @findex __gnat_set_globals
23388       pragma Import (C, Set_Globals, "__gnat_set_globals");
23389
23390       --  SDP_Table_Build is a library routine used to build the
23391       --  exception tables. See unit Ada.Exceptions in files
23392       --  a-except.ads/adb for full details of how zero cost
23393       --  exception handling works. This procedure, the call to
23394       --  it, and the two following tables are all omitted if the
23395       --  build is in longjmp/setjump exception mode.
23396
23397 @findex SDP_Table_Build
23398 @findex Zero Cost Exceptions
23399       procedure SDP_Table_Build
23400         (SDP_Addresses   : System.Address;
23401          SDP_Count       : Natural;
23402          Elab_Addresses  : System.Address;
23403          Elab_Addr_Count : Natural);
23404       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23405
23406       --  Table of Unit_Exception_Table addresses. Used for zero
23407       --  cost exception handling to build the top level table.
23408
23409       ST : aliased constant array (1 .. 23) of System.Address := (
23410         Hello'UET_Address,
23411         Ada.Text_Io'UET_Address,
23412         Ada.Exceptions'UET_Address,
23413         Gnat.Heap_Sort_A'UET_Address,
23414         System.Exception_Table'UET_Address,
23415         System.Machine_State_Operations'UET_Address,
23416         System.Secondary_Stack'UET_Address,
23417         System.Parameters'UET_Address,
23418         System.Soft_Links'UET_Address,
23419         System.Stack_Checking'UET_Address,
23420         System.Traceback'UET_Address,
23421         Ada.Streams'UET_Address,
23422         Ada.Tags'UET_Address,
23423         System.String_Ops'UET_Address,
23424         Interfaces.C_Streams'UET_Address,
23425         System.File_Io'UET_Address,
23426         Ada.Finalization'UET_Address,
23427         System.Finalization_Root'UET_Address,
23428         System.Finalization_Implementation'UET_Address,
23429         System.String_Ops_Concat_3'UET_Address,
23430         System.Stream_Attributes'UET_Address,
23431         System.File_Control_Block'UET_Address,
23432         Ada.Finalization.List_Controller'UET_Address);
23433
23434       --  Table of addresses of elaboration routines. Used for
23435       --  zero cost exception handling to make sure these
23436       --  addresses are included in the top level procedure
23437       --  address table.
23438
23439       EA : aliased constant array (1 .. 23) of System.Address := (
23440         adainit'Code_Address,
23441         Do_Finalize'Code_Address,
23442         Ada.Exceptions'Elab_Spec'Address,
23443         System.Exceptions'Elab_Spec'Address,
23444         Interfaces.C_Streams'Elab_Spec'Address,
23445         System.Exception_Table'Elab_Body'Address,
23446         Ada.Io_Exceptions'Elab_Spec'Address,
23447         System.Stack_Checking'Elab_Spec'Address,
23448         System.Soft_Links'Elab_Body'Address,
23449         System.Secondary_Stack'Elab_Body'Address,
23450         Ada.Tags'Elab_Spec'Address,
23451         Ada.Tags'Elab_Body'Address,
23452         Ada.Streams'Elab_Spec'Address,
23453         System.Finalization_Root'Elab_Spec'Address,
23454         Ada.Exceptions'Elab_Body'Address,
23455         System.Finalization_Implementation'Elab_Spec'Address,
23456         System.Finalization_Implementation'Elab_Body'Address,
23457         Ada.Finalization'Elab_Spec'Address,
23458         Ada.Finalization.List_Controller'Elab_Spec'Address,
23459         System.File_Control_Block'Elab_Spec'Address,
23460         System.File_Io'Elab_Body'Address,
23461         Ada.Text_Io'Elab_Spec'Address,
23462         Ada.Text_Io'Elab_Body'Address);
23463
23464    --  Start of processing for adainit
23465
23466    begin
23467
23468       --  Call SDP_Table_Build to build the top level procedure
23469       --  table for zero cost exception handling (omitted in
23470       --  longjmp/setjump mode).
23471
23472       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23473
23474       --  Call Set_Globals to record various information for
23475       --  this partition.  The values are derived by the binder
23476       --  from information stored in the ali files by the compiler.
23477
23478 @findex __gnat_set_globals
23479       Set_Globals
23480         (Main_Priority            => -1,
23481          --  Priority of main program, -1 if no pragma Priority used
23482
23483          Time_Slice_Value         => -1,
23484          --  Time slice from Time_Slice pragma, -1 if none used
23485
23486          WC_Encoding              => 'b',
23487          --  Wide_Character encoding used, default is brackets
23488
23489          Locking_Policy           => ' ',
23490          --  Locking_Policy used, default of space means not
23491          --  specified, otherwise it is the first character of
23492          --  the policy name.
23493
23494          Queuing_Policy           => ' ',
23495          --  Queuing_Policy used, default of space means not
23496          --  specified, otherwise it is the first character of
23497          --  the policy name.
23498
23499          Task_Dispatching_Policy  => ' ',
23500          --  Task_Dispatching_Policy used, default of space means
23501          --  not specified, otherwise first character of the
23502          --  policy name.
23503
23504          Adafinal                 => System.Null_Address,
23505          --  Address of Adafinal routine, not used anymore
23506
23507          Unreserve_All_Interrupts => 0,
23508          --  Set true if pragma Unreserve_All_Interrupts was used
23509
23510          Exception_Tracebacks     => 0);
23511          --  Indicates if exception tracebacks are enabled
23512
23513       Elab_Final_Code := 1;
23514
23515       --  Now we have the elaboration calls for all units in the partition.
23516       --  The Elab_Spec and Elab_Body attributes generate references to the
23517       --  implicit elaboration procedures generated by the compiler for
23518       --  each unit that requires elaboration.
23519
23520       if not E040 then
23521          Interfaces.C_Streams'Elab_Spec;
23522       end if;
23523       E040 := True;
23524       if not E008 then
23525          Ada.Exceptions'Elab_Spec;
23526       end if;
23527       if not E014 then
23528          System.Exception_Table'Elab_Body;
23529          E014 := True;
23530       end if;
23531       if not E053 then
23532          Ada.Io_Exceptions'Elab_Spec;
23533          E053 := True;
23534       end if;
23535       if not E017 then
23536          System.Exceptions'Elab_Spec;
23537          E017 := True;
23538       end if;
23539       if not E030 then
23540          System.Stack_Checking'Elab_Spec;
23541       end if;
23542       if not E028 then
23543          System.Soft_Links'Elab_Body;
23544          E028 := True;
23545       end if;
23546       E030 := True;
23547       if not E024 then
23548          System.Secondary_Stack'Elab_Body;
23549          E024 := True;
23550       end if;
23551       if not E035 then
23552          Ada.Tags'Elab_Spec;
23553       end if;
23554       if not E035 then
23555          Ada.Tags'Elab_Body;
23556          E035 := True;
23557       end if;
23558       if not E033 then
23559          Ada.Streams'Elab_Spec;
23560          E033 := True;
23561       end if;
23562       if not E046 then
23563          System.Finalization_Root'Elab_Spec;
23564       end if;
23565       E046 := True;
23566       if not E008 then
23567          Ada.Exceptions'Elab_Body;
23568          E008 := True;
23569       end if;
23570       if not E048 then
23571          System.Finalization_Implementation'Elab_Spec;
23572       end if;
23573       if not E048 then
23574          System.Finalization_Implementation'Elab_Body;
23575          E048 := True;
23576       end if;
23577       if not E044 then
23578          Ada.Finalization'Elab_Spec;
23579       end if;
23580       E044 := True;
23581       if not E057 then
23582          Ada.Finalization.List_Controller'Elab_Spec;
23583       end if;
23584       E057 := True;
23585       if not E055 then
23586          System.File_Control_Block'Elab_Spec;
23587          E055 := True;
23588       end if;
23589       if not E042 then
23590          System.File_Io'Elab_Body;
23591          E042 := True;
23592       end if;
23593       if not E006 then
23594          Ada.Text_Io'Elab_Spec;
23595       end if;
23596       if not E006 then
23597          Ada.Text_Io'Elab_Body;
23598          E006 := True;
23599       end if;
23600
23601       Elab_Final_Code := 0;
23602    end adainit;
23603
23604    --------------
23605    -- adafinal --
23606    --------------
23607
23608 @findex adafinal
23609    procedure adafinal is
23610    begin
23611       Do_Finalize;
23612    end adafinal;
23613
23614    ----------
23615    -- main --
23616    ----------
23617
23618    --  main is actually a function, as in the ANSI C standard,
23619    --  defined to return the exit status. The three parameters
23620    --  are the argument count, argument values and environment
23621    --  pointer.
23622
23623 @findex Main Program
23624    function main
23625      (argc : Integer;
23626       argv : System.Address;
23627       envp : System.Address)
23628       return Integer
23629    is
23630       --  The initialize routine performs low level system
23631       --  initialization using a standard library routine which
23632       --  sets up signal handling and performs any other
23633       --  required setup. The routine can be found in file
23634       --  a-init.c.
23635
23636 @findex __gnat_initialize
23637       procedure initialize;
23638       pragma Import (C, initialize, "__gnat_initialize");
23639
23640       --  The finalize routine performs low level system
23641       --  finalization using a standard library routine. The
23642       --  routine is found in file a-final.c and in the standard
23643       --  distribution is a dummy routine that does nothing, so
23644       --  really this is a hook for special user finalization.
23645
23646 @findex __gnat_finalize
23647       procedure finalize;
23648       pragma Import (C, finalize, "__gnat_finalize");
23649
23650       --  We get to the main program of the partition by using
23651       --  pragma Import because if we try to with the unit and
23652       --  call it Ada style, then not only do we waste time
23653       --  recompiling it, but also, we don't really know the right
23654       --  switches (e.g. identifier character set) to be used
23655       --  to compile it.
23656
23657       procedure Ada_Main_Program;
23658       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23659
23660    --  Start of processing for main
23661
23662    begin
23663       --  Save global variables
23664
23665       gnat_argc := argc;
23666       gnat_argv := argv;
23667       gnat_envp := envp;
23668
23669       --  Call low level system initialization
23670
23671       Initialize;
23672
23673       --  Call our generated Ada initialization routine
23674
23675       adainit;
23676
23677       --  This is the point at which we want the debugger to get
23678       --  control
23679
23680       Break_Start;
23681
23682       --  Now we call the main program of the partition
23683
23684       Ada_Main_Program;
23685
23686       --  Perform Ada finalization
23687
23688       adafinal;
23689
23690       --  Perform low level system finalization
23691
23692       Finalize;
23693
23694       --  Return the proper exit status
23695       return (gnat_exit_status);
23696    end;
23697
23698 --  This section is entirely comments, so it has no effect on the
23699 --  compilation of the Ada_Main package. It provides the list of
23700 --  object files and linker options, as well as some standard
23701 --  libraries needed for the link. The gnatlink utility parses
23702 --  this b~hello.adb file to read these comment lines to generate
23703 --  the appropriate command line arguments for the call to the
23704 --  system linker. The BEGIN/END lines are used for sentinels for
23705 --  this parsing operation.
23706
23707 --  The exact file names will of course depend on the environment,
23708 --  host/target and location of files on the host system.
23709
23710 @findex Object file list
23711 -- BEGIN Object file/option list
23712    --   ./hello.o
23713    --   -L./
23714    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23715    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23716 -- END Object file/option list
23717
23718 end ada_main;
23719 @end smallexample
23720
23721 @noindent
23722 The Ada code in the above example is exactly what is generated by the
23723 binder. We have added comments to more clearly indicate the function
23724 of each part of the generated @code{Ada_Main} package.
23725
23726 The code is standard Ada in all respects, and can be processed by any
23727 tools that handle Ada. In particular, it is possible to use the debugger
23728 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23729 suppose that for reasons that you do not understand, your program is crashing
23730 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23731 you can place a breakpoint on the call:
23732
23733 @smallexample @c ada
23734 Ada.Text_Io'Elab_Body;
23735 @end smallexample
23736
23737 @noindent
23738 and trace the elaboration routine for this package to find out where
23739 the problem might be (more usually of course you would be debugging
23740 elaboration code in your own application).
23741
23742 @node Elaboration Order Handling in GNAT
23743 @appendix Elaboration Order Handling in GNAT
23744 @cindex Order of elaboration
23745 @cindex Elaboration control
23746
23747 @menu
23748 * Elaboration Code in Ada 95::
23749 * Checking the Elaboration Order in Ada 95::
23750 * Controlling the Elaboration Order in Ada 95::
23751 * Controlling Elaboration in GNAT - Internal Calls::
23752 * Controlling Elaboration in GNAT - External Calls::
23753 * Default Behavior in GNAT - Ensuring Safety::
23754 * Treatment of Pragma Elaborate::
23755 * Elaboration Issues for Library Tasks::
23756 * Mixing Elaboration Models::
23757 * What to Do If the Default Elaboration Behavior Fails::
23758 * Elaboration for Access-to-Subprogram Values::
23759 * Summary of Procedures for Elaboration Control::
23760 * Other Elaboration Order Considerations::
23761 @end menu
23762
23763 @noindent
23764 This chapter describes the handling of elaboration code in Ada 95 and
23765 in GNAT, and discusses how the order of elaboration of program units can
23766 be controlled in GNAT, either automatically or with explicit programming
23767 features.
23768
23769 @node Elaboration Code in Ada 95
23770 @section Elaboration Code in Ada 95
23771
23772 @noindent
23773 Ada 95 provides rather general mechanisms for executing code at elaboration
23774 time, that is to say before the main program starts executing. Such code arises
23775 in three contexts:
23776
23777 @table @asis
23778 @item Initializers for variables.
23779 Variables declared at the library level, in package specs or bodies, can
23780 require initialization that is performed at elaboration time, as in:
23781 @smallexample @c ada
23782 @cartouche
23783 Sqrt_Half : Float := Sqrt (0.5);
23784 @end cartouche
23785 @end smallexample
23786
23787 @item Package initialization code
23788 Code in a @code{BEGIN-END} section at the outer level of a package body is
23789 executed as part of the package body elaboration code.
23790
23791 @item Library level task allocators
23792 Tasks that are declared using task allocators at the library level
23793 start executing immediately and hence can execute at elaboration time.
23794 @end table
23795
23796 @noindent
23797 Subprogram calls are possible in any of these contexts, which means that
23798 any arbitrary part of the program may be executed as part of the elaboration
23799 code. It is even possible to write a program which does all its work at
23800 elaboration time, with a null main program, although stylistically this
23801 would usually be considered an inappropriate way to structure
23802 a program.
23803
23804 An important concern arises in the context of elaboration code:
23805 we have to be sure that it is executed in an appropriate order. What we
23806 have is a series of elaboration code sections, potentially one section
23807 for each unit in the program. It is important that these execute
23808 in the correct order. Correctness here means that, taking the above
23809 example of the declaration of @code{Sqrt_Half},
23810 if some other piece of
23811 elaboration code references @code{Sqrt_Half},
23812 then it must run after the
23813 section of elaboration code that contains the declaration of
23814 @code{Sqrt_Half}.
23815
23816 There would never be any order of elaboration problem if we made a rule
23817 that whenever you @code{with} a unit, you must elaborate both the spec and body
23818 of that unit before elaborating the unit doing the @code{with}'ing:
23819
23820 @smallexample @c ada
23821 @group
23822 @cartouche
23823 with Unit_1;
23824 package Unit_2 is ...
23825 @end cartouche
23826 @end group
23827 @end smallexample
23828
23829 @noindent
23830 would require that both the body and spec of @code{Unit_1} be elaborated
23831 before the spec of @code{Unit_2}. However, a rule like that would be far too
23832 restrictive. In particular, it would make it impossible to have routines
23833 in separate packages that were mutually recursive.
23834
23835 You might think that a clever enough compiler could look at the actual
23836 elaboration code and determine an appropriate correct order of elaboration,
23837 but in the general case, this is not possible. Consider the following
23838 example.
23839
23840 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23841 that references
23842 the variable @code{Sqrt_1}, which is declared in the elaboration code
23843 of the body of @code{Unit_1}:
23844
23845 @smallexample @c ada
23846 @cartouche
23847 Sqrt_1 : Float := Sqrt (0.1);
23848 @end cartouche
23849 @end smallexample
23850
23851 @noindent
23852 The elaboration code of the body of @code{Unit_1} also contains:
23853
23854 @smallexample @c ada
23855 @group
23856 @cartouche
23857 if expression_1 = 1 then
23858    Q := Unit_2.Func_2;
23859 end if;
23860 @end cartouche
23861 @end group
23862 @end smallexample
23863
23864 @noindent
23865 @code{Unit_2} is exactly parallel,
23866 it has a procedure @code{Func_2} that references
23867 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23868 the body @code{Unit_2}:
23869
23870 @smallexample @c ada
23871 @cartouche
23872 Sqrt_2 : Float := Sqrt (0.1);
23873 @end cartouche
23874 @end smallexample
23875
23876 @noindent
23877 The elaboration code of the body of @code{Unit_2} also contains:
23878
23879 @smallexample @c ada
23880 @group
23881 @cartouche
23882 if expression_2 = 2 then
23883    Q := Unit_1.Func_1;
23884 end if;
23885 @end cartouche
23886 @end group
23887 @end smallexample
23888
23889 @noindent
23890 Now the question is, which of the following orders of elaboration is
23891 acceptable:
23892
23893 @smallexample
23894 @group
23895 Spec of Unit_1
23896 Spec of Unit_2
23897 Body of Unit_1
23898 Body of Unit_2
23899 @end group
23900 @end smallexample
23901
23902 @noindent
23903 or
23904
23905 @smallexample
23906 @group
23907 Spec of Unit_2
23908 Spec of Unit_1
23909 Body of Unit_2
23910 Body of Unit_1
23911 @end group
23912 @end smallexample
23913
23914 @noindent
23915 If you carefully analyze the flow here, you will see that you cannot tell
23916 at compile time the answer to this question.
23917 If @code{expression_1} is not equal to 1,
23918 and @code{expression_2} is not equal to 2,
23919 then either order is acceptable, because neither of the function calls is
23920 executed. If both tests evaluate to true, then neither order is acceptable
23921 and in fact there is no correct order.
23922
23923 If one of the two expressions is true, and the other is false, then one
23924 of the above orders is correct, and the other is incorrect. For example,
23925 if @code{expression_1} = 1 and @code{expression_2} /= 2,
23926 then the call to @code{Func_2}
23927 will occur, but not the call to @code{Func_1.}
23928 This means that it is essential
23929 to elaborate the body of @code{Unit_1} before
23930 the body of @code{Unit_2}, so the first
23931 order of elaboration is correct and the second is wrong.
23932
23933 By making @code{expression_1} and @code{expression_2}
23934 depend on input data, or perhaps
23935 the time of day, we can make it impossible for the compiler or binder
23936 to figure out which of these expressions will be true, and hence it
23937 is impossible to guarantee a safe order of elaboration at run time.
23938
23939 @node Checking the Elaboration Order in Ada 95
23940 @section Checking the Elaboration Order in Ada 95
23941
23942 @noindent
23943 In some languages that involve the same kind of elaboration problems,
23944 e.g. Java and C++, the programmer is expected to worry about these
23945 ordering problems himself, and it is common to
23946 write a program in which an incorrect elaboration order  gives
23947 surprising results, because it references variables before they
23948 are initialized.
23949 Ada 95 is designed to be a safe language, and a programmer-beware approach is
23950 clearly not sufficient. Consequently, the language provides three lines
23951 of defense:
23952
23953 @table @asis
23954 @item Standard rules
23955 Some standard rules restrict the possible choice of elaboration
23956 order. In particular, if you @code{with} a unit, then its spec is always
23957 elaborated before the unit doing the @code{with}. Similarly, a parent
23958 spec is always elaborated before the child spec, and finally
23959 a spec is always elaborated before its corresponding body.
23960
23961 @item Dynamic elaboration checks
23962 @cindex Elaboration checks
23963 @cindex Checks, elaboration
23964 Dynamic checks are made at run time, so that if some entity is accessed
23965 before it is elaborated (typically  by means of a subprogram call)
23966 then the exception (@code{Program_Error}) is raised.
23967
23968 @item Elaboration control
23969 Facilities are provided for the programmer to specify the desired order
23970 of elaboration.
23971 @end table
23972
23973 Let's look at these facilities in more detail. First, the rules for
23974 dynamic checking. One possible rule would be simply to say that the
23975 exception is raised if you access a variable which has not yet been
23976 elaborated. The trouble with this approach is that it could require
23977 expensive checks on every variable reference. Instead Ada 95 has two
23978 rules which are a little more restrictive, but easier to check, and
23979 easier to state:
23980
23981 @table @asis
23982 @item Restrictions on calls
23983 A subprogram can only be called at elaboration time if its body
23984 has been elaborated. The rules for elaboration given above guarantee
23985 that the spec of the subprogram has been elaborated before the
23986 call, but not the body. If this rule is violated, then the
23987 exception @code{Program_Error} is raised.
23988
23989 @item Restrictions on instantiations
23990 A generic unit can only be instantiated if the body of the generic
23991 unit has been elaborated. Again, the rules for elaboration given above
23992 guarantee that the spec of the generic unit has been elaborated
23993 before the instantiation, but not the body. If this rule is
23994 violated, then the exception @code{Program_Error} is raised.
23995 @end table
23996
23997 @noindent
23998 The idea is that if the body has been elaborated, then any variables
23999 it references must have been elaborated; by checking for the body being
24000 elaborated we guarantee that none of its references causes any
24001 trouble. As we noted above, this is a little too restrictive, because a
24002 subprogram that has no non-local references in its body may in fact be safe
24003 to call. However, it really would be unsafe to rely on this, because
24004 it would mean that the caller was aware of details of the implementation
24005 in the body. This goes against the basic tenets of Ada.
24006
24007 A plausible implementation can be described as follows.
24008 A Boolean variable is associated with each subprogram
24009 and each generic unit. This variable is initialized to False, and is set to
24010 True at the point body is elaborated. Every call or instantiation checks the
24011 variable, and raises @code{Program_Error} if the variable is False.
24012
24013 Note that one might think that it would be good enough to have one Boolean
24014 variable for each package, but that would not deal with cases of trying
24015 to call a body in the same package as the call
24016 that has not been elaborated yet.
24017 Of course a compiler may be able to do enough analysis to optimize away
24018 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24019 does such optimizations, but still the easiest conceptual model is to
24020 think of there being one variable per subprogram.
24021
24022 @node Controlling the Elaboration Order in Ada 95
24023 @section Controlling the Elaboration Order in Ada 95
24024
24025 @noindent
24026 In the previous section we discussed the rules in Ada 95 which ensure
24027 that @code{Program_Error} is raised if an incorrect elaboration order is
24028 chosen. This prevents erroneous executions, but we need mechanisms to
24029 specify a correct execution and avoid the exception altogether.
24030 To achieve this, Ada 95 provides a number of features for controlling
24031 the order of elaboration. We discuss these features in this section.
24032
24033 First, there are several ways of indicating to the compiler that a given
24034 unit has no elaboration problems:
24035
24036 @table @asis
24037 @item packages that do not require a body
24038 In Ada 95, a library package that does not require a body does not permit
24039 a body. This means that if we have a such a package, as in:
24040
24041 @smallexample @c ada
24042 @group
24043 @cartouche
24044 package Definitions is
24045    generic
24046       type m is new integer;
24047    package Subp is
24048       type a is array (1 .. 10) of m;
24049       type b is array (1 .. 20) of m;
24050    end Subp;
24051 end Definitions;
24052 @end cartouche
24053 @end group
24054 @end smallexample
24055
24056 @noindent
24057 A package that @code{with}'s @code{Definitions} may safely instantiate
24058 @code{Definitions.Subp} because the compiler can determine that there
24059 definitely is no package body to worry about in this case
24060
24061 @item pragma Pure
24062 @cindex pragma Pure
24063 @findex Pure
24064 Places sufficient restrictions on a unit to guarantee that
24065 no call to any subprogram in the unit can result in an
24066 elaboration problem. This means that the compiler does not need
24067 to worry about the point of elaboration of such units, and in
24068 particular, does not need to check any calls to any subprograms
24069 in this unit.
24070
24071 @item pragma Preelaborate
24072 @findex Preelaborate
24073 @cindex pragma Preelaborate
24074 This pragma places slightly less stringent restrictions on a unit than
24075 does pragma Pure,
24076 but these restrictions are still sufficient to ensure that there
24077 are no elaboration problems with any calls to the unit.
24078
24079 @item pragma Elaborate_Body
24080 @findex Elaborate_Body
24081 @cindex pragma Elaborate_Body
24082 This pragma requires that the body of a unit be elaborated immediately
24083 after its spec. Suppose a unit @code{A} has such a pragma,
24084 and unit @code{B} does
24085 a @code{with} of unit @code{A}. Recall that the standard rules require
24086 the spec of unit @code{A}
24087 to be elaborated before the @code{with}'ing unit; given the pragma in
24088 @code{A}, we also know that the body of @code{A}
24089 will be elaborated before @code{B}, so
24090 that calls to @code{A} are safe and do not need a check.
24091 @end table
24092
24093 @noindent
24094 Note that,
24095 unlike pragma @code{Pure} and pragma @code{Preelaborate},
24096 the use of
24097 @code{Elaborate_Body} does not guarantee that the program is
24098 free of elaboration problems, because it may not be possible
24099 to satisfy the requested elaboration order.
24100 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
24101 If a programmer
24102 marks @code{Unit_1} as @code{Elaborate_Body},
24103 and not @code{Unit_2,} then the order of
24104 elaboration will be:
24105
24106 @smallexample
24107 @group
24108 Spec of Unit_2
24109 Spec of Unit_1
24110 Body of Unit_1
24111 Body of Unit_2
24112 @end group
24113 @end smallexample
24114
24115 @noindent
24116 Now that means that the call to @code{Func_1} in @code{Unit_2}
24117 need not be checked,
24118 it must be safe. But the call to @code{Func_2} in
24119 @code{Unit_1} may still fail if
24120 @code{Expression_1} is equal to 1,
24121 and the programmer must still take
24122 responsibility for this not being the case.
24123
24124 If all units carry a pragma @code{Elaborate_Body}, then all problems are
24125 eliminated, except for calls entirely within a body, which are
24126 in any case fully under programmer control. However, using the pragma
24127 everywhere is not always possible.
24128 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
24129 we marked both of them as having pragma @code{Elaborate_Body}, then
24130 clearly there would be no possible elaboration order.
24131
24132 The above pragmas allow a server to guarantee safe use by clients, and
24133 clearly this is the preferable approach. Consequently a good rule in
24134 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
24135 and if this is not possible,
24136 mark them as @code{Elaborate_Body} if possible.
24137 As we have seen, there are situations where neither of these
24138 three pragmas can be used.
24139 So we also provide methods for clients to control the
24140 order of elaboration of the servers on which they depend:
24141
24142 @table @asis
24143 @item pragma Elaborate (unit)
24144 @findex Elaborate
24145 @cindex pragma Elaborate
24146 This pragma is placed in the context clause, after a @code{with} clause,
24147 and it requires that the body of the named unit be elaborated before
24148 the unit in which the pragma occurs. The idea is to use this pragma
24149 if the current unit calls at elaboration time, directly or indirectly,
24150 some subprogram in the named unit.
24151
24152 @item pragma Elaborate_All (unit)
24153 @findex Elaborate_All
24154 @cindex pragma Elaborate_All
24155 This is a stronger version of the Elaborate pragma. Consider the
24156 following example:
24157
24158 @smallexample
24159 Unit A @code{with}'s unit B and calls B.Func in elab code
24160 Unit B @code{with}'s unit C, and B.Func calls C.Func
24161 @end smallexample
24162
24163 @noindent
24164 Now if we put a pragma @code{Elaborate (B)}
24165 in unit @code{A}, this ensures that the
24166 body of @code{B} is elaborated before the call, but not the
24167 body of @code{C}, so
24168 the call to @code{C.Func} could still cause @code{Program_Error} to
24169 be raised.
24170
24171 The effect of a pragma @code{Elaborate_All} is stronger, it requires
24172 not only that the body of the named unit be elaborated before the
24173 unit doing the @code{with}, but also the bodies of all units that the
24174 named unit uses, following @code{with} links transitively. For example,
24175 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
24176 then it requires
24177 not only that the body of @code{B} be elaborated before @code{A},
24178 but also the
24179 body of @code{C}, because @code{B} @code{with}'s @code{C}.
24180 @end table
24181
24182 @noindent
24183 We are now in a position to give a usage rule in Ada 95 for avoiding
24184 elaboration problems, at least if dynamic dispatching and access to
24185 subprogram values are not used. We will handle these cases separately
24186 later.
24187
24188 The rule is simple. If a unit has elaboration code that can directly or
24189 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
24190 a generic package in a @code{with}'ed unit,
24191 then if the @code{with}'ed unit does not have
24192 pragma @code{Pure} or @code{Preelaborate}, then the client should have
24193 a pragma @code{Elaborate_All}
24194 for the @code{with}'ed unit. By following this rule a client is
24195 assured that calls can be made without risk of an exception.
24196
24197 For generic subprogram instantiations, the rule can be relaxed to
24198 require only a pragma @code{Elaborate} since elaborating the body
24199 of a subprogram cannot cause any transitive elaboration (we are
24200 not calling the subprogram in this case, just elaborating its
24201 declaration).
24202
24203 If this rule is not followed, then a program may be in one of four
24204 states:
24205
24206 @table @asis
24207 @item No order exists
24208 No order of elaboration exists which follows the rules, taking into
24209 account any @code{Elaborate}, @code{Elaborate_All},
24210 or @code{Elaborate_Body} pragmas. In
24211 this case, an Ada 95 compiler must diagnose the situation at bind
24212 time, and refuse to build an executable program.
24213
24214 @item One or more orders exist, all incorrect
24215 One or more acceptable elaboration orders exists, and all of them
24216 generate an elaboration order problem. In this case, the binder
24217 can build an executable program, but @code{Program_Error} will be raised
24218 when the program is run.
24219
24220 @item Several orders exist, some right, some incorrect
24221 One or more acceptable elaboration orders exists, and some of them
24222 work, and some do not. The programmer has not controlled
24223 the order of elaboration, so the binder may or may not pick one of
24224 the correct orders, and the program may or may not raise an
24225 exception when it is run. This is the worst case, because it means
24226 that the program may fail when moved to another compiler, or even
24227 another version of the same compiler.
24228
24229 @item One or more orders exists, all correct
24230 One ore more acceptable elaboration orders exist, and all of them
24231 work. In this case the program runs successfully. This state of
24232 affairs can be guaranteed by following the rule we gave above, but
24233 may be true even if the rule is not followed.
24234 @end table
24235
24236 @noindent
24237 Note that one additional advantage of following our rules on the use
24238 of @code{Elaborate} and @code{Elaborate_All}
24239 is that the program continues to stay in the ideal (all orders OK) state
24240 even if maintenance
24241 changes some bodies of some units. Conversely, if a program that does
24242 not follow this rule happens to be safe at some point, this state of affairs
24243 may deteriorate silently as a result of maintenance changes.
24244
24245 You may have noticed that the above discussion did not mention
24246 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24247 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24248 code in the body makes calls to some other unit, so it is still necessary
24249 to use @code{Elaborate_All} on such units.
24250
24251 @node Controlling Elaboration in GNAT - Internal Calls
24252 @section Controlling Elaboration in GNAT - Internal Calls
24253
24254 @noindent
24255 In the case of internal calls, i.e. calls within a single package, the
24256 programmer has full control over the order of elaboration, and it is up
24257 to the programmer to elaborate declarations in an appropriate order. For
24258 example writing:
24259
24260 @smallexample @c ada
24261 @group
24262 @cartouche
24263 function One return Float;
24264
24265 Q : Float := One;
24266
24267 function One return Float is
24268 begin
24269      return 1.0;
24270 end One;
24271 @end cartouche
24272 @end group
24273 @end smallexample
24274
24275 @noindent
24276 will obviously raise @code{Program_Error} at run time, because function
24277 One will be called before its body is elaborated. In this case GNAT will
24278 generate a warning that the call will raise @code{Program_Error}:
24279
24280 @smallexample
24281 @group
24282 @cartouche
24283  1. procedure y is
24284  2.    function One return Float;
24285  3.
24286  4.    Q : Float := One;
24287                     |
24288     >>> warning: cannot call "One" before body is elaborated
24289     >>> warning: Program_Error will be raised at run time
24290
24291  5.
24292  6.    function One return Float is
24293  7.    begin
24294  8.         return 1.0;
24295  9.    end One;
24296 10.
24297 11. begin
24298 12.    null;
24299 13. end;
24300 @end cartouche
24301 @end group
24302 @end smallexample
24303
24304 @noindent
24305 Note that in this particular case, it is likely that the call is safe, because
24306 the function @code{One} does not access any global variables.
24307 Nevertheless in Ada 95, we do not want the validity of the check to depend on
24308 the contents of the body (think about the separate compilation case), so this
24309 is still wrong, as we discussed in the previous sections.
24310
24311 The error is easily corrected by rearranging the declarations so that the
24312 body of One appears before the declaration containing the call
24313 (note that in Ada 95,
24314 declarations can appear in any order, so there is no restriction that
24315 would prevent this reordering, and if we write:
24316
24317 @smallexample @c ada
24318 @group
24319 @cartouche
24320 function One return Float;
24321
24322 function One return Float is
24323 begin
24324      return 1.0;
24325 end One;
24326
24327 Q : Float := One;
24328 @end cartouche
24329 @end group
24330 @end smallexample
24331
24332 @noindent
24333 then all is well, no warning is generated, and no
24334 @code{Program_Error} exception
24335 will be raised.
24336 Things are more complicated when a chain of subprograms is executed:
24337
24338 @smallexample @c ada
24339 @group
24340 @cartouche
24341 function A return Integer;
24342 function B return Integer;
24343 function C return Integer;
24344
24345 function B return Integer is begin return A; end;
24346 function C return Integer is begin return B; end;
24347
24348 X : Integer := C;
24349
24350 function A return Integer is begin return 1; end;
24351 @end cartouche
24352 @end group
24353 @end smallexample
24354
24355 @noindent
24356 Now the call to @code{C}
24357 at elaboration time in the declaration of @code{X} is correct, because
24358 the body of @code{C} is already elaborated,
24359 and the call to @code{B} within the body of
24360 @code{C} is correct, but the call
24361 to @code{A} within the body of @code{B} is incorrect, because the body
24362 of @code{A} has not been elaborated, so @code{Program_Error}
24363 will be raised on the call to @code{A}.
24364 In this case GNAT will generate a
24365 warning that @code{Program_Error} may be
24366 raised at the point of the call. Let's look at the warning:
24367
24368 @smallexample
24369 @group
24370 @cartouche
24371  1. procedure x is
24372  2.    function A return Integer;
24373  3.    function B return Integer;
24374  4.    function C return Integer;
24375  5.
24376  6.    function B return Integer is begin return A; end;
24377                                                     |
24378     >>> warning: call to "A" before body is elaborated may
24379                  raise Program_Error
24380     >>> warning: "B" called at line 7
24381     >>> warning: "C" called at line 9
24382
24383  7.    function C return Integer is begin return B; end;
24384  8.
24385  9.    X : Integer := C;
24386 10.
24387 11.    function A return Integer is begin return 1; end;
24388 12.
24389 13. begin
24390 14.    null;
24391 15. end;
24392 @end cartouche
24393 @end group
24394 @end smallexample
24395
24396 @noindent
24397 Note that the message here says ``may raise'', instead of the direct case,
24398 where the message says ``will be raised''. That's because whether
24399 @code{A} is
24400 actually called depends in general on run-time flow of control.
24401 For example, if the body of @code{B} said
24402
24403 @smallexample @c ada
24404 @group
24405 @cartouche
24406 function B return Integer is
24407 begin
24408    if some-condition-depending-on-input-data then
24409       return A;
24410    else
24411       return 1;
24412    end if;
24413 end B;
24414 @end cartouche
24415 @end group
24416 @end smallexample
24417
24418 @noindent
24419 then we could not know until run time whether the incorrect call to A would
24420 actually occur, so @code{Program_Error} might
24421 or might not be raised. It is possible for a compiler to
24422 do a better job of analyzing bodies, to
24423 determine whether or not @code{Program_Error}
24424 might be raised, but it certainly
24425 couldn't do a perfect job (that would require solving the halting problem
24426 and is provably impossible), and because this is a warning anyway, it does
24427 not seem worth the effort to do the analysis. Cases in which it
24428 would be relevant are rare.
24429
24430 In practice, warnings of either of the forms given
24431 above will usually correspond to
24432 real errors, and should be examined carefully and eliminated.
24433 In the rare case where a warning is bogus, it can be suppressed by any of
24434 the following methods:
24435
24436 @itemize @bullet
24437 @item
24438 Compile with the @option{-gnatws} switch set
24439
24440 @item
24441 Suppress @code{Elaboration_Check} for the called subprogram
24442
24443 @item
24444 Use pragma @code{Warnings_Off} to turn warnings off for the call
24445 @end itemize
24446
24447 @noindent
24448 For the internal elaboration check case,
24449 GNAT by default generates the
24450 necessary run-time checks to ensure
24451 that @code{Program_Error} is raised if any
24452 call fails an elaboration check. Of course this can only happen if a
24453 warning has been issued as described above. The use of pragma
24454 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24455 some of these checks, meaning that it may be possible (but is not
24456 guaranteed) for a program to be able to call a subprogram whose body
24457 is not yet elaborated, without raising a @code{Program_Error} exception.
24458
24459 @node Controlling Elaboration in GNAT - External Calls
24460 @section Controlling Elaboration in GNAT - External Calls
24461
24462 @noindent
24463 The previous section discussed the case in which the execution of a
24464 particular thread of elaboration code occurred entirely within a
24465 single unit. This is the easy case to handle, because a programmer
24466 has direct and total control over the order of elaboration, and
24467 furthermore, checks need only be generated in cases which are rare
24468 and which the compiler can easily detect.
24469 The situation is more complex when separate compilation is taken into account.
24470 Consider the following:
24471
24472 @smallexample @c ada
24473 @cartouche
24474 @group
24475 package Math is
24476    function Sqrt (Arg : Float) return Float;
24477 end Math;
24478
24479 package body Math is
24480    function Sqrt (Arg : Float) return Float is
24481    begin
24482          ...
24483    end Sqrt;
24484 end Math;
24485 @end group
24486 @group
24487 with Math;
24488 package Stuff is
24489    X : Float := Math.Sqrt (0.5);
24490 end Stuff;
24491
24492 with Stuff;
24493 procedure Main is
24494 begin
24495    ...
24496 end Main;
24497 @end group
24498 @end cartouche
24499 @end smallexample
24500
24501 @noindent
24502 where @code{Main} is the main program. When this program is executed, the
24503 elaboration code must first be executed, and one of the jobs of the
24504 binder is to determine the order in which the units of a program are
24505 to be elaborated. In this case we have four units: the spec and body
24506 of @code{Math},
24507 the spec of @code{Stuff} and the body of @code{Main}).
24508 In what order should the four separate sections of elaboration code
24509 be executed?
24510
24511 There are some restrictions in the order of elaboration that the binder
24512 can choose. In particular, if unit U has a @code{with}
24513 for a package @code{X}, then you
24514 are assured that the spec of @code{X}
24515 is elaborated before U , but you are
24516 not assured that the body of @code{X}
24517 is elaborated before U.
24518 This means that in the above case, the binder is allowed to choose the
24519 order:
24520
24521 @smallexample
24522 spec of Math
24523 spec of Stuff
24524 body of Math
24525 body of Main
24526 @end smallexample
24527
24528 @noindent
24529 but that's not good, because now the call to @code{Math.Sqrt}
24530 that happens during
24531 the elaboration of the @code{Stuff}
24532 spec happens before the body of @code{Math.Sqrt} is
24533 elaborated, and hence causes @code{Program_Error} exception to be raised.
24534 At first glance, one might say that the binder is misbehaving, because
24535 obviously you want to elaborate the body of something you @code{with}
24536 first, but
24537 that is not a general rule that can be followed in all cases. Consider
24538
24539 @smallexample @c ada
24540 @group
24541 @cartouche
24542 package X is ...
24543
24544 package Y is ...
24545
24546 with X;
24547 package body Y is ...
24548
24549 with Y;
24550 package body X is ...
24551 @end cartouche
24552 @end group
24553 @end smallexample
24554
24555 @noindent
24556 This is a common arrangement, and, apart from the order of elaboration
24557 problems that might arise in connection with elaboration code, this works fine.
24558 A rule that says that you must first elaborate the body of anything you
24559 @code{with} cannot work in this case:
24560 the body of @code{X} @code{with}'s @code{Y},
24561 which means you would have to
24562 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24563 which means
24564 you have to elaborate the body of @code{X} first, but ... and we have a
24565 loop that cannot be broken.
24566
24567 It is true that the binder can in many cases guess an order of elaboration
24568 that is unlikely to cause a @code{Program_Error}
24569 exception to be raised, and it tries to do so (in the
24570 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24571 by default
24572 elaborate the body of @code{Math} right after its spec, so all will be well).
24573
24574 However, a program that blindly relies on the binder to be helpful can
24575 get into trouble, as we discussed in the previous sections, so
24576 GNAT
24577 provides a number of facilities for assisting the programmer in
24578 developing programs that are robust with respect to elaboration order.
24579
24580 @node Default Behavior in GNAT - Ensuring Safety
24581 @section Default Behavior in GNAT - Ensuring Safety
24582
24583 @noindent
24584 The default behavior in GNAT ensures elaboration safety. In its
24585 default mode GNAT implements the
24586 rule we previously described as the right approach. Let's restate it:
24587
24588 @itemize
24589 @item
24590 @emph{If a unit has elaboration code that can directly or indirectly make a
24591 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24592 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24593 does not have pragma @code{Pure} or
24594 @code{Preelaborate}, then the client should have an
24595 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24596
24597 @emph{In the case of instantiating a generic subprogram, it is always
24598 sufficient to have only an @code{Elaborate} pragma for the
24599 @code{with}'ed unit.}
24600 @end itemize
24601
24602 @noindent
24603 By following this rule a client is assured that calls and instantiations
24604 can be made without risk of an exception.
24605
24606 In this mode GNAT traces all calls that are potentially made from
24607 elaboration code, and puts in any missing implicit @code{Elaborate}
24608 and @code{Elaborate_All} pragmas.
24609 The advantage of this approach is that no elaboration problems
24610 are possible if the binder can find an elaboration order that is
24611 consistent with these implicit @code{Elaborate} and
24612 @code{Elaborate_All} pragmas. The
24613 disadvantage of this approach is that no such order may exist.
24614
24615 If the binder does not generate any diagnostics, then it means that it has
24616 found an elaboration order that is guaranteed to be safe. However, the binder
24617 may still be relying on implicitly generated @code{Elaborate} and
24618 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24619 guaranteed.
24620
24621 If it is important to guarantee portability, then the compilations should
24622 use the
24623 @option{-gnatwl}
24624 (warn on elaboration problems) switch. This will cause warning messages
24625 to be generated indicating the missing @code{Elaborate} and
24626 @code{Elaborate_All} pragmas.
24627 Consider the following source program:
24628
24629 @smallexample @c ada
24630 @group
24631 @cartouche
24632 with k;
24633 package j is
24634   m : integer := k.r;
24635 end;
24636 @end cartouche
24637 @end group
24638 @end smallexample
24639
24640 @noindent
24641 where it is clear that there
24642 should be a pragma @code{Elaborate_All}
24643 for unit @code{k}. An implicit pragma will be generated, and it is
24644 likely that the binder will be able to honor it. However, if you want
24645 to port this program to some other Ada compiler than GNAT.
24646 it is safer to include the pragma explicitly in the source. If this
24647 unit is compiled with the
24648 @option{-gnatwl}
24649 switch, then the compiler outputs a warning:
24650
24651 @smallexample
24652 @group
24653 @cartouche
24654 1. with k;
24655 2. package j is
24656 3.   m : integer := k.r;
24657                      |
24658    >>> warning: call to "r" may raise Program_Error
24659    >>> warning: missing pragma Elaborate_All for "k"
24660
24661 4. end;
24662 @end cartouche
24663 @end group
24664 @end smallexample
24665
24666 @noindent
24667 and these warnings can be used as a guide for supplying manually
24668 the missing pragmas. It is usually a bad idea to use this warning
24669 option during development. That's because it will warn you when
24670 you need to put in a pragma, but cannot warn you when it is time
24671 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24672 unnecessary dependencies and even false circularities.
24673
24674 This default mode is more restrictive than the Ada Reference
24675 Manual, and it is possible to construct programs which will compile
24676 using the dynamic model described there, but will run into a
24677 circularity using the safer static model we have described.
24678
24679 Of course any Ada compiler must be able to operate in a mode
24680 consistent with the requirements of the Ada Reference Manual,
24681 and in particular must have the capability of implementing the
24682 standard dynamic model of elaboration with run-time checks.
24683
24684 In GNAT, this standard mode can be achieved either by the use of
24685 the @option{-gnatE} switch on the compiler (@command{gcc} or
24686 @command{gnatmake}) command, or by the use of the configuration pragma:
24687
24688 @smallexample @c ada
24689 pragma Elaboration_Checks (RM);
24690 @end smallexample
24691
24692 @noindent
24693 Either approach will cause the unit affected to be compiled using the
24694 standard dynamic run-time elaboration checks described in the Ada
24695 Reference Manual. The static model is generally preferable, since it
24696 is clearly safer to rely on compile and link time checks rather than
24697 run-time checks. However, in the case of legacy code, it may be
24698 difficult to meet the requirements of the static model. This
24699 issue is further discussed in
24700 @ref{What to Do If the Default Elaboration Behavior Fails}.
24701
24702 Note that the static model provides a strict subset of the allowed
24703 behavior and programs of the Ada Reference Manual, so if you do
24704 adhere to the static model and no circularities exist,
24705 then you are assured that your program will
24706 work using the dynamic model, providing that you remove any
24707 pragma Elaborate statements from the source.
24708
24709 @node Treatment of Pragma Elaborate
24710 @section Treatment of Pragma Elaborate
24711 @cindex Pragma Elaborate
24712
24713 @noindent
24714 The use of @code{pragma Elaborate}
24715 should generally be avoided in Ada 95 programs.
24716 The reason for this is that there is no guarantee that transitive calls
24717 will be properly handled. Indeed at one point, this pragma was placed
24718 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24719
24720 Now that's a bit restrictive. In practice, the case in which
24721 @code{pragma Elaborate} is useful is when the caller knows that there
24722 are no transitive calls, or that the called unit contains all necessary
24723 transitive @code{pragma Elaborate} statements, and legacy code often
24724 contains such uses.
24725
24726 Strictly speaking the static mode in GNAT should ignore such pragmas,
24727 since there is no assurance at compile time that the necessary safety
24728 conditions are met. In practice, this would cause GNAT to be incompatible
24729 with correctly written Ada 83 code that had all necessary
24730 @code{pragma Elaborate} statements in place. Consequently, we made the
24731 decision that GNAT in its default mode will believe that if it encounters
24732 a @code{pragma Elaborate} then the programmer knows what they are doing,
24733 and it will trust that no elaboration errors can occur.
24734
24735 The result of this decision is two-fold. First to be safe using the
24736 static mode, you should remove all @code{pragma Elaborate} statements.
24737 Second, when fixing circularities in existing code, you can selectively
24738 use @code{pragma Elaborate} statements to convince the static mode of
24739 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24740 statement.
24741
24742 When using the static mode with @option{-gnatwl}, any use of
24743 @code{pragma Elaborate} will generate a warning about possible
24744 problems.
24745
24746 @node Elaboration Issues for Library Tasks
24747 @section Elaboration Issues for Library Tasks
24748 @cindex Library tasks, elaboration issues
24749 @cindex Elaboration of library tasks
24750
24751 @noindent
24752 In this section we examine special elaboration issues that arise for
24753 programs that declare library level tasks.
24754
24755 Generally the model of execution of an Ada program is that all units are
24756 elaborated, and then execution of the program starts. However, the
24757 declaration of library tasks definitely does not fit this model. The
24758 reason for this is that library tasks start as soon as they are declared
24759 (more precisely, as soon as the statement part of the enclosing package
24760 body is reached), that is to say before elaboration
24761 of the program is complete. This means that if such a task calls a
24762 subprogram, or an entry in another task, the callee may or may not be
24763 elaborated yet, and in the standard
24764 Reference Manual model of dynamic elaboration checks, you can even
24765 get timing dependent Program_Error exceptions, since there can be
24766 a race between the elaboration code and the task code.
24767
24768 The static model of elaboration in GNAT seeks to avoid all such
24769 dynamic behavior, by being conservative, and the conservative
24770 approach in this particular case is to assume that all the code
24771 in a task body is potentially executed at elaboration time if
24772 a task is declared at the library level.
24773
24774 This can definitely result in unexpected circularities. Consider
24775 the following example
24776
24777 @smallexample @c ada
24778 package Decls is
24779   task Lib_Task is
24780      entry Start;
24781   end Lib_Task;
24782
24783   type My_Int is new Integer;
24784
24785   function Ident (M : My_Int) return My_Int;
24786 end Decls;
24787
24788 with Utils;
24789 package body Decls is
24790   task body Lib_Task is
24791   begin
24792      accept Start;
24793      Utils.Put_Val (2);
24794   end Lib_Task;
24795
24796   function Ident (M : My_Int) return My_Int is
24797   begin
24798      return M;
24799   end Ident;
24800 end Decls;
24801
24802 with Decls;
24803 package Utils is
24804   procedure Put_Val (Arg : Decls.My_Int);
24805 end Utils;
24806
24807 with Text_IO;
24808 package body Utils is
24809   procedure Put_Val (Arg : Decls.My_Int) is
24810   begin
24811      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24812   end Put_Val;
24813 end Utils;
24814
24815 with Decls;
24816 procedure Main is
24817 begin
24818    Decls.Lib_Task.Start;
24819 end;
24820 @end smallexample
24821
24822 @noindent
24823 If the above example is compiled in the default static elaboration
24824 mode, then a circularity occurs. The circularity comes from the call
24825 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24826 this call occurs in elaboration code, we need an implicit pragma
24827 @code{Elaborate_All} for @code{Utils}. This means that not only must
24828 the spec and body of @code{Utils} be elaborated before the body
24829 of @code{Decls}, but also the spec and body of any unit that is
24830 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24831 the body of @code{Decls}. This is the transitive implication of
24832 pragma @code{Elaborate_All} and it makes sense, because in general
24833 the body of @code{Put_Val} might have a call to something in a
24834 @code{with'ed} unit.
24835
24836 In this case, the body of Utils (actually its spec) @code{with's}
24837 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24838 must be elaborated before itself, in case there is a call from the
24839 body of @code{Utils}.
24840
24841 Here is the exact chain of events we are worrying about:
24842
24843 @enumerate
24844 @item
24845 In the body of @code{Decls} a call is made from within the body of a library
24846 task to a subprogram in the package @code{Utils}. Since this call may
24847 occur at elaboration time (given that the task is activated at elaboration
24848 time), we have to assume the worst, i.e. that the
24849 call does happen at elaboration time.
24850
24851 @item
24852 This means that the body and spec of @code{Util} must be elaborated before
24853 the body of @code{Decls} so that this call does not cause an access before
24854 elaboration.
24855
24856 @item
24857 Within the body of @code{Util}, specifically within the body of
24858 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24859 by this package.
24860
24861 @item
24862 One such @code{with}'ed package is package @code{Decls}, so there
24863 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24864 In fact there is such a call in this example, but we would have to
24865 assume that there was such a call even if it were not there, since
24866 we are not supposed to write the body of @code{Decls} knowing what
24867 is in the body of @code{Utils}; certainly in the case of the
24868 static elaboration model, the compiler does not know what is in
24869 other bodies and must assume the worst.
24870
24871 @item
24872 This means that the spec and body of @code{Decls} must also be
24873 elaborated before we elaborate the unit containing the call, but
24874 that unit is @code{Decls}! This means that the body of @code{Decls}
24875 must be elaborated before itself, and that's a circularity.
24876 @end enumerate
24877
24878 @noindent
24879 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24880 the body of @code{Decls} you will get a true Ada Reference Manual
24881 circularity that makes the program illegal.
24882
24883 In practice, we have found that problems with the static model of
24884 elaboration in existing code often arise from library tasks, so
24885 we must address this particular situation.
24886
24887 Note that if we compile and run the program above, using the dynamic model of
24888 elaboration (that is to say use the @option{-gnatE} switch),
24889 then it compiles, binds,
24890 links, and runs, printing the expected result of 2. Therefore in some sense
24891 the circularity here is only apparent, and we need to capture
24892 the properties of this program that  distinguish it from other library-level
24893 tasks that have real elaboration problems.
24894
24895 We have four possible answers to this question:
24896
24897 @itemize @bullet
24898
24899 @item
24900 Use the dynamic model of elaboration.
24901
24902 If we use the @option{-gnatE} switch, then as noted above, the program works.
24903 Why is this? If we examine the task body, it is apparent that the task cannot
24904 proceed past the
24905 @code{accept} statement until after elaboration has been completed, because
24906 the corresponding entry call comes from the main program, not earlier.
24907 This is why the dynamic model works here. But that's really giving
24908 up on a precise analysis, and we prefer to take this approach only if we cannot
24909 solve the
24910 problem in any other manner. So let us examine two ways to reorganize
24911 the program to avoid the potential elaboration problem.
24912
24913 @item
24914 Split library tasks into separate packages.
24915
24916 Write separate packages, so that library tasks are isolated from
24917 other declarations as much as possible. Let us look at a variation on
24918 the above program.
24919
24920 @smallexample @c ada
24921 package Decls1 is
24922   task Lib_Task is
24923      entry Start;
24924   end Lib_Task;
24925 end Decls1;
24926
24927 with Utils;
24928 package body Decls1 is
24929   task body Lib_Task is
24930   begin
24931      accept Start;
24932      Utils.Put_Val (2);
24933   end Lib_Task;
24934 end Decls1;
24935
24936 package Decls2 is
24937   type My_Int is new Integer;
24938   function Ident (M : My_Int) return My_Int;
24939 end Decls2;
24940
24941 with Utils;
24942 package body Decls2 is
24943   function Ident (M : My_Int) return My_Int is
24944   begin
24945      return M;
24946   end Ident;
24947 end Decls2;
24948
24949 with Decls2;
24950 package Utils is
24951   procedure Put_Val (Arg : Decls2.My_Int);
24952 end Utils;
24953
24954 with Text_IO;
24955 package body Utils is
24956   procedure Put_Val (Arg : Decls2.My_Int) is
24957   begin
24958      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24959   end Put_Val;
24960 end Utils;
24961
24962 with Decls1;
24963 procedure Main is
24964 begin
24965    Decls1.Lib_Task.Start;
24966 end;
24967 @end smallexample
24968
24969 @noindent
24970 All we have done is to split @code{Decls} into two packages, one
24971 containing the library task, and one containing everything else. Now
24972 there is no cycle, and the program compiles, binds, links and executes
24973 using the default static model of elaboration.
24974
24975 @item
24976 Declare separate task types.
24977
24978 A significant part of the problem arises because of the use of the
24979 single task declaration form. This means that the elaboration of
24980 the task type, and the elaboration of the task itself (i.e. the
24981 creation of the task) happen at the same time. A good rule
24982 of style in Ada 95 is to always create explicit task types. By
24983 following the additional step of placing task objects in separate
24984 packages from the task type declaration, many elaboration problems
24985 are avoided. Here is another modified example of the example program:
24986
24987 @smallexample @c ada
24988 package Decls is
24989   task type Lib_Task_Type is
24990      entry Start;
24991   end Lib_Task_Type;
24992
24993   type My_Int is new Integer;
24994
24995   function Ident (M : My_Int) return My_Int;
24996 end Decls;
24997
24998 with Utils;
24999 package body Decls is
25000   task body Lib_Task_Type is
25001   begin
25002      accept Start;
25003      Utils.Put_Val (2);
25004   end Lib_Task_Type;
25005
25006   function Ident (M : My_Int) return My_Int is
25007   begin
25008      return M;
25009   end Ident;
25010 end Decls;
25011
25012 with Decls;
25013 package Utils is
25014   procedure Put_Val (Arg : Decls.My_Int);
25015 end Utils;
25016
25017 with Text_IO;
25018 package body Utils is
25019   procedure Put_Val (Arg : Decls.My_Int) is
25020   begin
25021      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25022   end Put_Val;
25023 end Utils;
25024
25025 with Decls;
25026 package Declst is
25027    Lib_Task : Decls.Lib_Task_Type;
25028 end Declst;
25029
25030 with Declst;
25031 procedure Main is
25032 begin
25033    Declst.Lib_Task.Start;
25034 end;
25035 @end smallexample
25036
25037 @noindent
25038 What we have done here is to replace the @code{task} declaration in
25039 package @code{Decls} with a @code{task type} declaration. Then we
25040 introduce a separate package @code{Declst} to contain the actual
25041 task object. This separates the elaboration issues for
25042 the @code{task type}
25043 declaration, which causes no trouble, from the elaboration issues
25044 of the task object, which is also unproblematic, since it is now independent
25045 of the elaboration of  @code{Utils}.
25046 This separation of concerns also corresponds to
25047 a generally sound engineering principle of separating declarations
25048 from instances. This version of the program also compiles, binds, links,
25049 and executes, generating the expected output.
25050
25051 @item
25052 Use No_Entry_Calls_In_Elaboration_Code restriction.
25053 @cindex No_Entry_Calls_In_Elaboration_Code
25054
25055 The previous two approaches described how a program can be restructured
25056 to avoid the special problems caused by library task bodies. in practice,
25057 however, such restructuring may be difficult to apply to existing legacy code,
25058 so we must consider solutions that do not require massive rewriting.
25059
25060 Let us consider more carefully why our original sample program works
25061 under the dynamic model of elaboration. The reason is that the code
25062 in the task body blocks immediately on the @code{accept}
25063 statement. Now of course there is nothing to prohibit elaboration
25064 code from making entry calls (for example from another library level task),
25065 so we cannot tell in isolation that
25066 the task will not execute the accept statement  during elaboration.
25067
25068 However, in practice it is very unusual to see elaboration code
25069 make any entry calls, and the pattern of tasks starting
25070 at elaboration time and then immediately blocking on @code{accept} or
25071 @code{select} statements is very common. What this means is that
25072 the compiler is being too pessimistic when it analyzes the
25073 whole package body as though it might be executed at elaboration
25074 time.
25075
25076 If we know that the elaboration code contains no entry calls, (a very safe
25077 assumption most of the time, that could almost be made the default
25078 behavior), then we can compile all units of the program under control
25079 of the following configuration pragma:
25080
25081 @smallexample
25082 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
25083 @end smallexample
25084
25085 @noindent
25086 This pragma can be placed in the @file{gnat.adc} file in the usual
25087 manner. If we take our original unmodified program and compile it
25088 in the presence of a @file{gnat.adc} containing the above pragma,
25089 then once again, we can compile, bind, link, and execute, obtaining
25090 the expected result. In the presence of this pragma, the compiler does
25091 not trace calls in a task body, that appear after the first @code{accept}
25092 or @code{select} statement, and therefore does not report a potential
25093 circularity in the original program.
25094
25095 The compiler will check to the extent it can that the above
25096 restriction is not violated, but it is not always possible to do a
25097 complete check at compile time, so it is important to use this
25098 pragma only if the stated restriction is in fact met, that is to say
25099 no task receives an entry call before elaboration of all units is completed.
25100
25101 @end itemize
25102
25103 @node Mixing Elaboration Models
25104 @section Mixing Elaboration Models
25105 @noindent
25106 So far, we have assumed that the entire program is either compiled
25107 using the dynamic model or static model, ensuring consistency. It
25108 is possible to mix the two models, but rules have to be followed
25109 if this mixing is done to ensure that elaboration checks are not
25110 omitted.
25111
25112 The basic rule is that @emph{a unit compiled with the static model cannot
25113 be @code{with'ed} by a unit compiled with the dynamic model}. The
25114 reason for this is that in the static model, a unit assumes that
25115 its clients guarantee to use (the equivalent of) pragma
25116 @code{Elaborate_All} so that no elaboration checks are required
25117 in inner subprograms, and this assumption is violated if the
25118 client is compiled with dynamic checks.
25119
25120 The precise rule is as follows. A unit that is compiled with dynamic
25121 checks can only @code{with} a unit that meets at least one of the
25122 following criteria:
25123
25124 @itemize @bullet
25125
25126 @item
25127 The @code{with'ed} unit is itself compiled with dynamic elaboration
25128 checks (that is with the @option{-gnatE} switch.
25129
25130 @item
25131 The @code{with'ed} unit is an internal GNAT implementation unit from
25132 the System, Interfaces, Ada, or GNAT hierarchies.
25133
25134 @item
25135 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
25136
25137 @item
25138 The @code{with'ing} unit (that is the client) has an explicit pragma
25139 @code{Elaborate_All} for the @code{with'ed} unit.
25140
25141 @end itemize
25142
25143 @noindent
25144 If this rule is violated, that is if a unit with dynamic elaboration
25145 checks @code{with's} a unit that does not meet one of the above four
25146 criteria, then the binder (@code{gnatbind}) will issue a warning
25147 similar to that in the following example:
25148
25149 @smallexample
25150 warning: "x.ads" has dynamic elaboration checks and with's
25151 warning:   "y.ads" which has static elaboration checks
25152 @end smallexample
25153
25154 @noindent
25155 These warnings indicate that the rule has been violated, and that as a result
25156 elaboration checks may be missed in the resulting executable file.
25157 This warning may be suppressed using the @option{-ws} binder switch
25158 in the usual manner.
25159
25160 One useful application of this mixing rule is in the case of a subsystem
25161 which does not itself @code{with} units from the remainder of the
25162 application. In this case, the entire subsystem can be compiled with
25163 dynamic checks to resolve a circularity in the subsystem, while
25164 allowing the main application that uses this subsystem to be compiled
25165 using the more reliable default static model.
25166
25167 @node What to Do If the Default Elaboration Behavior Fails
25168 @section What to Do If the Default Elaboration Behavior Fails
25169
25170 @noindent
25171 If the binder cannot find an acceptable order, it outputs detailed
25172 diagnostics. For example:
25173 @smallexample
25174 @group
25175 @iftex
25176 @leftskip=0cm
25177 @end iftex
25178 error: elaboration circularity detected
25179 info:   "proc (body)" must be elaborated before "pack (body)"
25180 info:     reason: Elaborate_All probably needed in unit "pack (body)"
25181 info:     recompile "pack (body)" with -gnatwl
25182 info:                             for full details
25183 info:       "proc (body)"
25184 info:         is needed by its spec:
25185 info:       "proc (spec)"
25186 info:         which is withed by:
25187 info:       "pack (body)"
25188 info:  "pack (body)" must be elaborated before "proc (body)"
25189 info:     reason: pragma Elaborate in unit "proc (body)"
25190 @end group
25191
25192 @end smallexample
25193
25194 @noindent
25195 In this case we have a cycle that the binder cannot break. On the one
25196 hand, there is an explicit pragma Elaborate in @code{proc} for
25197 @code{pack}. This means that the body of @code{pack} must be elaborated
25198 before the body of @code{proc}. On the other hand, there is elaboration
25199 code in @code{pack} that calls a subprogram in @code{proc}. This means
25200 that for maximum safety, there should really be a pragma
25201 Elaborate_All in @code{pack} for @code{proc} which would require that
25202 the body of @code{proc} be elaborated before the body of
25203 @code{pack}. Clearly both requirements cannot be satisfied.
25204 Faced with a circularity of this kind, you have three different options.
25205
25206 @table @asis
25207 @item Fix the program
25208 The most desirable option from the point of view of long-term maintenance
25209 is to rearrange the program so that the elaboration problems are avoided.
25210 One useful technique is to place the elaboration code into separate
25211 child packages. Another is to move some of the initialization code to
25212 explicitly called subprograms, where the program controls the order
25213 of initialization explicitly. Although this is the most desirable option,
25214 it may be impractical and involve too much modification, especially in
25215 the case of complex legacy code.
25216
25217 @item Perform dynamic checks
25218 If the compilations are done using the
25219 @option{-gnatE}
25220 (dynamic elaboration check) switch, then GNAT behaves in a quite different
25221 manner. Dynamic checks are generated for all calls that could possibly result
25222 in raising an exception. With this switch, the compiler does not generate
25223 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
25224 exactly as specified in the Ada 95 Reference Manual. The binder will generate
25225 an executable program that may or may not raise @code{Program_Error}, and then
25226 it is the programmer's job to ensure that it does not raise an exception. Note
25227 that it is important to compile all units with the switch, it cannot be used
25228 selectively.
25229
25230 @item Suppress checks
25231 The drawback of dynamic checks is that they generate a
25232 significant overhead at run time, both in space and time. If you
25233 are absolutely sure that your program cannot raise any elaboration
25234 exceptions, and you still want to use the dynamic elaboration model,
25235 then you can use the configuration pragma
25236 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25237 example this pragma could be placed in the @file{gnat.adc} file.
25238
25239 @item Suppress checks selectively
25240 When you know that certain calls or instantiations in elaboration code cannot
25241 possibly lead to an elaboration error, and the binder nevertheless complains
25242 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25243 elaboration circularities, it is possible to remove those warnings locally and
25244 obtain a program that will bind. Clearly this can be unsafe, and it is the
25245 responsibility of the programmer to make sure that the resulting program has no
25246 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25247 used with different granularity to suppress warnings and break elaboration
25248 circularities:
25249
25250 @itemize @bullet
25251 @item
25252 Place the pragma that names the called subprogram in the declarative part
25253 that contains the call.
25254
25255 @item
25256 Place the pragma in the declarative part, without naming an entity. This
25257 disables warnings on all calls in the corresponding  declarative region.
25258
25259 @item
25260 Place the pragma in the package spec that declares the called subprogram,
25261 and name the subprogram. This disables warnings on all elaboration calls to
25262 that subprogram.
25263
25264 @item
25265 Place the pragma in the package spec that declares the called subprogram,
25266 without naming any entity. This disables warnings on all elaboration calls to
25267 all subprograms declared in this spec.
25268
25269 @item Use Pragma Elaborate
25270 As previously described in section @xref{Treatment of Pragma Elaborate},
25271 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25272 that no elaboration checks are required on calls to the designated unit.
25273 There may be cases in which the caller knows that no transitive calls
25274 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25275 case where @code{pragma Elaborate_All} would cause a circularity.
25276 @end itemize
25277
25278 @noindent
25279 These five cases are listed in order of decreasing safety, and therefore
25280 require increasing programmer care in their application. Consider the
25281 following program:
25282
25283 @smallexample @c adanocomment
25284 package Pack1 is
25285   function F1 return Integer;
25286   X1 : Integer;
25287 end Pack1;
25288
25289 package Pack2 is
25290   function F2 return Integer;
25291   function Pure (x : integer) return integer;
25292   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
25293   --  pragma Suppress (Elaboration_Check);              -- (4)
25294 end Pack2;
25295
25296 with Pack2;
25297 package body Pack1 is
25298   function F1 return Integer is
25299   begin
25300     return 100;
25301   end F1;
25302   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
25303 begin
25304   declare
25305     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
25306     --  pragma Suppress(Elaboration_Check);             -- (2)
25307   begin
25308     X1 := Pack2.F2 + 1;                --  Elab. call (2)
25309   end;
25310 end Pack1;
25311
25312 with Pack1;
25313 package body Pack2 is
25314   function F2 return Integer is
25315   begin
25316      return Pack1.F1;
25317   end F2;
25318   function Pure (x : integer) return integer is
25319   begin
25320      return x ** 3 - 3 * x;
25321   end;
25322 end Pack2;
25323
25324 with Pack1, Ada.Text_IO;
25325 procedure Proc3 is
25326 begin
25327   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25328 end Proc3;
25329 @end smallexample
25330 In the absence of any pragmas, an attempt to bind this program produces
25331 the following diagnostics:
25332 @smallexample
25333 @group
25334 @iftex
25335 @leftskip=.5cm
25336 @end iftex
25337 error: elaboration circularity detected
25338 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
25339 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
25340 info:       recompile "pack1 (body)" with -gnatwl for full details
25341 info:          "pack1 (body)"
25342 info:             must be elaborated along with its spec:
25343 info:          "pack1 (spec)"
25344 info:             which is withed by:
25345 info:          "pack2 (body)"
25346 info:             which must be elaborated along with its spec:
25347 info:          "pack2 (spec)"
25348 info:             which is withed by:
25349 info:          "pack1 (body)"
25350 @end group
25351 @end smallexample
25352 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25353 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25354 F2 is safe, even though F2 calls F1, because the call appears after the
25355 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25356 remove the warning on the call. It is also possible to use pragma (2)
25357 because there are no other potentially unsafe calls in the block.
25358
25359 @noindent
25360 The call to @code{Pure} is safe because this function does not depend on the
25361 state of @code{Pack2}. Therefore any call to this function is safe, and it
25362 is correct to place pragma (3) in the corresponding package spec.
25363
25364 @noindent
25365 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25366 warnings on all calls to functions declared therein. Note that this is not
25367 necessarily safe, and requires more detailed examination of the subprogram
25368 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25369 be already elaborated.
25370 @end table
25371
25372 @noindent
25373 It is hard to generalize on which of these four approaches should be
25374 taken. Obviously if it is possible to fix the program so that the default
25375 treatment works, this is preferable, but this may not always be practical.
25376 It is certainly simple enough to use
25377 @option{-gnatE}
25378 but the danger in this case is that, even if the GNAT binder
25379 finds a correct elaboration order, it may not always do so,
25380 and certainly a binder from another Ada compiler might not. A
25381 combination of testing and analysis (for which the warnings generated
25382 with the
25383 @option{-gnatwl}
25384 switch can be useful) must be used to ensure that the program is free
25385 of errors. One switch that is useful in this testing is the
25386 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25387 switch for
25388 @code{gnatbind}.
25389 Normally the binder tries to find an order that has the best chance of
25390 of avoiding elaboration problems. With this switch, the binder
25391 plays a devil's advocate role, and tries to choose the order that
25392 has the best chance of failing. If your program works even with this
25393 switch, then it has a better chance of being error free, but this is still
25394 not a guarantee.
25395
25396 For an example of this approach in action, consider the C-tests (executable
25397 tests) from the ACVC suite. If these are compiled and run with the default
25398 treatment, then all but one of them succeed without generating any error
25399 diagnostics from the binder. However, there is one test that fails, and
25400 this is not surprising, because the whole point of this test is to ensure
25401 that the compiler can handle cases where it is impossible to determine
25402 a correct order statically, and it checks that an exception is indeed
25403 raised at run time.
25404
25405 This one test must be compiled and run using the
25406 @option{-gnatE}
25407 switch, and then it passes. Alternatively, the entire suite can
25408 be run using this switch. It is never wrong to run with the dynamic
25409 elaboration switch if your code is correct, and we assume that the
25410 C-tests are indeed correct (it is less efficient, but efficiency is
25411 not a factor in running the ACVC tests.)
25412
25413 @node Elaboration for Access-to-Subprogram Values
25414 @section Elaboration for Access-to-Subprogram Values
25415 @cindex Access-to-subprogram
25416
25417 @noindent
25418 The introduction of access-to-subprogram types in Ada 95 complicates
25419 the handling of elaboration. The trouble is that it becomes
25420 impossible to tell at compile time which procedure
25421 is being called. This means that it is not possible for the binder
25422 to analyze the elaboration requirements in this case.
25423
25424 If at the point at which the access value is created
25425 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
25426 the body of the subprogram is
25427 known to have been elaborated, then the access value is safe, and its use
25428 does not require a check. This may be achieved by appropriate arrangement
25429 of the order of declarations if the subprogram is in the current unit,
25430 or, if the subprogram is in another unit, by using pragma
25431 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
25432 on the referenced unit.
25433
25434 If the referenced body is not known to have been elaborated at the point
25435 the access value is created, then any use of the access value must do a
25436 dynamic check, and this dynamic check will fail and raise a
25437 @code{Program_Error} exception if the body has not been elaborated yet.
25438 GNAT will generate the necessary checks, and in addition, if the
25439 @option{-gnatwl}
25440 switch is set, will generate warnings that such checks are required.
25441
25442 The use of dynamic dispatching for tagged types similarly generates
25443 a requirement for dynamic checks, and premature calls to any primitive
25444 operation of a tagged type before the body of the operation has been
25445 elaborated, will result in the raising of @code{Program_Error}.
25446
25447 @node Summary of Procedures for Elaboration Control
25448 @section Summary of Procedures for Elaboration Control
25449 @cindex Elaboration control
25450
25451 @noindent
25452 First, compile your program with the default options, using none of
25453 the special elaboration control switches. If the binder successfully
25454 binds your program, then you can be confident that, apart from issues
25455 raised by the use of access-to-subprogram types and dynamic dispatching,
25456 the program is free of elaboration errors. If it is important that the
25457 program be portable, then use the
25458 @option{-gnatwl}
25459 switch to generate warnings about missing @code{Elaborate} or
25460 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25461
25462 If the program fails to bind using the default static elaboration
25463 handling, then you can fix the program to eliminate the binder
25464 message, or recompile the entire program with the
25465 @option{-gnatE} switch to generate dynamic elaboration checks,
25466 and, if you are sure there really are no elaboration problems,
25467 use a global pragma @code{Suppress (Elaboration_Check)}.
25468
25469 @node Other Elaboration Order Considerations
25470 @section Other Elaboration Order Considerations
25471 @noindent
25472 This section has been entirely concerned with the issue of finding a valid
25473 elaboration order, as defined by the Ada Reference Manual. In a case
25474 where several elaboration orders are valid, the task is to find one
25475 of the possible valid elaboration orders (and the static model in GNAT
25476 will ensure that this is achieved).
25477
25478 The purpose of the elaboration rules in the Ada Reference Manual is to
25479 make sure that no entity is accessed before it has been elaborated. For
25480 a subprogram, this means that the spec and body must have been elaborated
25481 before the subprogram is called. For an object, this means that the object
25482 must have been elaborated before its value is read or written. A violation
25483 of either of these two requirements is an access before elaboration order,
25484 and this section has been all about avoiding such errors.
25485
25486 In the case where more than one order of elaboration is possible, in the
25487 sense that access before elaboration errors are avoided, then any one of
25488 the orders is ``correct'' in the sense that it meets the requirements of
25489 the Ada Reference Manual, and no such error occurs.
25490
25491 However, it may be the case for a given program, that there are
25492 constraints on the order of elaboration that come not from consideration
25493 of avoiding elaboration errors, but rather from extra-lingual logic
25494 requirements. Consider this example:
25495
25496 @smallexample @c ada
25497 with Init_Constants;
25498 package Constants is
25499    X : Integer := 0;
25500    Y : Integer := 0;
25501 end Constants;
25502
25503 package Init_Constants is
25504    procedure P; -- require a body
25505 end Init_Constants;
25506
25507 with Constants;
25508 package body Init_Constants is
25509    procedure P is begin null; end;
25510 begin
25511    Constants.X := 3;
25512    Constants.Y := 4;
25513 end Init_Constants;
25514
25515 with Constants;
25516 package Calc is
25517    Z : Integer := Constants.X + Constants.Y;
25518 end Calc;
25519
25520 with Calc;
25521 with Text_IO; use Text_IO;
25522 procedure Main is
25523 begin
25524    Put_Line (Calc.Z'Img);
25525 end Main;
25526 @end smallexample
25527
25528 @noindent
25529 In this example, there is more than one valid order of elaboration. For
25530 example both the following are correct orders:
25531
25532 @smallexample
25533 Init_Constants spec
25534 Constants spec
25535 Calc spec
25536 Init_Constants body
25537 Main body
25538
25539   and
25540
25541 Init_Constants spec
25542 Init_Constants body
25543 Constants spec
25544 Calc spec
25545 Main body
25546 @end smallexample
25547
25548 @noindent
25549 There is no language rule to prefer one or the other, both are correct
25550 from an order of elaboration point of view. But the programmatic effects
25551 of the two orders are very different. In the first, the elaboration routine
25552 of @code{Calc} initializes @code{Z} to zero, and then the main program
25553 runs with this value of zero. But in the second order, the elaboration
25554 routine of @code{Calc} runs after the body of Init_Constants has set
25555 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25556 runs.
25557
25558 One could perhaps by applying pretty clever non-artificial intelligence
25559 to the situation guess that it is more likely that the second order of
25560 elaboration is the one desired, but there is no formal linguistic reason
25561 to prefer one over the other. In fact in this particular case, GNAT will
25562 prefer the second order, because of the rule that bodies are elaborated
25563 as soon as possible, but it's just luck that this is what was wanted
25564 (if indeed the second order was preferred).
25565
25566 If the program cares about the order of elaboration routines in a case like
25567 this, it is important to specify the order required. In this particular
25568 case, that could have been achieved by adding to the spec of Calc:
25569
25570 @smallexample @c ada
25571 pragma Elaborate_All (Constants);
25572 @end smallexample
25573
25574 @noindent
25575 which requires that the body (if any) and spec of @code{Constants},
25576 as well as the body and spec of any unit @code{with}'ed by
25577 @code{Constants} be elaborated before @code{Calc} is elaborated.
25578
25579 Clearly no automatic method can always guess which alternative you require,
25580 and if you are working with legacy code that had constraints of this kind
25581 which were not properly specified by adding @code{Elaborate} or
25582 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25583 compilers can choose different orders.
25584
25585 However, GNAT does attempt to diagnose the common situation where there
25586 are uninitialized variables in the visible part of a package spec, and the
25587 corresponding package body has an elaboration block that directly or
25588 indirectly initialized one or more of these variables. This is the situation
25589 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25590 a warning that suggests this addition if it detects this situation.
25591
25592 The @code{gnatbind}
25593 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25594 out problems. This switch causes bodies to be elaborated as late as possible
25595 instead of as early as possible. In the example above, it would have forced
25596 the choice of the first elaboration order. If you get different results
25597 when using this switch, and particularly if one set of results is right,
25598 and one is wrong as far as you are concerned, it shows that you have some
25599 missing @code{Elaborate} pragmas. For the example above, we have the
25600 following output:
25601
25602 @smallexample
25603 gnatmake -f -q main
25604 main
25605  7
25606 gnatmake -f -q main -bargs -p
25607 main
25608  0
25609 @end smallexample
25610
25611 @noindent
25612 It is of course quite unlikely that both these results are correct, so
25613 it is up to you in a case like this to investigate the source of the
25614 difference, by looking at the two elaboration orders that are chosen,
25615 and figuring out which is correct, and then adding the necessary
25616 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25617
25618 @node Inline Assembler
25619 @appendix Inline Assembler
25620
25621 @noindent
25622 If you need to write low-level software that interacts directly
25623 with the hardware, Ada provides two ways to incorporate assembly
25624 language code into your program.  First, you can import and invoke
25625 external routines written in assembly language, an Ada feature fully
25626 supported by GNAT.  However, for small sections of code it may be simpler
25627 or more efficient to include assembly language statements directly
25628 in your Ada source program, using the facilities of the implementation-defined
25629 package @code{System.Machine_Code}, which incorporates the gcc
25630 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25631 including the following:
25632
25633 @itemize @bullet
25634 @item No need to use non-Ada tools
25635 @item Consistent interface over different targets
25636 @item Automatic usage of the proper calling conventions
25637 @item Access to Ada constants and variables
25638 @item Definition of intrinsic routines
25639 @item Possibility of inlining a subprogram comprising assembler code
25640 @item Code optimizer can take Inline Assembler code into account
25641 @end itemize
25642
25643 This chapter presents a series of examples to show you how to use
25644 the Inline Assembler.  Although it focuses on the Intel x86,
25645 the general approach applies also to other processors.
25646 It is assumed that you are familiar with Ada
25647 and with assembly language programming.
25648
25649 @menu
25650 * Basic Assembler Syntax::
25651 * A Simple Example of Inline Assembler::
25652 * Output Variables in Inline Assembler::
25653 * Input Variables in Inline Assembler::
25654 * Inlining Inline Assembler Code::
25655 * Other Asm Functionality::
25656 @end menu
25657
25658 @c ---------------------------------------------------------------------------
25659 @node Basic Assembler Syntax
25660 @section Basic Assembler Syntax
25661
25662 @noindent
25663 The assembler used by GNAT and gcc is based not on the Intel assembly
25664 language, but rather on a language that descends from the AT&T Unix
25665 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25666 The following table summarizes the main features of @emph{as} syntax
25667 and points out the differences from the Intel conventions.
25668 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25669 pre-processor) documentation for further information.
25670
25671 @table @asis
25672 @item Register names
25673 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25674 @*
25675 Intel: No extra punctuation; for example @code{eax}
25676
25677 @item Immediate operand
25678 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25679 @*
25680 Intel: No extra punctuation; for example @code{4}
25681
25682 @item Address
25683 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25684 @*
25685 Intel: No extra punctuation; for example @code{loc}
25686
25687 @item Memory contents
25688 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25689 @*
25690 Intel: Square brackets; for example @code{[loc]}
25691
25692 @item Register contents
25693 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25694 @*
25695 Intel: Square brackets; for example @code{[eax]}
25696
25697 @item Hexadecimal numbers
25698 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25699 @*
25700 Intel: Trailing ``h''; for example @code{A0h}
25701
25702 @item Operand size
25703 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25704 a 16-bit word
25705 @*
25706 Intel: Implicit, deduced by assembler; for example @code{mov}
25707
25708 @item Instruction repetition
25709 gcc / @emph{as}: Split into two lines; for example
25710 @*
25711 @code{rep}
25712 @*
25713 @code{stosl}
25714 @*
25715 Intel: Keep on one line; for example @code{rep stosl}
25716
25717 @item Order of operands
25718 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25719 @*
25720 Intel: Destination first; for example @code{mov eax, 4}
25721 @end table
25722
25723 @c ---------------------------------------------------------------------------
25724 @node A Simple Example of Inline Assembler
25725 @section A Simple Example of Inline Assembler
25726
25727 @noindent
25728 The following example will generate a single assembly language statement,
25729 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25730 the example will be useful in illustrating the basics of
25731 the Inline Assembler facility.
25732
25733 @smallexample @c ada
25734 @group
25735 with System.Machine_Code; use System.Machine_Code;
25736 procedure Nothing is
25737 begin
25738    Asm ("nop");
25739 end Nothing;
25740 @end group
25741 @end smallexample
25742
25743 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25744 here it takes one parameter, a @emph{template string} that must be a static
25745 expression and that will form the generated instruction.
25746 @code{Asm} may be regarded as a compile-time procedure that parses
25747 the template string and additional parameters (none here),
25748 from which it generates a sequence of assembly language instructions.
25749
25750 The examples in this chapter will illustrate several of the forms
25751 for invoking @code{Asm}; a complete specification of the syntax
25752 is found in the @cite{GNAT Reference Manual}.
25753
25754 Under the standard GNAT conventions, the @code{Nothing} procedure
25755 should be in a file named @file{nothing.adb}.
25756 You can build the executable in the usual way:
25757 @smallexample
25758 gnatmake nothing
25759 @end smallexample
25760 However, the interesting aspect of this example is not its run-time behavior
25761 but rather the generated assembly code.
25762 To see this output, invoke the compiler as follows:
25763 @smallexample
25764    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25765 @end smallexample
25766 where the options are:
25767
25768 @table @code
25769 @item -c
25770 compile only (no bind or link)
25771 @item -S
25772 generate assembler listing
25773 @item -fomit-frame-pointer
25774 do not set up separate stack frames
25775 @item -gnatp
25776 do not add runtime checks
25777 @end table
25778
25779 This gives a human-readable assembler version of the code. The resulting
25780 file will have the same name as the Ada source file, but with a @code{.s}
25781 extension. In our example, the file @file{nothing.s} has the following
25782 contents:
25783
25784 @smallexample
25785 @group
25786 .file "nothing.adb"
25787 gcc2_compiled.:
25788 ___gnu_compiled_ada:
25789 .text
25790    .align 4
25791 .globl __ada_nothing
25792 __ada_nothing:
25793 #APP
25794    nop
25795 #NO_APP
25796    jmp L1
25797    .align 2,0x90
25798 L1:
25799    ret
25800 @end group
25801 @end smallexample
25802
25803 The assembly code you included is clearly indicated by
25804 the compiler, between the @code{#APP} and @code{#NO_APP}
25805 delimiters. The character before the 'APP' and 'NOAPP'
25806 can differ on different targets. For example, GNU/Linux uses '#APP' while
25807 on NT you will see '/APP'.
25808
25809 If you make a mistake in your assembler code (such as using the
25810 wrong size modifier, or using a wrong operand for the instruction) GNAT
25811 will report this error in a temporary file, which will be deleted when
25812 the compilation is finished.  Generating an assembler file will help
25813 in such cases, since you can assemble this file separately using the
25814 @emph{as} assembler that comes with gcc.
25815
25816 Assembling the file using the command
25817
25818 @smallexample
25819 as @file{nothing.s}
25820 @end smallexample
25821 @noindent
25822 will give you error messages whose lines correspond to the assembler
25823 input file, so you can easily find and correct any mistakes you made.
25824 If there are no errors, @emph{as} will generate an object file
25825 @file{nothing.out}.
25826
25827 @c ---------------------------------------------------------------------------
25828 @node Output Variables in Inline Assembler
25829 @section Output Variables in Inline Assembler
25830
25831 @noindent
25832 The examples in this section, showing how to access the processor flags,
25833 illustrate how to specify the destination operands for assembly language
25834 statements.
25835
25836 @smallexample @c ada
25837 @group
25838 with Interfaces; use Interfaces;
25839 with Ada.Text_IO; use Ada.Text_IO;
25840 with System.Machine_Code; use System.Machine_Code;
25841 procedure Get_Flags is
25842    Flags : Unsigned_32;
25843    use ASCII;
25844 begin
25845    Asm ("pushfl"          & LF & HT & -- push flags on stack
25846         "popl %%eax"      & LF & HT & -- load eax with flags
25847         "movl %%eax, %0",             -- store flags in variable
25848         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25849    Put_Line ("Flags register:" & Flags'Img);
25850 end Get_Flags;
25851 @end group
25852 @end smallexample
25853
25854 In order to have a nicely aligned assembly listing, we have separated
25855 multiple assembler statements in the Asm template string with linefeed
25856 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25857 The resulting section of the assembly output file is:
25858
25859 @smallexample
25860 @group
25861 #APP
25862    pushfl
25863    popl %eax
25864    movl %eax, -40(%ebp)
25865 #NO_APP
25866 @end group
25867 @end smallexample
25868
25869 It would have been legal to write the Asm invocation as:
25870
25871 @smallexample
25872 Asm ("pushfl popl %%eax movl %%eax, %0")
25873 @end smallexample
25874
25875 but in the generated assembler file, this would come out as:
25876
25877 @smallexample
25878 #APP
25879    pushfl popl %eax movl %eax, -40(%ebp)
25880 #NO_APP
25881 @end smallexample
25882
25883 which is not so convenient for the human reader.
25884
25885 We use Ada comments
25886 at the end of each line to explain what the assembler instructions
25887 actually do.  This is a useful convention.
25888
25889 When writing Inline Assembler instructions, you need to precede each register
25890 and variable name with a percent sign.  Since the assembler already requires
25891 a percent sign at the beginning of a register name, you need two consecutive
25892 percent signs for such names in the Asm template string, thus @code{%%eax}.
25893 In the generated assembly code, one of the percent signs will be stripped off.
25894
25895 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25896 variables: operands you later define using @code{Input} or @code{Output}
25897 parameters to @code{Asm}.
25898 An output variable is illustrated in
25899 the third statement in the Asm template string:
25900 @smallexample
25901 movl %%eax, %0
25902 @end smallexample
25903 The intent is to store the contents of the eax register in a variable that can
25904 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25905 necessarily work, since the compiler might optimize by using a register
25906 to hold Flags, and the expansion of the @code{movl} instruction would not be
25907 aware of this optimization.  The solution is not to store the result directly
25908 but rather to advise the compiler to choose the correct operand form;
25909 that is the purpose of the @code{%0} output variable.
25910
25911 Information about the output variable is supplied in the @code{Outputs}
25912 parameter to @code{Asm}:
25913 @smallexample
25914 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25915 @end smallexample
25916
25917 The output is defined by the @code{Asm_Output} attribute of the target type;
25918 the general format is
25919 @smallexample
25920 Type'Asm_Output (constraint_string, variable_name)
25921 @end smallexample
25922
25923 The constraint string directs the compiler how
25924 to store/access the associated variable.  In the example
25925 @smallexample
25926 Unsigned_32'Asm_Output ("=m", Flags);
25927 @end smallexample
25928 the @code{"m"} (memory) constraint tells the compiler that the variable
25929 @code{Flags} should be stored in a memory variable, thus preventing
25930 the optimizer from keeping it in a register.  In contrast,
25931 @smallexample
25932 Unsigned_32'Asm_Output ("=r", Flags);
25933 @end smallexample
25934 uses the @code{"r"} (register) constraint, telling the compiler to
25935 store the variable in a register.
25936
25937 If the constraint is preceded by the equal character (@strong{=}), it tells
25938 the compiler that the variable will be used to store data into it.
25939
25940 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25941 allowing the optimizer to choose whatever it deems best.
25942
25943 There are a fairly large number of constraints, but the ones that are
25944 most useful (for the Intel x86 processor) are the following:
25945
25946 @table @code
25947 @item =
25948 output constraint
25949 @item g
25950 global (i.e. can be stored anywhere)
25951 @item m
25952 in memory
25953 @item I
25954 a constant
25955 @item a
25956 use eax
25957 @item b
25958 use ebx
25959 @item c
25960 use ecx
25961 @item d
25962 use edx
25963 @item S
25964 use esi
25965 @item D
25966 use edi
25967 @item r
25968 use one of eax, ebx, ecx or edx
25969 @item q
25970 use one of eax, ebx, ecx, edx, esi or edi
25971 @end table
25972
25973 The full set of constraints is described in the gcc and @emph{as}
25974 documentation; note that it is possible to combine certain constraints
25975 in one constraint string.
25976
25977 You specify the association of an output variable with an assembler operand
25978 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25979 integer.  Thus in
25980 @smallexample @c ada
25981 @group
25982 Asm ("pushfl"          & LF & HT & -- push flags on stack
25983      "popl %%eax"      & LF & HT & -- load eax with flags
25984      "movl %%eax, %0",             -- store flags in variable
25985      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25986 @end group
25987 @end smallexample
25988 @noindent
25989 @code{%0} will be replaced in the expanded code by the appropriate operand,
25990 whatever
25991 the compiler decided for the @code{Flags} variable.
25992
25993 In general, you may have any number of output variables:
25994 @itemize @bullet
25995 @item
25996 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25997 @item
25998 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25999 of @code{Asm_Output} attributes
26000 @end itemize
26001
26002 For example:
26003 @smallexample @c ada
26004 @group
26005 Asm ("movl %%eax, %0" & LF & HT &
26006      "movl %%ebx, %1" & LF & HT &
26007      "movl %%ecx, %2",
26008      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
26009                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
26010                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
26011 @end group
26012 @end smallexample
26013 @noindent
26014 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26015 in the Ada program.
26016
26017 As a variation on the @code{Get_Flags} example, we can use the constraints
26018 string to direct the compiler to store the eax register into the @code{Flags}
26019 variable, instead of including the store instruction explicitly in the
26020 @code{Asm} template string:
26021
26022 @smallexample @c ada
26023 @group
26024 with Interfaces; use Interfaces;
26025 with Ada.Text_IO; use Ada.Text_IO;
26026 with System.Machine_Code; use System.Machine_Code;
26027 procedure Get_Flags_2 is
26028    Flags : Unsigned_32;
26029    use ASCII;
26030 begin
26031    Asm ("pushfl"      & LF & HT & -- push flags on stack
26032         "popl %%eax",             -- save flags in eax
26033         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26034    Put_Line ("Flags register:" & Flags'Img);
26035 end Get_Flags_2;
26036 @end group
26037 @end smallexample
26038
26039 @noindent
26040 The @code{"a"} constraint tells the compiler that the @code{Flags}
26041 variable will come from the eax register. Here is the resulting code:
26042
26043 @smallexample
26044 @group
26045 #APP
26046    pushfl
26047    popl %eax
26048 #NO_APP
26049    movl %eax,-40(%ebp)
26050 @end group
26051 @end smallexample
26052
26053 @noindent
26054 The compiler generated the store of eax into Flags after
26055 expanding the assembler code.
26056
26057 Actually, there was no need to pop the flags into the eax register;
26058 more simply, we could just pop the flags directly into the program variable:
26059
26060 @smallexample @c ada
26061 @group
26062 with Interfaces; use Interfaces;
26063 with Ada.Text_IO; use Ada.Text_IO;
26064 with System.Machine_Code; use System.Machine_Code;
26065 procedure Get_Flags_3 is
26066    Flags : Unsigned_32;
26067    use ASCII;
26068 begin
26069    Asm ("pushfl"  & LF & HT & -- push flags on stack
26070         "pop %0",             -- save flags in Flags
26071         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26072    Put_Line ("Flags register:" & Flags'Img);
26073 end Get_Flags_3;
26074 @end group
26075 @end smallexample
26076
26077 @c ---------------------------------------------------------------------------
26078 @node Input Variables in Inline Assembler
26079 @section Input Variables in Inline Assembler
26080
26081 @noindent
26082 The example in this section illustrates how to specify the source operands
26083 for assembly language statements.
26084 The program simply increments its input value by 1:
26085
26086 @smallexample @c ada
26087 @group
26088 with Interfaces; use Interfaces;
26089 with Ada.Text_IO; use Ada.Text_IO;
26090 with System.Machine_Code; use System.Machine_Code;
26091 procedure Increment is
26092
26093    function Incr (Value : Unsigned_32) return Unsigned_32 is
26094       Result : Unsigned_32;
26095    begin
26096       Asm ("incl %0",
26097            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26098            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26099       return Result;
26100    end Incr;
26101
26102    Value : Unsigned_32;
26103
26104 begin
26105    Value := 5;
26106    Put_Line ("Value before is" & Value'Img);
26107    Value := Incr (Value);
26108    Put_Line ("Value after is" & Value'Img);
26109 end Increment;
26110 @end group
26111 @end smallexample
26112
26113 The @code{Outputs} parameter to @code{Asm} specifies
26114 that the result will be in the eax register and that it is to be stored
26115 in the @code{Result} variable.
26116
26117 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26118 but with an @code{Asm_Input} attribute.
26119 The @code{"="} constraint, indicating an output value, is not present.
26120
26121 You can have multiple input variables, in the same way that you can have more
26122 than one output variable.
26123
26124 The parameter count (%0, %1) etc, now starts at the first input
26125 statement, and continues with the output statements.
26126 When both parameters use the same variable, the
26127 compiler will treat them as the same %n operand, which is the case here.
26128
26129 Just as the @code{Outputs} parameter causes the register to be stored into the
26130 target variable after execution of the assembler statements, so does the
26131 @code{Inputs} parameter cause its variable to be loaded into the register
26132 before execution of the assembler statements.
26133
26134 Thus the effect of the @code{Asm} invocation is:
26135 @enumerate
26136 @item load the 32-bit value of @code{Value} into eax
26137 @item execute the @code{incl %eax} instruction
26138 @item store the contents of eax into the @code{Result} variable
26139 @end enumerate
26140
26141 The resulting assembler file (with @option{-O2} optimization) contains:
26142 @smallexample
26143 @group
26144 _increment__incr.1:
26145    subl $4,%esp
26146    movl 8(%esp),%eax
26147 #APP
26148    incl %eax
26149 #NO_APP
26150    movl %eax,%edx
26151    movl %ecx,(%esp)
26152    addl $4,%esp
26153    ret
26154 @end group
26155 @end smallexample
26156
26157 @c ---------------------------------------------------------------------------
26158 @node Inlining Inline Assembler Code
26159 @section Inlining Inline Assembler Code
26160
26161 @noindent
26162 For a short subprogram such as the @code{Incr} function in the previous
26163 section, the overhead of the call and return (creating / deleting the stack
26164 frame) can be significant, compared to the amount of code in the subprogram
26165 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26166 which directs the compiler to expand invocations of the subprogram at the
26167 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26168 Here is the resulting program:
26169
26170 @smallexample @c ada
26171 @group
26172 with Interfaces; use Interfaces;
26173 with Ada.Text_IO; use Ada.Text_IO;
26174 with System.Machine_Code; use System.Machine_Code;
26175 procedure Increment_2 is
26176
26177    function Incr (Value : Unsigned_32) return Unsigned_32 is
26178       Result : Unsigned_32;
26179    begin
26180       Asm ("incl %0",
26181            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26182            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26183       return Result;
26184    end Incr;
26185    pragma Inline (Increment);
26186
26187    Value : Unsigned_32;
26188
26189 begin
26190    Value := 5;
26191    Put_Line ("Value before is" & Value'Img);
26192    Value := Increment (Value);
26193    Put_Line ("Value after is" & Value'Img);
26194 end Increment_2;
26195 @end group
26196 @end smallexample
26197
26198 Compile the program with both optimization (@option{-O2}) and inlining
26199 enabled (@option{-gnatpn} instead of @option{-gnatp}).
26200
26201 The @code{Incr} function is still compiled as usual, but at the
26202 point in @code{Increment} where our function used to be called:
26203
26204 @smallexample
26205 @group
26206 pushl %edi
26207 call _increment__incr.1
26208 @end group
26209 @end smallexample
26210
26211 @noindent
26212 the code for the function body directly appears:
26213
26214 @smallexample
26215 @group
26216 movl %esi,%eax
26217 #APP
26218    incl %eax
26219 #NO_APP
26220    movl %eax,%edx
26221 @end group
26222 @end smallexample
26223
26224 @noindent
26225 thus saving the overhead of stack frame setup and an out-of-line call.
26226
26227 @c ---------------------------------------------------------------------------
26228 @node Other Asm Functionality
26229 @section Other @code{Asm} Functionality
26230
26231 @noindent
26232 This section describes two important parameters to the @code{Asm}
26233 procedure: @code{Clobber}, which identifies register usage;
26234 and @code{Volatile}, which inhibits unwanted optimizations.
26235
26236 @menu
26237 * The Clobber Parameter::
26238 * The Volatile Parameter::
26239 @end menu
26240
26241 @c ---------------------------------------------------------------------------
26242 @node The Clobber Parameter
26243 @subsection The @code{Clobber} Parameter
26244
26245 @noindent
26246 One of the dangers of intermixing assembly language and a compiled language
26247 such as Ada is that the compiler needs to be aware of which registers are
26248 being used by the assembly code.  In some cases, such as the earlier examples,
26249 the constraint string is sufficient to indicate register usage (e.g.,
26250 @code{"a"} for
26251 the eax register).  But more generally, the compiler needs an explicit
26252 identification of the registers that are used by the Inline Assembly
26253 statements.
26254
26255 Using a register that the compiler doesn't know about
26256 could be a side effect of an instruction (like @code{mull}
26257 storing its result in both eax and edx).
26258 It can also arise from explicit register usage in your
26259 assembly code; for example:
26260 @smallexample
26261 @group
26262 Asm ("movl %0, %%ebx" & LF & HT &
26263      "movl %%ebx, %1",
26264      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26265      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
26266 @end group
26267 @end smallexample
26268 @noindent
26269 where the compiler (since it does not analyze the @code{Asm} template string)
26270 does not know you are using the ebx register.
26271
26272 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26273 to identify the registers that will be used by your assembly code:
26274
26275 @smallexample
26276 @group
26277 Asm ("movl %0, %%ebx" & LF & HT &
26278      "movl %%ebx, %1",
26279      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26280      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26281      Clobber => "ebx");
26282 @end group
26283 @end smallexample
26284
26285 The Clobber parameter is a static string expression specifying the
26286 register(s) you are using.  Note that register names are @emph{not} prefixed
26287 by a percent sign. Also, if more than one register is used then their names
26288 are separated by commas; e.g., @code{"eax, ebx"}
26289
26290 The @code{Clobber} parameter has several additional uses:
26291 @enumerate
26292 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26293 @item Use ``register'' name @code{memory} if you changed a memory location
26294 @end enumerate
26295
26296 @c ---------------------------------------------------------------------------
26297 @node The Volatile Parameter
26298 @subsection The @code{Volatile} Parameter
26299 @cindex Volatile parameter
26300
26301 @noindent
26302 Compiler optimizations in the presence of Inline Assembler may sometimes have
26303 unwanted effects.  For example, when an @code{Asm} invocation with an input
26304 variable is inside a loop, the compiler might move the loading of the input
26305 variable outside the loop, regarding it as a one-time initialization.
26306
26307 If this effect is not desired, you can disable such optimizations by setting
26308 the @code{Volatile} parameter to @code{True}; for example:
26309
26310 @smallexample @c ada
26311 @group
26312 Asm ("movl %0, %%ebx" & LF & HT &
26313      "movl %%ebx, %1",
26314      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26315      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26316      Clobber  => "ebx",
26317      Volatile => True);
26318 @end group
26319 @end smallexample
26320
26321 By default, @code{Volatile} is set to @code{False} unless there is no
26322 @code{Outputs} parameter.
26323
26324 Although setting @code{Volatile} to @code{True} prevents unwanted
26325 optimizations, it will also disable other optimizations that might be
26326 important for efficiency. In general, you should set @code{Volatile}
26327 to @code{True} only if the compiler's optimizations have created
26328 problems.
26329 @c END OF INLINE ASSEMBLER CHAPTER
26330 @c ===============================
26331
26332 @c ***********************************
26333 @c * Compatibility and Porting Guide *
26334 @c ***********************************
26335 @node Compatibility and Porting Guide
26336 @appendix Compatibility and Porting Guide
26337
26338 @noindent
26339 This chapter describes the compatibility issues that may arise between
26340 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
26341 can expedite porting
26342 applications developed in other Ada environments.
26343
26344 @menu
26345 * Compatibility with Ada 83::
26346 * Implementation-dependent characteristics::
26347 * Compatibility with Other Ada 95 Systems::
26348 * Representation Clauses::
26349 @ifclear vms
26350 @c Brief section is only in non-VMS version
26351 @c Full chapter is in VMS version
26352 * Compatibility with HP Ada 83::
26353 @end ifclear
26354 @ifset vms
26355 * Transitioning to 64-Bit GNAT for OpenVMS::
26356 @end ifset
26357 @end menu
26358
26359 @node Compatibility with Ada 83
26360 @section Compatibility with Ada 83
26361 @cindex Compatibility (between Ada 83 and Ada 95)
26362
26363 @noindent
26364 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
26365 particular, the design intention is that the difficulties associated
26366 with moving from Ada 83 to Ada 95 should be no greater than those
26367 that occur when moving from one Ada 83 system to another.
26368
26369 However, there are a number of points at which there are minor
26370 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26371 full details of these issues,
26372 and should be consulted for a complete treatment.
26373 In practice the
26374 following subsections treat the most likely issues to be encountered.
26375
26376 @menu
26377 * Legal Ada 83 programs that are illegal in Ada 95::
26378 * More deterministic semantics::
26379 * Changed semantics::
26380 * Other language compatibility issues::
26381 @end menu
26382
26383 @node Legal Ada 83 programs that are illegal in Ada 95
26384 @subsection Legal Ada 83 programs that are illegal in Ada 95
26385
26386 @table @asis
26387 @item Character literals
26388 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26389 @code{Wide_Character} as a new predefined character type, some uses of
26390 character literals that were legal in Ada 83 are illegal in Ada 95.
26391 For example:
26392 @smallexample @c ada
26393    for Char in 'A' .. 'Z' loop ... end loop;
26394 @end smallexample
26395 @noindent
26396 The problem is that @code{'A'} and @code{'Z'} could be from either
26397 @code{Character} or @code{Wide_Character}.  The simplest correction
26398 is to make the type explicit; e.g.:
26399 @smallexample @c ada
26400    for Char in Character range 'A' .. 'Z' loop ... end loop;
26401 @end smallexample
26402
26403 @item New reserved words
26404 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26405 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26406 Existing Ada 83 code using any of these identifiers must be edited to
26407 use some alternative name.
26408
26409 @item Freezing rules
26410 The rules in Ada 95 are slightly different with regard to the point at
26411 which entities are frozen, and representation pragmas and clauses are
26412 not permitted past the freeze point.  This shows up most typically in
26413 the form of an error message complaining that a representation item
26414 appears too late, and the appropriate corrective action is to move
26415 the item nearer to the declaration of the entity to which it refers.
26416
26417 A particular case is that representation pragmas
26418 @ifset vms
26419 (including the
26420 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26421 @end ifset
26422 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26423 declaration must be introduced to which the pragma can be applied.
26424
26425 @item Optional bodies for library packages
26426 In Ada 83, a package that did not require a package body was nevertheless
26427 allowed to have one.  This lead to certain surprises in compiling large
26428 systems (situations in which the body could be unexpectedly ignored by the
26429 binder).  In Ada 95, if a package does not require a body then it is not
26430 permitted to have a body.  To fix this problem, simply remove a redundant
26431 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26432 into the spec that makes the body required.  One approach is to add a private
26433 part to the package declaration (if necessary), and define a parameterless
26434 procedure called @code{Requires_Body}, which must then be given a dummy
26435 procedure body in the package body, which then becomes required.
26436 Another approach (assuming that this does not introduce elaboration
26437 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26438 since one effect of this pragma is to require the presence of a package body.
26439
26440 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26441 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26442 @code{Constraint_Error}.
26443 This means that it is illegal to have separate exception handlers for
26444 the two exceptions.  The fix is simply to remove the handler for the
26445 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26446 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26447
26448 @item Indefinite subtypes in generics
26449 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26450 as the actual for a generic formal private type, but then the instantiation
26451 would be illegal if there were any instances of declarations of variables
26452 of this type in the generic body.  In Ada 95, to avoid this clear violation
26453 of the methodological principle known as the ``contract model'',
26454 the generic declaration explicitly indicates whether
26455 or not such instantiations are permitted.  If a generic formal parameter
26456 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26457 type name, then it can be instantiated with indefinite types, but no
26458 stand-alone variables can be declared of this type.  Any attempt to declare
26459 such a variable will result in an illegality at the time the generic is
26460 declared.  If the @code{(<>)} notation is not used, then it is illegal
26461 to instantiate the generic with an indefinite type.
26462 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26463 It will show up as a compile time error, and
26464 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26465 @end table
26466
26467 @node More deterministic semantics
26468 @subsection More deterministic semantics
26469
26470 @table @asis
26471 @item Conversions
26472 Conversions from real types to integer types round away from 0.  In Ada 83
26473 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26474 implementation freedom was intended to support unbiased rounding in
26475 statistical applications, but in practice it interfered with portability.
26476 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26477 is required.  Numeric code may be affected by this change in semantics.
26478 Note, though, that this issue is no worse than already existed in Ada 83
26479 when porting code from one vendor to another.
26480
26481 @item Tasking
26482 The Real-Time Annex introduces a set of policies that define the behavior of
26483 features that were implementation dependent in Ada 83, such as the order in
26484 which open select branches are executed.
26485 @end table
26486
26487 @node Changed semantics
26488 @subsection Changed semantics
26489
26490 @noindent
26491 The worst kind of incompatibility is one where a program that is legal in
26492 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26493 possible in Ada 83.  Fortunately this is extremely rare, but the one
26494 situation that you should be alert to is the change in the predefined type
26495 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26496
26497 @table @asis
26498 @item range of @code{Character}
26499 The range of @code{Standard.Character} is now the full 256 characters
26500 of Latin-1, whereas in most Ada 83 implementations it was restricted
26501 to 128 characters. Although some of the effects of
26502 this change will be manifest in compile-time rejection of legal
26503 Ada 83 programs it is possible for a working Ada 83 program to have
26504 a different effect in Ada 95, one that was not permitted in Ada 83.
26505 As an example, the expression
26506 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26507 delivers @code{255} as its value.
26508 In general, you should look at the logic of any
26509 character-processing Ada 83 program and see whether it needs to be adapted
26510 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26511 character handling package that may be relevant if code needs to be adapted
26512 to account for the additional Latin-1 elements.
26513 The desirable fix is to
26514 modify the program to accommodate the full character set, but in some cases
26515 it may be convenient to define a subtype or derived type of Character that
26516 covers only the restricted range.
26517 @cindex Latin-1
26518 @end table
26519
26520 @node Other language compatibility issues
26521 @subsection Other language compatibility issues
26522 @table @asis
26523 @item @option{-gnat83 switch}
26524 All implementations of GNAT provide a switch that causes GNAT to operate
26525 in Ada 83 mode.  In this mode, some but not all compatibility problems
26526 of the type described above are handled automatically.  For example, the
26527 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
26528 However,
26529 in practice, it is usually advisable to make the necessary modifications
26530 to the program to remove the need for using this switch.
26531 See @ref{Compiling Different Versions of Ada}.
26532
26533 @item Support for removed Ada 83 pragmas and attributes
26534 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
26535 generally because they have been replaced by other mechanisms.  Ada 95
26536 compilers are allowed, but not required, to implement these missing
26537 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
26538 such pragmas and attributes, eliminating this compatibility concern.  These
26539 include @code{pragma Interface} and the floating point type attributes
26540 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26541 @end table
26542
26543 @node Implementation-dependent characteristics
26544 @section Implementation-dependent characteristics
26545 @noindent
26546 Although the Ada language defines the semantics of each construct as
26547 precisely as practical, in some situations (for example for reasons of
26548 efficiency, or where the effect is heavily dependent on the host or target
26549 platform) the implementation is allowed some freedom.  In porting Ada 83
26550 code to GNAT, you need to be aware of whether / how the existing code
26551 exercised such implementation dependencies.  Such characteristics fall into
26552 several categories, and GNAT offers specific support in assisting the
26553 transition from certain Ada 83 compilers.
26554
26555 @menu
26556 * Implementation-defined pragmas::
26557 * Implementation-defined attributes::
26558 * Libraries::
26559 * Elaboration order::
26560 * Target-specific aspects::
26561 @end menu
26562
26563 @node Implementation-defined pragmas
26564 @subsection Implementation-defined pragmas
26565
26566 @noindent
26567 Ada compilers are allowed to supplement the language-defined pragmas, and
26568 these are a potential source of non-portability.  All GNAT-defined pragmas
26569 are described in the GNAT Reference Manual, and these include several that
26570 are specifically intended to correspond to other vendors' Ada 83 pragmas.
26571 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26572 For
26573 compatibility with HP Ada 83, GNAT supplies the pragmas
26574 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26575 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26576 and @code{Volatile}.
26577 Other relevant pragmas include @code{External} and @code{Link_With}.
26578 Some vendor-specific
26579 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26580 recognized, thus
26581 avoiding compiler rejection of units that contain such pragmas; they are not
26582 relevant in a GNAT context and hence are not otherwise implemented.
26583
26584 @node Implementation-defined attributes
26585 @subsection Implementation-defined attributes
26586
26587 Analogous to pragmas, the set of attributes may be extended by an
26588 implementation.  All GNAT-defined attributes are described in the
26589 @cite{GNAT Reference Manual}, and these include several that are specifically
26590 intended
26591 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26592 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26593 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26594 @code{Type_Class}.
26595
26596 @node Libraries
26597 @subsection Libraries
26598 @noindent
26599 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26600 code uses vendor-specific libraries then there are several ways to manage
26601 this in Ada 95:
26602 @enumerate
26603 @item
26604 If the source code for the libraries (specifications and bodies) are
26605 available, then the libraries can be migrated in the same way as the
26606 application.
26607 @item
26608 If the source code for the specifications but not the bodies are
26609 available, then you can reimplement the bodies.
26610 @item
26611 Some new Ada 95 features obviate the need for library support.  For
26612 example most Ada 83 vendors supplied a package for unsigned integers.  The
26613 Ada 95 modular type feature is the preferred way to handle this need, so
26614 instead of migrating or reimplementing the unsigned integer package it may
26615 be preferable to retrofit the application using modular types.
26616 @end enumerate
26617
26618 @node Elaboration order
26619 @subsection Elaboration order
26620 @noindent
26621 The implementation can choose any elaboration order consistent with the unit
26622 dependency relationship.  This freedom means that some orders can result in
26623 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26624 to invoke a subprogram its body has been elaborated, or to instantiate a
26625 generic before the generic body has been elaborated.  By default GNAT
26626 attempts to choose a safe order (one that will not encounter access before
26627 elaboration problems) by implicitly inserting @code{Elaborate} or
26628 @code{Elaborate_All} pragmas where
26629 needed.  However, this can lead to the creation of elaboration circularities
26630 and a resulting rejection of the program by gnatbind.  This issue is
26631 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26632 In brief, there are several
26633 ways to deal with this situation:
26634
26635 @itemize @bullet
26636 @item
26637 Modify the program to eliminate the circularities, e.g. by moving
26638 elaboration-time code into explicitly-invoked procedures
26639 @item
26640 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26641 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26642 @code{Elaborate_All}
26643 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26644 (by selectively suppressing elaboration checks via pragma
26645 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26646 @end itemize
26647
26648 @node Target-specific aspects
26649 @subsection Target-specific aspects
26650 @noindent
26651 Low-level applications need to deal with machine addresses, data
26652 representations, interfacing with assembler code, and similar issues.  If
26653 such an Ada 83 application is being ported to different target hardware (for
26654 example where the byte endianness has changed) then you will need to
26655 carefully examine the program logic; the porting effort will heavily depend
26656 on the robustness of the original design.  Moreover, Ada 95 is sometimes
26657 incompatible with typical Ada 83 compiler practices regarding implicit
26658 packing, the meaning of the Size attribute, and the size of access values.
26659 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26660
26661 @node Compatibility with Other Ada 95 Systems
26662 @section Compatibility with Other Ada 95 Systems
26663
26664 @noindent
26665 Providing that programs avoid the use of implementation dependent and
26666 implementation defined features of Ada 95, as documented in the Ada 95
26667 reference manual, there should be a high degree of portability between
26668 GNAT and other Ada 95 systems.  The following are specific items which
26669 have proved troublesome in moving GNAT programs to other Ada 95
26670 compilers, but do not affect porting code to GNAT@.
26671
26672 @table @asis
26673 @item Ada 83 Pragmas and Attributes
26674 Ada 95 compilers are allowed, but not required, to implement the missing
26675 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26676 GNAT implements all such pragmas and attributes, eliminating this as
26677 a compatibility concern, but some other Ada 95 compilers reject these
26678 pragmas and attributes.
26679
26680 @item Special-needs Annexes
26681 GNAT implements the full set of special needs annexes.  At the
26682 current time, it is the only Ada 95 compiler to do so.  This means that
26683 programs making use of these features may not be portable to other Ada
26684 95 compilation systems.
26685
26686 @item Representation Clauses
26687 Some other Ada 95 compilers implement only the minimal set of
26688 representation clauses required by the Ada 95 reference manual.  GNAT goes
26689 far beyond this minimal set, as described in the next section.
26690 @end table
26691
26692 @node Representation Clauses
26693 @section Representation Clauses
26694
26695 @noindent
26696 The Ada 83 reference manual was quite vague in describing both the minimal
26697 required implementation of representation clauses, and also their precise
26698 effects.  The Ada 95 reference manual is much more explicit, but the minimal
26699 set of capabilities required in Ada 95 is quite limited.
26700
26701 GNAT implements the full required set of capabilities described in the
26702 Ada 95 reference manual, but also goes much beyond this, and in particular
26703 an effort has been made to be compatible with existing Ada 83 usage to the
26704 greatest extent possible.
26705
26706 A few cases exist in which Ada 83 compiler behavior is incompatible with
26707 requirements in the Ada 95 reference manual.  These are instances of
26708 intentional or accidental dependence on specific implementation dependent
26709 characteristics of these Ada 83 compilers.  The following is a list of
26710 the cases most likely to arise in existing legacy Ada 83 code.
26711
26712 @table @asis
26713 @item Implicit Packing
26714 Some Ada 83 compilers allowed a Size specification to cause implicit
26715 packing of an array or record.  This could cause expensive implicit
26716 conversions for change of representation in the presence of derived
26717 types, and the Ada design intends to avoid this possibility.
26718 Subsequent AI's were issued to make it clear that such implicit
26719 change of representation in response to a Size clause is inadvisable,
26720 and this recommendation is represented explicitly in the Ada 95 RM
26721 as implementation advice that is followed by GNAT@.
26722 The problem will show up as an error
26723 message rejecting the size clause.  The fix is simply to provide
26724 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26725 a Component_Size clause.
26726
26727 @item Meaning of Size Attribute
26728 The Size attribute in Ada 95 for discrete types is defined as being the
26729 minimal number of bits required to hold values of the type.  For example,
26730 on a 32-bit machine, the size of Natural will typically be 31 and not
26731 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26732 some 32 in this situation.  This problem will usually show up as a compile
26733 time error, but not always.  It is a good idea to check all uses of the
26734 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26735 Object_Size can provide a useful way of duplicating the behavior of
26736 some Ada 83 compiler systems.
26737
26738 @item Size of Access Types
26739 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26740 and that therefore it will be the same size as a System.Address value.  This
26741 assumption is true for GNAT in most cases with one exception.  For the case of
26742 a pointer to an unconstrained array type (where the bounds may vary from one
26743 value of the access type to another), the default is to use a ``fat pointer'',
26744 which is represented as two separate pointers, one to the bounds, and one to
26745 the array.  This representation has a number of advantages, including improved
26746 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26747 code which makes the assumption that, for example, pointers fit in 32 bits on
26748 a machine with 32-bit addressing.
26749
26750 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26751 access types in this case (where the designated type is an unconstrained array
26752 type).  These thin pointers are indeed the same size as a System.Address value.
26753 To specify a thin pointer, use a size clause for the type, for example:
26754
26755 @smallexample @c ada
26756 type X is access all String;
26757 for X'Size use Standard'Address_Size;
26758 @end smallexample
26759
26760 @noindent
26761 which will cause the type X to be represented using a single pointer.
26762 When using this representation, the bounds are right behind the array.
26763 This representation is slightly less efficient, and does not allow quite
26764 such flexibility in the use of foreign pointers or in using the
26765 Unrestricted_Access attribute to create pointers to non-aliased objects.
26766 But for any standard portable use of the access type it will work in
26767 a functionally correct manner and allow porting of existing code.
26768 Note that another way of forcing a thin pointer representation
26769 is to use a component size clause for the element size in an array,
26770 or a record representation clause for an access field in a record.
26771 @end table
26772
26773 @ifclear vms
26774 @c This brief section is only in the non-VMS version
26775 @c The complete chapter on HP Ada is in the VMS version
26776 @node Compatibility with HP Ada 83
26777 @section Compatibility with HP Ada 83
26778
26779 @noindent
26780 The VMS version of GNAT fully implements all the pragmas and attributes
26781 provided by HP Ada 83, as well as providing the standard HP Ada 83
26782 libraries, including Starlet.  In addition, data layouts and parameter
26783 passing conventions are highly compatible.  This means that porting
26784 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26785 most other porting efforts.  The following are some of the most
26786 significant differences between GNAT and HP Ada 83.
26787
26788 @table @asis
26789 @item Default floating-point representation
26790 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26791 it is VMS format.  GNAT does implement the necessary pragmas
26792 (Long_Float, Float_Representation) for changing this default.
26793
26794 @item System
26795 The package System in GNAT exactly corresponds to the definition in the
26796 Ada 95 reference manual, which means that it excludes many of the
26797 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26798 that contains the additional definitions, and a special pragma,
26799 Extend_System allows this package to be treated transparently as an
26800 extension of package System.
26801
26802 @item To_Address
26803 The definitions provided by Aux_DEC are exactly compatible with those
26804 in the HP Ada 83 version of System, with one exception.
26805 HP Ada provides the following declarations:
26806
26807 @smallexample @c ada
26808 TO_ADDRESS (INTEGER)
26809 TO_ADDRESS (UNSIGNED_LONGWORD)
26810 TO_ADDRESS (universal_integer)
26811 @end smallexample
26812
26813 @noindent
26814 The version of TO_ADDRESS taking a universal integer argument is in fact
26815 an extension to Ada 83 not strictly compatible with the reference manual.
26816 In GNAT, we are constrained to be exactly compatible with the standard,
26817 and this means we cannot provide this capability.  In HP Ada 83, the
26818 point of this definition is to deal with a call like:
26819
26820 @smallexample @c ada
26821 TO_ADDRESS (16#12777#);
26822 @end smallexample
26823
26824 @noindent
26825 Normally, according to the Ada 83 standard, one would expect this to be
26826 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26827 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26828 definition using universal_integer takes precedence.
26829
26830 In GNAT, since the version with universal_integer cannot be supplied, it is
26831 not possible to be 100% compatible.  Since there are many programs using
26832 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26833 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26834 declarations provided in the GNAT version of AUX_Dec are:
26835
26836 @smallexample @c ada
26837 function To_Address (X : Integer) return Address;
26838 pragma Pure_Function (To_Address);
26839
26840 function To_Address_Long (X : Unsigned_Longword)
26841  return Address;
26842 pragma Pure_Function (To_Address_Long);
26843 @end smallexample
26844
26845 @noindent
26846 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26847 change the name to TO_ADDRESS_LONG@.
26848
26849 @item Task_Id values
26850 The Task_Id values assigned will be different in the two systems, and GNAT
26851 does not provide a specified value for the Task_Id of the environment task,
26852 which in GNAT is treated like any other declared task.
26853 @end table
26854
26855 For full details on these and other less significant compatibility issues,
26856 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26857 Overview and Comparison on HP Platforms}.
26858
26859 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26860 attributes are recognized, although only a subset of them can sensibly
26861 be implemented.  The description of pragmas in the
26862 @cite{GNAT Reference Manual}
26863 indicates whether or not they are applicable to non-VMS systems.
26864 @end ifclear
26865
26866 @ifset vms
26867 @node Transitioning to 64-Bit GNAT for OpenVMS
26868 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26869
26870 @noindent
26871 This section is meant to assist users of pre-2006 @value{EDITION}
26872 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26873 the version of the GNAT technology supplied in 2006 and later for
26874 OpenVMS on both Alpha and I64.
26875
26876 @menu
26877 * Introduction to transitioning::
26878 * Migration of 32 bit code::
26879 * Taking advantage of 64 bit addressing::
26880 * Technical details::
26881 @end menu
26882
26883 @node Introduction to transitioning
26884 @subsection Introduction
26885
26886 @noindent
26887 64-bit @value{EDITION} for Open VMS has been designed to meet
26888 three main goals:
26889
26890 @enumerate
26891 @item
26892 Providing a full conforming implementation of the Ada 95 language
26893
26894 @item
26895 Allowing maximum backward compatibility, thus easing migration of existing
26896 Ada source code
26897
26898 @item
26899 Supplying a path for exploiting the full 64-bit address range
26900 @end enumerate
26901
26902 @noindent
26903 Ada's strong typing semantics has made it
26904 impractical to have different 32-bit and 64-bit modes. As soon as
26905 one object could possibly be outside the 32-bit address space, this
26906 would make it necessary for the @code{System.Address} type to be 64 bits.
26907 In particular, this would cause inconsistencies if 32-bit code is
26908 called from 64-bit code that raises an exception.
26909
26910 This issue has been resolved by always using 64-bit addressing
26911 at the system level, but allowing for automatic conversions between
26912 32-bit and 64-bit addresses where required. Thus users who
26913 do not currently require 64-bit addressing capabilities, can
26914 recompile their code with only minimal changes (and indeed
26915 if the code is written in portable Ada, with no assumptions about
26916 the size of the @code{Address} type, then no changes at all are necessary).
26917 At the same time,
26918 this approach provides a simple, gradual upgrade path to future
26919 use of larger memories than available for 32-bit systems.
26920 Also, newly written applications or libraries will by default
26921 be fully compatible with future systems exploiting 64-bit
26922 addressing capabilities.
26923
26924 @ref{Migration of 32 bit code}, will focus on porting applications
26925 that do not require more than 2 GB of
26926 addressable memory. This code will be referred to as
26927 @emph{32-bit code}.
26928 For applications intending to exploit the full 64-bit address space,
26929 @ref{Taking advantage of 64 bit addressing},
26930 will consider further changes that may be required.
26931 Such code will be referred to below as @emph{64-bit code}.
26932
26933 @node Migration of 32 bit code
26934 @subsection Migration of 32-bit code
26935
26936 @menu
26937 * Address types::
26938 * Access types::
26939 * Unchecked conversions::
26940 * Predefined constants::
26941 * Interfacing with C::
26942 * Experience with source compatibility::
26943 @end menu
26944
26945 @node Address types
26946 @subsubsection Address types
26947
26948 @noindent
26949 To solve the problem of mixing 64-bit and 32-bit addressing,
26950 while maintaining maximum backward compatibility, the following
26951 approach has been taken:
26952
26953 @itemize @bullet
26954 @item
26955 @code{System.Address} always has a size of 64 bits
26956
26957 @item
26958 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26959 @end itemize
26960
26961 @noindent
26962 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26963 a @code{Short_Address}
26964 may be used where an @code{Address} is required, and vice versa, without
26965 needing explicit type conversions.
26966 By virtue of the Open VMS parameter passing conventions,
26967 even imported
26968 and exported subprograms that have 32-bit address parameters are
26969 compatible with those that have 64-bit address parameters.
26970 (See @ref{Making code 64 bit clean} for details.)
26971
26972 The areas that may need attention are those where record types have
26973 been defined that contain components of the type @code{System.Address}, and
26974 where objects of this type are passed to code expecting a record layout with
26975 32-bit addresses.
26976
26977 Different compilers on different platforms cannot be
26978 expected to represent the same type in the same way,
26979 since alignment constraints
26980 and other system-dependent properties affect the compiler's decision.
26981 For that reason, Ada code
26982 generally uses representation clauses to specify the expected
26983 layout where required.
26984
26985 If such a representation clause uses 32 bits for a component having
26986 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26987 will detect that error and produce a specific diagnostic message.
26988 The developer should then determine whether the representation
26989 should be 64 bits or not and make either of two changes:
26990 change the size to 64 bits and leave the type as @code{System.Address}, or
26991 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26992 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26993 required in any code setting or accessing the field; the compiler will
26994 automatically perform any needed conversions between address
26995 formats.
26996
26997 @node Access types
26998 @subsubsection Access types
26999
27000 @noindent
27001 By default, objects designated by access values are always
27002 allocated in the 32-bit
27003 address space. Thus legacy code will never contain
27004 any objects that are not addressable with 32-bit addresses, and
27005 the compiler will never raise exceptions as result of mixing
27006 32-bit and 64-bit addresses.
27007
27008 However, the access values themselves are represented in 64 bits, for optimum
27009 performance and future compatibility with 64-bit code. As was
27010 the case with @code{System.Address}, the compiler will give an error message
27011 if an object or record component has a representation clause that
27012 requires the access value to fit in 32 bits. In such a situation,
27013 an explicit size clause for the access type, specifying 32 bits,
27014 will have the desired effect.
27015
27016 General access types (declared with @code{access all}) can never be
27017 32 bits, as values of such types must be able to refer to any object
27018 of the  designated type,
27019 including objects residing outside the 32-bit address range.
27020 Existing Ada 83 code will not contain such type definitions,
27021 however, since general access types were introduced in Ada 95.
27022
27023 @node Unchecked conversions
27024 @subsubsection Unchecked conversions
27025
27026 @noindent
27027 In the case of an @code{Unchecked_Conversion} where the source type is a
27028 64-bit access type or the type @code{System.Address}, and the target
27029 type is a 32-bit type, the compiler will generate a warning.
27030 Even though the generated code will still perform the required
27031 conversions, it is highly recommended in these cases to use
27032 respectively a 32-bit access type or @code{System.Short_Address}
27033 as the source type.
27034
27035 @node Predefined constants
27036 @subsubsection Predefined constants
27037
27038 @noindent
27039 The following table shows the correspondence between pre-2006 versions of
27040 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
27041 (``New''):
27042
27043 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
27044 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
27045 @item   @code{System.Word_Size}          @tab 32      @tab 64
27046 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
27047 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
27048 @item   @code{System.Address_Size}       @tab 32      @tab 64
27049 @end multitable
27050
27051 @noindent
27052 If you need to refer to the specific
27053 memory size of a 32-bit implementation, instead of the
27054 actual memory size, use @code{System.Short_Memory_Size}
27055 rather than @code{System.Memory_Size}.
27056 Similarly, references to @code{System.Address_Size} may need
27057 to be replaced by @code{System.Short_Address'Size}.
27058 The program @command{gnatfind} may be useful for locating
27059 references to the above constants, so that you can verify that they
27060 are still correct.
27061
27062 @node Interfacing with C
27063 @subsubsection Interfacing with C
27064
27065 @noindent
27066 In order to minimize the impact of the transition to 64-bit addresses on
27067 legacy programs, some fundamental types in the @code{Interfaces.C}
27068 package hierarchy continue to be represented in 32 bits.
27069 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
27070 This eases integration with the default HP C layout choices, for example
27071 as found in the system routines in @code{DECC$SHR.EXE}.
27072 Because of this implementation choice, the type fully compatible with
27073 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27074 Depending on the context the compiler will issue a
27075 warning or an error when type @code{Address} is used, alerting the user to a
27076 potential problem. Otherwise 32-bit programs that use
27077 @code{Interfaces.C} should normally not require code modifications
27078
27079 The other issue arising with C interfacing concerns pragma @code{Convention}.
27080 For VMS 64-bit systems, there is an issue of the appropriate default size
27081 of C convention pointers in the absence of an explicit size clause. The HP
27082 C compiler can choose either 32 or 64 bits depending on compiler options.
27083 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27084 clause is given. This proves a better choice for porting 32-bit legacy
27085 applications. In order to have a 64-bit representation, it is necessary to
27086 specify a size representation clause. For example:
27087
27088 @smallexample @c ada
27089 type int_star is access Interfaces.C.int;
27090 pragma Convention(C, int_star);
27091 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
27092 @end smallexample
27093
27094 @node Experience with source compatibility
27095 @subsubsection Experience with source compatibility
27096
27097 @noindent
27098 The Security Server and STARLET on I64 provide an interesting ``test case''
27099 for source compatibility issues, since it is in such system code
27100 where assumptions about @code{Address} size might be expected to occur.
27101 Indeed, there were a small number of occasions in the Security Server
27102 file @file{jibdef.ads}
27103 where a representation clause for a record type specified
27104 32 bits for a component of type @code{Address}.
27105 All of these errors were detected by the compiler.
27106 The repair was obvious and immediate; to simply replace @code{Address} by
27107 @code{Short_Address}.
27108
27109 In the case of STARLET, there were several record types that should
27110 have had representation clauses but did not.  In these record types
27111 there was an implicit assumption that an @code{Address} value occupied
27112 32 bits.
27113 These compiled without error, but their usage resulted in run-time error
27114 returns from STARLET system calls.
27115 Future GNAT technology enhancements may include a tool that detects and flags
27116 these sorts of potential source code porting problems.
27117
27118 @c ****************************************
27119 @node Taking advantage of 64 bit addressing
27120 @subsection Taking advantage of 64-bit addressing
27121
27122 @menu
27123 * Making code 64 bit clean::
27124 * Allocating memory from the 64 bit storage pool::
27125 * Restrictions on use of 64 bit objects::
27126 * Using 64 bit storage pools by default::
27127 * General access types::
27128 * STARLET and other predefined libraries::
27129 @end menu
27130
27131 @node Making code 64 bit clean
27132 @subsubsection Making code 64-bit clean
27133
27134 @noindent
27135 In order to prevent problems that may occur when (parts of) a
27136 system start using memory outside the 32-bit address range,
27137 we recommend some additional guidelines:
27138
27139 @itemize @bullet
27140 @item
27141 For imported subprograms that take parameters of the
27142 type @code{System.Address}, ensure that these subprograms can
27143 indeed handle 64-bit addresses. If not, or when in doubt,
27144 change the subprogram declaration to specify
27145 @code{System.Short_Address} instead.
27146
27147 @item
27148 Resolve all warnings related to size mismatches in
27149 unchecked conversions. Failing to do so causes
27150 erroneous execution if the source object is outside
27151 the 32-bit address space.
27152
27153 @item
27154 (optional) Explicitly use the 32-bit storage pool
27155 for access types used in a 32-bit context, or use
27156 generic access types where possible
27157 (@pxref{Restrictions on use of 64 bit objects}).
27158 @end itemize
27159
27160 @noindent
27161 If these rules are followed, the compiler will automatically insert
27162 any necessary checks to ensure that no addresses or access values
27163 passed to 32-bit code ever refer to objects outside the 32-bit
27164 address range.
27165 Any attempt to do this will raise @code{Constraint_Error}.
27166
27167 @node Allocating memory from the 64 bit storage pool
27168 @subsubsection Allocating memory from the 64-bit storage pool
27169
27170 @noindent
27171 For any access type @code{T} that potentially requires memory allocations
27172 beyond the 32-bit address space,
27173 use the following representation clause:
27174
27175 @smallexample @c ada
27176    for T'Storage_Pool use System.Pool_64;
27177 @end smallexample
27178
27179 @node Restrictions on use of 64 bit objects
27180 @subsubsection Restrictions on use of 64-bit objects
27181
27182 @noindent
27183 Taking the address of an object allocated from a 64-bit storage pool,
27184 and then passing this address to a subprogram expecting
27185 @code{System.Short_Address},
27186 or assigning it to a variable of type @code{Short_Address}, will cause
27187 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27188 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27189 no exception is raised and execution
27190 will become erroneous.
27191
27192 @node Using 64 bit storage pools by default
27193 @subsubsection Using 64-bit storage pools by default
27194
27195 @noindent
27196 In some cases it may be desirable to have the compiler allocate
27197 from 64-bit storage pools by default. This may be the case for
27198 libraries that are 64-bit clean, but may be used in both 32-bit
27199 and 64-bit contexts. For these cases the following configuration
27200 pragma may be specified:
27201
27202 @smallexample @c ada
27203   pragma Pool_64_Default;
27204 @end smallexample
27205
27206 @noindent
27207 Any code compiled in the context of this pragma will by default
27208 use the @code{System.Pool_64} storage pool. This default may be overridden
27209 for a specific access type @code{T} by the representation clause:
27210
27211 @smallexample @c ada
27212    for T'Storage_Pool use System.Pool_32;
27213 @end smallexample
27214
27215 @noindent
27216 Any object whose address may be passed to a subprogram with a
27217 @code{Short_Address} argument, or assigned to a variable of type
27218 @code{Short_Address}, needs to be allocated from this pool.
27219
27220 @node General access types
27221 @subsubsection General access types
27222
27223 @noindent
27224 Objects designated by access values from a
27225 general access type (declared with @code{access all}) are never allocated
27226 from a 64-bit storage pool. Code that uses general access types will
27227 accept objects allocated in either 32-bit or 64-bit address spaces,
27228 but never allocate objects outside the 32-bit address space.
27229 Using general access types ensures maximum compatibility with both
27230 32-bit and 64-bit code.
27231
27232 @node STARLET and other predefined libraries
27233 @subsubsection STARLET and other predefined libraries
27234
27235 @noindent
27236 All code that comes as part of GNAT is 64-bit clean, but the
27237 restrictions given in @ref{Restrictions on use of 64 bit objects},
27238 still apply. Look at the package
27239 specifications to see in which contexts objects allocated
27240 in 64-bit address space are acceptable.
27241
27242 @node Technical details
27243 @subsection Technical details
27244
27245 @noindent
27246 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27247 Ada standard with respect to the type of @code{System.Address}. Previous
27248 versions of GNAT Pro have defined this type as private and implemented it as a
27249 modular type.
27250
27251 In order to allow defining @code{System.Short_Address} as a proper subtype,
27252 and to match the implicit sign extension in parameter passing,
27253 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27254 visible (i.e., non-private) integer type.
27255 Standard operations on the type, such as the binary operators ``+'', ``-'',
27256 etc., that take @code{Address} operands and return an @code{Address} result,
27257 have been hidden by declaring these
27258 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
27259 that would otherwise result from overloading.
27260 (Note that, although @code{Address} is a visible integer type,
27261 good programming practice dictates against exploiting the type's
27262 integer properties such as literals, since this will compromise
27263 code portability.)
27264
27265 Defining @code{Address} as a visible integer type helps achieve
27266 maximum compatibility for existing Ada code,
27267 without sacrificing the capabilities of the 64-bit architecture.
27268 @end ifset
27269
27270 @c ************************************************
27271 @ifset unw
27272 @node Microsoft Windows Topics
27273 @appendix Microsoft Windows Topics
27274 @cindex Windows NT
27275 @cindex Windows 95
27276 @cindex Windows 98
27277
27278 @noindent
27279 This chapter describes topics that are specific to the Microsoft Windows
27280 platforms (NT, 2000, and XP Professional).
27281
27282 @menu
27283 * Using GNAT on Windows::
27284 * Using a network installation of GNAT::
27285 * CONSOLE and WINDOWS subsystems::
27286 * Temporary Files::
27287 * Mixed-Language Programming on Windows::
27288 * Windows Calling Conventions::
27289 * Introduction to Dynamic Link Libraries (DLLs)::
27290 * Using DLLs with GNAT::
27291 * Building DLLs with GNAT::
27292 * Building DLLs with GNAT Project files::
27293 * Building DLLs with gnatdll::
27294 * GNAT and Windows Resources::
27295 * Debugging a DLL::
27296 * Setting Stack Size from gnatlink::
27297 * Setting Heap Size from gnatlink::
27298 @end menu
27299
27300 @node Using GNAT on Windows
27301 @section Using GNAT on Windows
27302
27303 @noindent
27304 One of the strengths of the GNAT technology is that its tool set
27305 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27306 @code{gdb} debugger, etc.) is used in the same way regardless of the
27307 platform.
27308
27309 On Windows this tool set is complemented by a number of Microsoft-specific
27310 tools that have been provided to facilitate interoperability with Windows
27311 when this is required. With these tools:
27312
27313 @itemize @bullet
27314
27315 @item
27316 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27317 subsystems.
27318
27319 @item
27320 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27321 relocatable and non-relocatable DLLs are supported).
27322
27323 @item
27324 You can build Ada DLLs for use in other applications. These applications
27325 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27326 relocatable and non-relocatable Ada DLLs are supported.
27327
27328 @item
27329 You can include Windows resources in your Ada application.
27330
27331 @item
27332 You can use or create COM/DCOM objects.
27333 @end itemize
27334
27335 @noindent
27336 Immediately below are listed all known general GNAT-for-Windows restrictions.
27337 Other restrictions about specific features like Windows Resources and DLLs
27338 are listed in separate sections below.
27339
27340 @itemize @bullet
27341
27342 @item
27343 It is not possible to use @code{GetLastError} and @code{SetLastError}
27344 when tasking, protected records, or exceptions are used. In these
27345 cases, in order to implement Ada semantics, the GNAT run-time system
27346 calls certain Win32 routines that set the last error variable to 0 upon
27347 success. It should be possible to use @code{GetLastError} and
27348 @code{SetLastError} when tasking, protected record, and exception
27349 features are not used, but it is not guaranteed to work.
27350
27351 @item
27352 It is not possible to link against Microsoft libraries except for
27353 import libraries. The library must be built to be compatible with
27354 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
27355 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
27356 not be compatible with the GNAT runtime. Even if the library is
27357 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
27358
27359 @item
27360 When the compilation environment is located on FAT32 drives, users may
27361 experience recompilations of the source files that have not changed if
27362 Daylight Saving Time (DST) state has changed since the last time files
27363 were compiled. NTFS drives do not have this problem.
27364
27365 @item
27366 No components of the GNAT toolset use any entries in the Windows
27367 registry. The only entries that can be created are file associations and
27368 PATH settings, provided the user has chosen to create them at installation
27369 time, as well as some minimal book-keeping information needed to correctly
27370 uninstall or integrate different GNAT products.
27371 @end itemize
27372
27373 @node Using a network installation of GNAT
27374 @section Using a network installation of GNAT
27375
27376 @noindent
27377 Make sure the system on which GNAT is installed is accessible from the
27378 current machine, i.e. the install location is shared over the network.
27379 Shared resources are accessed on Windows by means of UNC paths, which
27380 have the format @code{\\server\sharename\path}
27381
27382 In order to use such a network installation, simply add the UNC path of the
27383 @file{bin} directory of your GNAT installation in front of your PATH. For
27384 example, if GNAT is installed in @file{\GNAT} directory of a share location
27385 called @file{c-drive} on a machine @file{LOKI}, the following command will
27386 make it available:
27387
27388 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27389
27390 Be aware that every compilation using the network installation results in the
27391 transfer of large amounts of data across the network and will likely cause
27392 serious performance penalty.
27393
27394 @node CONSOLE and WINDOWS subsystems
27395 @section CONSOLE and WINDOWS subsystems
27396 @cindex CONSOLE Subsystem
27397 @cindex WINDOWS Subsystem
27398 @cindex -mwindows
27399
27400 @noindent
27401 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27402 (which is the default subsystem) will always create a console when
27403 launching the application. This is not something desirable when the
27404 application has a Windows GUI. To get rid of this console the
27405 application must be using the @code{WINDOWS} subsystem. To do so
27406 the @option{-mwindows} linker option must be specified.
27407
27408 @smallexample
27409 $ gnatmake winprog -largs -mwindows
27410 @end smallexample
27411
27412 @node Temporary Files
27413 @section Temporary Files
27414 @cindex Temporary files
27415
27416 @noindent
27417 It is possible to control where temporary files gets created by setting
27418 the TMP environment variable. The file will be created:
27419
27420 @itemize
27421 @item Under the directory pointed to by the TMP environment variable if
27422 this directory exists.
27423
27424 @item Under c:\temp, if the TMP environment variable is not set (or not
27425 pointing to a directory) and if this directory exists.
27426
27427 @item Under the current working directory otherwise.
27428 @end itemize
27429
27430 @noindent
27431 This allows you to determine exactly where the temporary
27432 file will be created. This is particularly useful in networked
27433 environments where you may not have write access to some
27434 directories.
27435
27436 @node Mixed-Language Programming on Windows
27437 @section Mixed-Language Programming on Windows
27438
27439 @noindent
27440 Developing pure Ada applications on Windows is no different than on
27441 other GNAT-supported platforms. However, when developing or porting an
27442 application that contains a mix of Ada and C/C++, the choice of your
27443 Windows C/C++ development environment conditions your overall
27444 interoperability strategy.
27445
27446 If you use @command{gcc} to compile the non-Ada part of your application,
27447 there are no Windows-specific restrictions that affect the overall
27448 interoperability with your Ada code. If you plan to use
27449 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
27450 the following limitations:
27451
27452 @itemize @bullet
27453 @item
27454 You cannot link your Ada code with an object or library generated with
27455 Microsoft tools if these use the @code{.tls} section (Thread Local
27456 Storage section) since the GNAT linker does not yet support this section.
27457
27458 @item
27459 You cannot link your Ada code with an object or library generated with
27460 Microsoft tools if these use I/O routines other than those provided in
27461 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
27462 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
27463 libraries can cause a conflict with @code{msvcrt.dll} services. For
27464 instance Visual C++ I/O stream routines conflict with those in
27465 @code{msvcrt.dll}.
27466 @end itemize
27467
27468 @noindent
27469 If you do want to use the Microsoft tools for your non-Ada code and hit one
27470 of the above limitations, you have two choices:
27471
27472 @enumerate
27473 @item
27474 Encapsulate your non Ada code in a DLL to be linked with your Ada
27475 application. In this case, use the Microsoft or whatever environment to
27476 build the DLL and use GNAT to build your executable
27477 (@pxref{Using DLLs with GNAT}).
27478
27479 @item
27480 Or you can encapsulate your Ada code in a DLL to be linked with the
27481 other part of your application. In this case, use GNAT to build the DLL
27482 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
27483 environment to build your executable.
27484 @end enumerate
27485
27486 @node Windows Calling Conventions
27487 @section Windows Calling Conventions
27488 @findex Stdcall
27489 @findex APIENTRY
27490
27491 @menu
27492 * C Calling Convention::
27493 * Stdcall Calling Convention::
27494 * Win32 Calling Convention::
27495 * DLL Calling Convention::
27496 @end menu
27497
27498 @noindent
27499 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27500 (callee), there are several ways to push @code{G}'s parameters on the
27501 stack and there are several possible scenarios to clean up the stack
27502 upon @code{G}'s return. A calling convention is an agreed upon software
27503 protocol whereby the responsibilities between the caller (@code{F}) and
27504 the callee (@code{G}) are clearly defined. Several calling conventions
27505 are available for Windows:
27506
27507 @itemize @bullet
27508 @item
27509 @code{C} (Microsoft defined)
27510
27511 @item
27512 @code{Stdcall} (Microsoft defined)
27513
27514 @item
27515 @code{Win32} (GNAT specific)
27516
27517 @item
27518 @code{DLL} (GNAT specific)
27519 @end itemize
27520
27521 @node C Calling Convention
27522 @subsection @code{C} Calling Convention
27523
27524 @noindent
27525 This is the default calling convention used when interfacing to C/C++
27526 routines compiled with either @command{gcc} or Microsoft Visual C++.
27527
27528 In the @code{C} calling convention subprogram parameters are pushed on the
27529 stack by the caller from right to left. The caller itself is in charge of
27530 cleaning up the stack after the call. In addition, the name of a routine
27531 with @code{C} calling convention is mangled by adding a leading underscore.
27532
27533 The name to use on the Ada side when importing (or exporting) a routine
27534 with @code{C} calling convention is the name of the routine. For
27535 instance the C function:
27536
27537 @smallexample
27538 int get_val (long);
27539 @end smallexample
27540
27541 @noindent
27542 should be imported from Ada as follows:
27543
27544 @smallexample @c ada
27545 @group
27546 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27547 pragma Import (C, Get_Val, External_Name => "get_val");
27548 @end group
27549 @end smallexample
27550
27551 @noindent
27552 Note that in this particular case the @code{External_Name} parameter could
27553 have been omitted since, when missing, this parameter is taken to be the
27554 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27555 is missing, as in the above example, this parameter is set to be the
27556 @code{External_Name} with a leading underscore.
27557
27558 When importing a variable defined in C, you should always use the @code{C}
27559 calling convention unless the object containing the variable is part of a
27560 DLL (in which case you should use the @code{Stdcall} calling
27561 convention, @pxref{Stdcall Calling Convention}).
27562
27563 @node Stdcall Calling Convention
27564 @subsection @code{Stdcall} Calling Convention
27565
27566 @noindent
27567 This convention, which was the calling convention used for Pascal
27568 programs, is used by Microsoft for all the routines in the Win32 API for
27569 efficiency reasons. It must be used to import any routine for which this
27570 convention was specified.
27571
27572 In the @code{Stdcall} calling convention subprogram parameters are pushed
27573 on the stack by the caller from right to left. The callee (and not the
27574 caller) is in charge of cleaning the stack on routine exit. In addition,
27575 the name of a routine with @code{Stdcall} calling convention is mangled by
27576 adding a leading underscore (as for the @code{C} calling convention) and a
27577 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
27578 bytes) of the parameters passed to the routine.
27579
27580 The name to use on the Ada side when importing a C routine with a
27581 @code{Stdcall} calling convention is the name of the C routine. The leading
27582 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
27583 the compiler. For instance the Win32 function:
27584
27585 @smallexample
27586 @b{APIENTRY} int get_val (long);
27587 @end smallexample
27588
27589 @noindent
27590 should be imported from Ada as follows:
27591
27592 @smallexample @c ada
27593 @group
27594 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27595 pragma Import (Stdcall, Get_Val);
27596 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27597 @end group
27598 @end smallexample
27599
27600 @noindent
27601 As for the @code{C} calling convention, when the @code{External_Name}
27602 parameter is missing, it is taken to be the name of the Ada entity in lower
27603 case. If instead of writing the above import pragma you write:
27604
27605 @smallexample @c ada
27606 @group
27607 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27608 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27609 @end group
27610 @end smallexample
27611
27612 @noindent
27613 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27614 of specifying the @code{External_Name} parameter you specify the
27615 @code{Link_Name} as in the following example:
27616
27617 @smallexample @c ada
27618 @group
27619 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27620 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27621 @end group
27622 @end smallexample
27623
27624 @noindent
27625 then the imported routine is @code{retrieve_val@@4}, that is, there is no
27626 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
27627 added at the end of the @code{Link_Name} by the compiler.
27628
27629 @noindent
27630 Note, that in some special cases a DLL's entry point name lacks a trailing
27631 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
27632 The @code{gnatdll} tool, which creates the import library for the DLL, is able
27633 to handle those cases (@pxref{Using gnatdll} for the description of
27634 the switches).
27635
27636 @noindent
27637 It is also possible to import variables defined in a DLL by using an
27638 import pragma for a variable. As an example, if a DLL contains a
27639 variable defined as:
27640
27641 @smallexample
27642 int my_var;
27643 @end smallexample
27644
27645 @noindent
27646 then, to access this variable from Ada you should write:
27647
27648 @smallexample @c ada
27649 @group
27650 My_Var : Interfaces.C.int;
27651 pragma Import (Stdcall, My_Var);
27652 @end group
27653 @end smallexample
27654
27655 @noindent
27656 Note that to ease building cross-platform bindings this convention
27657 will be handled as a @code{C} calling convention on non Windows platforms.
27658
27659 @node Win32 Calling Convention
27660 @subsection @code{Win32} Calling Convention
27661
27662 @noindent
27663 This convention, which is GNAT-specific is fully equivalent to the
27664 @code{Stdcall} calling convention described above.
27665
27666 @node DLL Calling Convention
27667 @subsection @code{DLL} Calling Convention
27668
27669 @noindent
27670 This convention, which is GNAT-specific is fully equivalent to the
27671 @code{Stdcall} calling convention described above.
27672
27673 @node Introduction to Dynamic Link Libraries (DLLs)
27674 @section Introduction to Dynamic Link Libraries (DLLs)
27675 @findex DLL
27676
27677 @noindent
27678 A Dynamically Linked Library (DLL) is a library that can be shared by
27679 several applications running under Windows. A DLL can contain any number of
27680 routines and variables.
27681
27682 One advantage of DLLs is that you can change and enhance them without
27683 forcing all the applications that depend on them to be relinked or
27684 recompiled. However, you should be aware than all calls to DLL routines are
27685 slower since, as you will understand below, such calls are indirect.
27686
27687 To illustrate the remainder of this section, suppose that an application
27688 wants to use the services of a DLL @file{API.dll}. To use the services
27689 provided by @file{API.dll} you must statically link against the DLL or
27690 an import library which contains a jump table with an entry for each
27691 routine and variable exported by the DLL. In the Microsoft world this
27692 import library is called @file{API.lib}. When using GNAT this import
27693 library is called either @file{libAPI.a} or @file{libapi.a} (names are
27694 case insensitive).
27695
27696 After you have linked your application with the DLL or the import library
27697 and you run your application, here is what happens:
27698
27699 @enumerate
27700 @item
27701 Your application is loaded into memory.
27702
27703 @item
27704 The DLL @file{API.dll} is mapped into the address space of your
27705 application. This means that:
27706
27707 @itemize @bullet
27708 @item
27709 The DLL will use the stack of the calling thread.
27710
27711 @item
27712 The DLL will use the virtual address space of the calling process.
27713
27714 @item
27715 The DLL will allocate memory from the virtual address space of the calling
27716 process.
27717
27718 @item
27719 Handles (pointers) can be safely exchanged between routines in the DLL
27720 routines and routines in the application using the DLL.
27721 @end itemize
27722
27723 @item
27724 The entries in the jump table (from the import library @file{libAPI.a}
27725 or @file{API.lib} or automatically created when linking against a DLL)
27726 which is part of your application are initialized with the addresses
27727 of the routines and variables in @file{API.dll}.
27728
27729 @item
27730 If present in @file{API.dll}, routines @code{DllMain} or
27731 @code{DllMainCRTStartup} are invoked. These routines typically contain
27732 the initialization code needed for the well-being of the routines and
27733 variables exported by the DLL.
27734 @end enumerate
27735
27736 @noindent
27737 There is an additional point which is worth mentioning. In the Windows
27738 world there are two kind of DLLs: relocatable and non-relocatable
27739 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27740 in the target application address space. If the addresses of two
27741 non-relocatable DLLs overlap and these happen to be used by the same
27742 application, a conflict will occur and the application will run
27743 incorrectly. Hence, when possible, it is always preferable to use and
27744 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27745 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27746 User's Guide) removes the debugging symbols from the DLL but the DLL can
27747 still be relocated.
27748
27749 As a side note, an interesting difference between Microsoft DLLs and
27750 Unix shared libraries, is the fact that on most Unix systems all public
27751 routines are exported by default in a Unix shared library, while under
27752 Windows it is possible (but not required) to list exported routines in
27753 a definition file (@pxref{The Definition File}).
27754
27755 @node Using DLLs with GNAT
27756 @section Using DLLs with GNAT
27757
27758 @menu
27759 * Creating an Ada Spec for the DLL Services::
27760 * Creating an Import Library::
27761 @end menu
27762
27763 @noindent
27764 To use the services of a DLL, say @file{API.dll}, in your Ada application
27765 you must have:
27766
27767 @enumerate
27768 @item
27769 The Ada spec for the routines and/or variables you want to access in
27770 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27771 header files provided with the DLL.
27772
27773 @item
27774 The import library (@file{libAPI.a} or @file{API.lib}). As previously
27775 mentioned an import library is a statically linked library containing the
27776 import table which will be filled at load time to point to the actual
27777 @file{API.dll} routines. Sometimes you don't have an import library for the
27778 DLL you want to use. The following sections will explain how to build
27779 one. Note that this is optional.
27780
27781 @item
27782 The actual DLL, @file{API.dll}.
27783 @end enumerate
27784
27785 @noindent
27786 Once you have all the above, to compile an Ada application that uses the
27787 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27788 you simply issue the command
27789
27790 @smallexample
27791 $ gnatmake my_ada_app -largs -lAPI
27792 @end smallexample
27793
27794 @noindent
27795 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27796 tells the GNAT linker to look first for a library named @file{API.lib}
27797 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
27798 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27799 contains the following pragma
27800
27801 @smallexample @c ada
27802 pragma Linker_Options ("-lAPI");
27803 @end smallexample
27804
27805 @noindent
27806 you do not have to add @option{-largs -lAPI} at the end of the
27807 @command{gnatmake} command.
27808
27809 If any one of the items above is missing you will have to create it
27810 yourself. The following sections explain how to do so using as an
27811 example a fictitious DLL called @file{API.dll}.
27812
27813 @node Creating an Ada Spec for the DLL Services
27814 @subsection Creating an Ada Spec for the DLL Services
27815
27816 @noindent
27817 A DLL typically comes with a C/C++ header file which provides the
27818 definitions of the routines and variables exported by the DLL. The Ada
27819 equivalent of this header file is a package spec that contains definitions
27820 for the imported entities. If the DLL you intend to use does not come with
27821 an Ada spec you have to generate one such spec yourself. For example if
27822 the header file of @file{API.dll} is a file @file{api.h} containing the
27823 following two definitions:
27824
27825 @smallexample
27826 @group
27827 @cartouche
27828 int some_var;
27829 int get (char *);
27830 @end cartouche
27831 @end group
27832 @end smallexample
27833
27834 @noindent
27835 then the equivalent Ada spec could be:
27836
27837 @smallexample @c ada
27838 @group
27839 @cartouche
27840 with Interfaces.C.Strings;
27841 package API is
27842    use Interfaces;
27843
27844    Some_Var : C.int;
27845    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27846
27847 private
27848    pragma Import (C, Get);
27849    pragma Import (DLL, Some_Var);
27850 end API;
27851 @end cartouche
27852 @end group
27853 @end smallexample
27854
27855 @noindent
27856 Note that a variable is
27857 @strong{always imported with a Stdcall convention}. A function
27858 can have @code{C} or @code{Stdcall} convention.
27859 (@pxref{Windows Calling Conventions}).
27860
27861 @node Creating an Import Library
27862 @subsection Creating an Import Library
27863 @cindex Import library
27864
27865 @menu
27866 * The Definition File::
27867 * GNAT-Style Import Library::
27868 * Microsoft-Style Import Library::
27869 @end menu
27870
27871 @noindent
27872 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27873 import library @file{libAPI.a} is available with @file{API.dll} you
27874 can skip this section. You can also skip this section if
27875 @file{API.dll} is built with GNU tools as in this case it is possible
27876 to link directly against the DLL. Otherwise read on.
27877
27878 @node The Definition File
27879 @subsubsection The Definition File
27880 @cindex Definition file
27881 @findex .def
27882
27883 @noindent
27884 As previously mentioned, and unlike Unix systems, the list of symbols
27885 that are exported from a DLL must be provided explicitly in Windows.
27886 The main goal of a definition file is precisely that: list the symbols
27887 exported by a DLL. A definition file (usually a file with a @code{.def}
27888 suffix) has the following structure:
27889
27890 @smallexample
27891 @group
27892 @cartouche
27893 [LIBRARY @i{name}]
27894 [DESCRIPTION @i{string}]
27895 EXPORTS
27896    @i{symbol1}
27897    @i{symbol2}
27898    ...
27899 @end cartouche
27900 @end group
27901 @end smallexample
27902
27903 @table @code
27904 @item LIBRARY @i{name}
27905 This section, which is optional, gives the name of the DLL.
27906
27907 @item DESCRIPTION @i{string}
27908 This section, which is optional, gives a description string that will be
27909 embedded in the import library.
27910
27911 @item EXPORTS
27912 This section gives the list of exported symbols (procedures, functions or
27913 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27914 section of @file{API.def} looks like:
27915
27916 @smallexample
27917 @group
27918 @cartouche
27919 EXPORTS
27920    some_var
27921    get
27922 @end cartouche
27923 @end group
27924 @end smallexample
27925 @end table
27926
27927 @noindent
27928 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
27929 (@pxref{Windows Calling Conventions}) for a Stdcall
27930 calling convention function in the exported symbols list.
27931
27932 @noindent
27933 There can actually be other sections in a definition file, but these
27934 sections are not relevant to the discussion at hand.
27935
27936 @node GNAT-Style Import Library
27937 @subsubsection GNAT-Style Import Library
27938
27939 @noindent
27940 To create a static import library from @file{API.dll} with the GNAT tools
27941 you should proceed as follows:
27942
27943 @enumerate
27944 @item
27945 Create the definition file @file{API.def} (@pxref{The Definition File}).
27946 For that use the @code{dll2def} tool as follows:
27947
27948 @smallexample
27949 $ dll2def API.dll > API.def
27950 @end smallexample
27951
27952 @noindent
27953 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27954 to standard output the list of entry points in the DLL. Note that if
27955 some routines in the DLL have the @code{Stdcall} convention
27956 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27957 suffix then you'll have to edit @file{api.def} to add it, and specify
27958 @code{-k} to @code{gnatdll} when creating the import library.
27959
27960 @noindent
27961 Here are some hints to find the right @code{@@}@i{nn} suffix.
27962
27963 @enumerate
27964 @item
27965 If you have the Microsoft import library (.lib), it is possible to get
27966 the right symbols by using Microsoft @code{dumpbin} tool (see the
27967 corresponding Microsoft documentation for further details).
27968
27969 @smallexample
27970 $ dumpbin /exports api.lib
27971 @end smallexample
27972
27973 @item
27974 If you have a message about a missing symbol at link time the compiler
27975 tells you what symbol is expected. You just have to go back to the
27976 definition file and add the right suffix.
27977 @end enumerate
27978
27979 @item
27980 Build the import library @code{libAPI.a}, using @code{gnatdll}
27981 (@pxref{Using gnatdll}) as follows:
27982
27983 @smallexample
27984 $ gnatdll -e API.def -d API.dll
27985 @end smallexample
27986
27987 @noindent
27988 @code{gnatdll} takes as input a definition file @file{API.def} and the
27989 name of the DLL containing the services listed in the definition file
27990 @file{API.dll}. The name of the static import library generated is
27991 computed from the name of the definition file as follows: if the
27992 definition file name is @i{xyz}@code{.def}, the import library name will
27993 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27994 @option{-e} could have been removed because the name of the definition
27995 file (before the ``@code{.def}'' suffix) is the same as the name of the
27996 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27997 @end enumerate
27998
27999 @node Microsoft-Style Import Library
28000 @subsubsection Microsoft-Style Import Library
28001
28002 @noindent
28003 With GNAT you can either use a GNAT-style or Microsoft-style import
28004 library. A Microsoft import library is needed only if you plan to make an
28005 Ada DLL available to applications developed with Microsoft
28006 tools (@pxref{Mixed-Language Programming on Windows}).
28007
28008 To create a Microsoft-style import library for @file{API.dll} you
28009 should proceed as follows:
28010
28011 @enumerate
28012 @item
28013 Create the definition file @file{API.def} from the DLL. For this use either
28014 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28015 tool (see the corresponding Microsoft documentation for further details).
28016
28017 @item
28018 Build the actual import library using Microsoft's @code{lib} utility:
28019
28020 @smallexample
28021 $ lib -machine:IX86 -def:API.def -out:API.lib
28022 @end smallexample
28023
28024 @noindent
28025 If you use the above command the definition file @file{API.def} must
28026 contain a line giving the name of the DLL:
28027
28028 @smallexample
28029 LIBRARY      "API"
28030 @end smallexample
28031
28032 @noindent
28033 See the Microsoft documentation for further details about the usage of
28034 @code{lib}.
28035 @end enumerate
28036
28037 @node Building DLLs with GNAT
28038 @section Building DLLs with GNAT
28039 @cindex DLLs, building
28040
28041 @noindent
28042 This section explain how to build DLLs using the GNAT built-in DLL
28043 support. With the following procedure it is straight forward to build
28044 and use DLLs with GNAT.
28045
28046 @enumerate
28047
28048 @item building object files
28049
28050 The first step is to build all objects files that are to be included
28051 into the DLL. This is done by using the standard @command{gnatmake} tool.
28052
28053 @item building the DLL
28054
28055 To build the DLL you must use @command{gcc}'s @code{-shared}
28056 option. It is quite simple to use this method:
28057
28058 @smallexample
28059 $ gcc -shared -o api.dll obj1.o obj2.o ...
28060 @end smallexample
28061
28062 It is important to note that in this case all symbols found in the
28063 object files are automatically exported. It is possible to restrict
28064 the set of symbols to export by passing to @command{gcc} a definition
28065 file, @pxref{The Definition File}. For example:
28066
28067 @smallexample
28068 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
28069 @end smallexample
28070
28071 If you use a definition file you must export the elaboration procedures
28072 for every package that required one. Elaboration procedures are named
28073 using the package name followed by "_E".
28074
28075 @item preparing DLL to be used
28076
28077 For the DLL to be used by client programs the bodies must be hidden
28078 from it and the .ali set with read-only attribute. This is very important
28079 otherwise GNAT will recompile all packages and will not actually use
28080 the code in the DLL. For example:
28081
28082 @smallexample
28083 $ mkdir apilib
28084 $ copy *.ads *.ali api.dll apilib
28085 $ attrib +R apilib\*.ali
28086 @end smallexample
28087
28088 @end enumerate
28089
28090 At this point it is possible to use the DLL by directly linking
28091 against it. Note that you must use the GNAT shared runtime when using
28092 GNAT shared libraries. This is achieved by using @code{-shared} binder's
28093 option.
28094
28095 @smallexample
28096 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28097 @end smallexample
28098
28099 @node Building DLLs with GNAT Project files
28100 @section Building DLLs with GNAT Project files
28101 @cindex DLLs, building
28102
28103 @noindent
28104 There is nothing specific to Windows in this area. @pxref{Library Projects}.
28105
28106 @node Building DLLs with gnatdll
28107 @section Building DLLs with gnatdll
28108 @cindex DLLs, building
28109
28110 @menu
28111 * Limitations When Using Ada DLLs from Ada::
28112 * Exporting Ada Entities::
28113 * Ada DLLs and Elaboration::
28114 * Ada DLLs and Finalization::
28115 * Creating a Spec for Ada DLLs::
28116 * Creating the Definition File::
28117 * Using gnatdll::
28118 @end menu
28119
28120 @noindent
28121 Note that it is preferred to use the built-in GNAT DLL support
28122 (@pxref{Building DLLs with GNAT}) or GNAT Project files
28123 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
28124
28125 This section explains how to build DLLs containing Ada code using
28126 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28127 remainder of this section.
28128
28129 The steps required to build an Ada DLL that is to be used by Ada as well as
28130 non-Ada applications are as follows:
28131
28132 @enumerate
28133 @item
28134 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28135 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28136 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28137 skip this step if you plan to use the Ada DLL only from Ada applications.
28138
28139 @item
28140 Your Ada code must export an initialization routine which calls the routine
28141 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28142 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28143 routine exported by the Ada DLL must be invoked by the clients of the DLL
28144 to initialize the DLL.
28145
28146 @item
28147 When useful, the DLL should also export a finalization routine which calls
28148 routine @code{adafinal} generated by @command{gnatbind} to perform the
28149 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28150 The finalization routine exported by the Ada DLL must be invoked by the
28151 clients of the DLL when the DLL services are no further needed.
28152
28153 @item
28154 You must provide a spec for the services exported by the Ada DLL in each
28155 of the programming languages to which you plan to make the DLL available.
28156
28157 @item
28158 You must provide a definition file listing the exported entities
28159 (@pxref{The Definition File}).
28160
28161 @item
28162 Finally you must use @code{gnatdll} to produce the DLL and the import
28163 library (@pxref{Using gnatdll}).
28164 @end enumerate
28165
28166 @noindent
28167 Note that a relocatable DLL stripped using the @code{strip}
28168 binutils tool will not be relocatable anymore. To build a DLL without
28169 debug information pass @code{-largs -s} to @code{gnatdll}. This
28170 restriction does not apply to a DLL built using a Library Project.
28171 @pxref{Library Projects}.
28172
28173 @node Limitations When Using Ada DLLs from Ada
28174 @subsection Limitations When Using Ada DLLs from Ada
28175
28176 @noindent
28177 When using Ada DLLs from Ada applications there is a limitation users
28178 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28179 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28180 each Ada DLL includes the services of the GNAT run time that are necessary
28181 to the Ada code inside the DLL. As a result, when an Ada program uses an
28182 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28183 one in the main program.
28184
28185 It is therefore not possible to exchange GNAT run-time objects between the
28186 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28187 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
28188 types, etc.
28189
28190 It is completely safe to exchange plain elementary, array or record types,
28191 Windows object handles, etc.
28192
28193 @node Exporting Ada Entities
28194 @subsection Exporting Ada Entities
28195 @cindex Export table
28196
28197 @noindent
28198 Building a DLL is a way to encapsulate a set of services usable from any
28199 application. As a result, the Ada entities exported by a DLL should be
28200 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28201 any Ada name mangling. As an example here is an Ada package
28202 @code{API}, spec and body, exporting two procedures, a function, and a
28203 variable:
28204
28205 @smallexample @c ada
28206 @group
28207 @cartouche
28208 with Interfaces.C; use Interfaces;
28209 package API is
28210    Count : C.int := 0;
28211    function Factorial (Val : C.int) return C.int;
28212
28213    procedure Initialize_API;
28214    procedure Finalize_API;
28215    --  Initialization & Finalization routines. More in the next section.
28216 private
28217    pragma Export (C, Initialize_API);
28218    pragma Export (C, Finalize_API);
28219    pragma Export (C, Count);
28220    pragma Export (C, Factorial);
28221 end API;
28222 @end cartouche
28223 @end group
28224 @end smallexample
28225
28226 @smallexample @c ada
28227 @group
28228 @cartouche
28229 package body API is
28230    function Factorial (Val : C.int) return C.int is
28231       Fact : C.int := 1;
28232    begin
28233       Count := Count + 1;
28234       for K in 1 .. Val loop
28235          Fact := Fact * K;
28236       end loop;
28237       return Fact;
28238    end Factorial;
28239
28240    procedure Initialize_API is
28241       procedure Adainit;
28242       pragma Import (C, Adainit);
28243    begin
28244       Adainit;
28245    end Initialize_API;
28246
28247    procedure Finalize_API is
28248       procedure Adafinal;
28249       pragma Import (C, Adafinal);
28250    begin
28251       Adafinal;
28252    end Finalize_API;
28253 end API;
28254 @end cartouche
28255 @end group
28256 @end smallexample
28257
28258 @noindent
28259 If the Ada DLL you are building will only be used by Ada applications
28260 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28261 convention. As an example, the previous package could be written as
28262 follows:
28263
28264 @smallexample @c ada
28265 @group
28266 @cartouche
28267 package API is
28268    Count : Integer := 0;
28269    function Factorial (Val : Integer) return Integer;
28270
28271    procedure Initialize_API;
28272    procedure Finalize_API;
28273    --  Initialization and Finalization routines.
28274 end API;
28275 @end cartouche
28276 @end group
28277 @end smallexample
28278
28279 @smallexample @c ada
28280 @group
28281 @cartouche
28282 package body API is
28283    function Factorial (Val : Integer) return Integer is
28284       Fact : Integer := 1;
28285    begin
28286       Count := Count + 1;
28287       for K in 1 .. Val loop
28288          Fact := Fact * K;
28289       end loop;
28290       return Fact;
28291    end Factorial;
28292
28293    ...
28294    --  The remainder of this package body is unchanged.
28295 end API;
28296 @end cartouche
28297 @end group
28298 @end smallexample
28299
28300 @noindent
28301 Note that if you do not export the Ada entities with a @code{C} or
28302 @code{Stdcall} convention you will have to provide the mangled Ada names
28303 in the definition file of the Ada DLL
28304 (@pxref{Creating the Definition File}).
28305
28306 @node Ada DLLs and Elaboration
28307 @subsection Ada DLLs and Elaboration
28308 @cindex DLLs and elaboration
28309
28310 @noindent
28311 The DLL that you are building contains your Ada code as well as all the
28312 routines in the Ada library that are needed by it. The first thing a
28313 user of your DLL must do is elaborate the Ada code
28314 (@pxref{Elaboration Order Handling in GNAT}).
28315
28316 To achieve this you must export an initialization routine
28317 (@code{Initialize_API} in the previous example), which must be invoked
28318 before using any of the DLL services. This elaboration routine must call
28319 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28320 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28321 @code{Initialize_Api} for an example. Note that the GNAT binder is
28322 automatically invoked during the DLL build process by the @code{gnatdll}
28323 tool (@pxref{Using gnatdll}).
28324
28325 When a DLL is loaded, Windows systematically invokes a routine called
28326 @code{DllMain}. It would therefore be possible to call @code{adainit}
28327 directly from @code{DllMain} without having to provide an explicit
28328 initialization routine. Unfortunately, it is not possible to call
28329 @code{adainit} from the @code{DllMain} if your program has library level
28330 tasks because access to the @code{DllMain} entry point is serialized by
28331 the system (that is, only a single thread can execute ``through'' it at a
28332 time), which means that the GNAT run time will deadlock waiting for the
28333 newly created task to complete its initialization.
28334
28335 @node Ada DLLs and Finalization
28336 @subsection Ada DLLs and Finalization
28337 @cindex DLLs and finalization
28338
28339 @noindent
28340 When the services of an Ada DLL are no longer needed, the client code should
28341 invoke the DLL finalization routine, if available. The DLL finalization
28342 routine is in charge of releasing all resources acquired by the DLL. In the
28343 case of the Ada code contained in the DLL, this is achieved by calling
28344 routine @code{adafinal} generated by the GNAT binder
28345 (@pxref{Binding with Non-Ada Main Programs}).
28346 See the body of @code{Finalize_Api} for an
28347 example. As already pointed out the GNAT binder is automatically invoked
28348 during the DLL build process by the @code{gnatdll} tool
28349 (@pxref{Using gnatdll}).
28350
28351 @node Creating a Spec for Ada DLLs
28352 @subsection Creating a Spec for Ada DLLs
28353
28354 @noindent
28355 To use the services exported by the Ada DLL from another programming
28356 language (e.g. C), you have to translate the specs of the exported Ada
28357 entities in that language. For instance in the case of @code{API.dll},
28358 the corresponding C header file could look like:
28359
28360 @smallexample
28361 @group
28362 @cartouche
28363 extern int *_imp__count;
28364 #define count (*_imp__count)
28365 int factorial (int);
28366 @end cartouche
28367 @end group
28368 @end smallexample
28369
28370 @noindent
28371 It is important to understand that when building an Ada DLL to be used by
28372 other Ada applications, you need two different specs for the packages
28373 contained in the DLL: one for building the DLL and the other for using
28374 the DLL. This is because the @code{DLL} calling convention is needed to
28375 use a variable defined in a DLL, but when building the DLL, the variable
28376 must have either the @code{Ada} or @code{C} calling convention. As an
28377 example consider a DLL comprising the following package @code{API}:
28378
28379 @smallexample @c ada
28380 @group
28381 @cartouche
28382 package API is
28383    Count : Integer := 0;
28384    ...
28385    --  Remainder of the package omitted.
28386 end API;
28387 @end cartouche
28388 @end group
28389 @end smallexample
28390
28391 @noindent
28392 After producing a DLL containing package @code{API}, the spec that
28393 must be used to import @code{API.Count} from Ada code outside of the
28394 DLL is:
28395
28396 @smallexample @c ada
28397 @group
28398 @cartouche
28399 package API is
28400    Count : Integer;
28401    pragma Import (DLL, Count);
28402 end API;
28403 @end cartouche
28404 @end group
28405 @end smallexample
28406
28407 @node Creating the Definition File
28408 @subsection Creating the Definition File
28409
28410 @noindent
28411 The definition file is the last file needed to build the DLL. It lists
28412 the exported symbols. As an example, the definition file for a DLL
28413 containing only package @code{API} (where all the entities are exported
28414 with a @code{C} calling convention) is:
28415
28416 @smallexample
28417 @group
28418 @cartouche
28419 EXPORTS
28420     count
28421     factorial
28422     finalize_api
28423     initialize_api
28424 @end cartouche
28425 @end group
28426 @end smallexample
28427
28428 @noindent
28429 If the @code{C} calling convention is missing from package @code{API},
28430 then the definition file contains the mangled Ada names of the above
28431 entities, which in this case are:
28432
28433 @smallexample
28434 @group
28435 @cartouche
28436 EXPORTS
28437     api__count
28438     api__factorial
28439     api__finalize_api
28440     api__initialize_api
28441 @end cartouche
28442 @end group
28443 @end smallexample
28444
28445 @node Using gnatdll
28446 @subsection Using @code{gnatdll}
28447 @findex gnatdll
28448
28449 @menu
28450 * gnatdll Example::
28451 * gnatdll behind the Scenes::
28452 * Using dlltool::
28453 @end menu
28454
28455 @noindent
28456 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28457 and non-Ada sources that make up your DLL have been compiled.
28458 @code{gnatdll} is actually in charge of two distinct tasks: build the
28459 static import library for the DLL and the actual DLL. The form of the
28460 @code{gnatdll} command is
28461
28462 @smallexample
28463 @cartouche
28464 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
28465 @end cartouche
28466 @end smallexample
28467
28468 @noindent
28469 where @i{list-of-files} is a list of ALI and object files. The object
28470 file list must be the exact list of objects corresponding to the non-Ada
28471 sources whose services are to be included in the DLL. The ALI file list
28472 must be the exact list of ALI files for the corresponding Ada sources
28473 whose services are to be included in the DLL. If @i{list-of-files} is
28474 missing, only the static import library is generated.
28475
28476 @noindent
28477 You may specify any of the following switches to @code{gnatdll}:
28478
28479 @table @code
28480 @item -a[@var{address}]
28481 @cindex @option{-a} (@code{gnatdll})
28482 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28483 specified the default address @var{0x11000000} will be used. By default,
28484 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28485 advise the reader to build relocatable DLL.
28486
28487 @item -b @var{address}
28488 @cindex @option{-b} (@code{gnatdll})
28489 Set the relocatable DLL base address. By default the address is
28490 @var{0x11000000}.
28491
28492 @item -bargs @var{opts}
28493 @cindex @option{-bargs} (@code{gnatdll})
28494 Binder options. Pass @var{opts} to the binder.
28495
28496 @item -d @var{dllfile}
28497 @cindex @option{-d} (@code{gnatdll})
28498 @var{dllfile} is the name of the DLL. This switch must be present for
28499 @code{gnatdll} to do anything. The name of the generated import library is
28500 obtained algorithmically from @var{dllfile} as shown in the following
28501 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28502 @code{libxyz.a}. The name of the definition file to use (if not specified
28503 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28504 as shown in the following example:
28505 if @var{dllfile} is @code{xyz.dll}, the definition
28506 file used is @code{xyz.def}.
28507
28508 @item -e @var{deffile}
28509 @cindex @option{-e} (@code{gnatdll})
28510 @var{deffile} is the name of the definition file.
28511
28512 @item -g
28513 @cindex @option{-g} (@code{gnatdll})
28514 Generate debugging information. This information is stored in the object
28515 file and copied from there to the final DLL file by the linker,
28516 where it can be read by the debugger. You must use the
28517 @option{-g} switch if you plan on using the debugger or the symbolic
28518 stack traceback.
28519
28520 @item -h
28521 @cindex @option{-h} (@code{gnatdll})
28522 Help mode. Displays @code{gnatdll} switch usage information.
28523
28524 @item -Idir
28525 @cindex @option{-I} (@code{gnatdll})
28526 Direct @code{gnatdll} to search the @var{dir} directory for source and
28527 object files needed to build the DLL.
28528 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28529
28530 @item -k
28531 @cindex @option{-k} (@code{gnatdll})
28532 Removes the @code{@@}@i{nn} suffix from the import library's exported
28533 names, but keeps them for the link names. You must specify this
28534 option if you want to use a @code{Stdcall} function in a DLL for which
28535 the @code{@@}@i{nn} suffix has been removed. This is the case for most
28536 of the Windows NT DLL for example. This option has no effect when
28537 @option{-n} option is specified.
28538
28539 @item -l @var{file}
28540 @cindex @option{-l} (@code{gnatdll})
28541 The list of ALI and object files used to build the DLL are listed in
28542 @var{file}, instead of being given in the command line. Each line in
28543 @var{file} contains the name of an ALI or object file.
28544
28545 @item -n
28546 @cindex @option{-n} (@code{gnatdll})
28547 No Import. Do not create the import library.
28548
28549 @item -q
28550 @cindex @option{-q} (@code{gnatdll})
28551 Quiet mode. Do not display unnecessary messages.
28552
28553 @item -v
28554 @cindex @option{-v} (@code{gnatdll})
28555 Verbose mode. Display extra information.
28556
28557 @item -largs @var{opts}
28558 @cindex @option{-largs} (@code{gnatdll})
28559 Linker options. Pass @var{opts} to the linker.
28560 @end table
28561
28562 @node gnatdll Example
28563 @subsubsection @code{gnatdll} Example
28564
28565 @noindent
28566 As an example the command to build a relocatable DLL from @file{api.adb}
28567 once @file{api.adb} has been compiled and @file{api.def} created is
28568
28569 @smallexample
28570 $ gnatdll -d api.dll api.ali
28571 @end smallexample
28572
28573 @noindent
28574 The above command creates two files: @file{libapi.a} (the import
28575 library) and @file{api.dll} (the actual DLL). If you want to create
28576 only the DLL, just type:
28577
28578 @smallexample
28579 $ gnatdll -d api.dll -n api.ali
28580 @end smallexample
28581
28582 @noindent
28583 Alternatively if you want to create just the import library, type:
28584
28585 @smallexample
28586 $ gnatdll -d api.dll
28587 @end smallexample
28588
28589 @node gnatdll behind the Scenes
28590 @subsubsection @code{gnatdll} behind the Scenes
28591
28592 @noindent
28593 This section details the steps involved in creating a DLL. @code{gnatdll}
28594 does these steps for you. Unless you are interested in understanding what
28595 goes on behind the scenes, you should skip this section.
28596
28597 We use the previous example of a DLL containing the Ada package @code{API},
28598 to illustrate the steps necessary to build a DLL. The starting point is a
28599 set of objects that will make up the DLL and the corresponding ALI
28600 files. In the case of this example this means that @file{api.o} and
28601 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28602 the following:
28603
28604 @enumerate
28605 @item
28606 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28607 the information necessary to generate relocation information for the
28608 DLL.
28609
28610 @smallexample
28611 @group
28612 $ gnatbind -n api
28613 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28614 @end group
28615 @end smallexample
28616
28617 @noindent
28618 In addition to the base file, the @command{gnatlink} command generates an
28619 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28620 asks @command{gnatlink} to generate the routines @code{DllMain} and
28621 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28622 is loaded into memory.
28623
28624 @item
28625 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28626 export table (@file{api.exp}). The export table contains the relocation
28627 information in a form which can be used during the final link to ensure
28628 that the Windows loader is able to place the DLL anywhere in memory.
28629
28630 @smallexample
28631 @group
28632 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28633           --output-exp api.exp
28634 @end group
28635 @end smallexample
28636
28637 @item
28638 @code{gnatdll} builds the base file using the new export table. Note that
28639 @command{gnatbind} must be called once again since the binder generated file
28640 has been deleted during the previous call to @command{gnatlink}.
28641
28642 @smallexample
28643 @group
28644 $ gnatbind -n api
28645 $ gnatlink api -o api.jnk api.exp -mdll
28646       -Wl,--base-file,api.base
28647 @end group
28648 @end smallexample
28649
28650 @item
28651 @code{gnatdll} builds the new export table using the new base file and
28652 generates the DLL import library @file{libAPI.a}.
28653
28654 @smallexample
28655 @group
28656 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28657           --output-exp api.exp --output-lib libAPI.a
28658 @end group
28659 @end smallexample
28660
28661 @item
28662 Finally @code{gnatdll} builds the relocatable DLL using the final export
28663 table.
28664
28665 @smallexample
28666 @group
28667 $ gnatbind -n api
28668 $ gnatlink api api.exp -o api.dll -mdll
28669 @end group
28670 @end smallexample
28671 @end enumerate
28672
28673 @node Using dlltool
28674 @subsubsection Using @code{dlltool}
28675
28676 @noindent
28677 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28678 DLLs and static import libraries. This section summarizes the most
28679 common @code{dlltool} switches. The form of the @code{dlltool} command
28680 is
28681
28682 @smallexample
28683 $ dlltool [@var{switches}]
28684 @end smallexample
28685
28686 @noindent
28687 @code{dlltool} switches include:
28688
28689 @table @option
28690 @item --base-file @var{basefile}
28691 @cindex @option{--base-file} (@command{dlltool})
28692 Read the base file @var{basefile} generated by the linker. This switch
28693 is used to create a relocatable DLL.
28694
28695 @item --def @var{deffile}
28696 @cindex @option{--def} (@command{dlltool})
28697 Read the definition file.
28698
28699 @item --dllname @var{name}
28700 @cindex @option{--dllname} (@command{dlltool})
28701 Gives the name of the DLL. This switch is used to embed the name of the
28702 DLL in the static import library generated by @code{dlltool} with switch
28703 @option{--output-lib}.
28704
28705 @item -k
28706 @cindex @option{-k} (@command{dlltool})
28707 Kill @code{@@}@i{nn} from exported names
28708 (@pxref{Windows Calling Conventions}
28709 for a discussion about @code{Stdcall}-style symbols.
28710
28711 @item --help
28712 @cindex @option{--help} (@command{dlltool})
28713 Prints the @code{dlltool} switches with a concise description.
28714
28715 @item --output-exp @var{exportfile}
28716 @cindex @option{--output-exp} (@command{dlltool})
28717 Generate an export file @var{exportfile}. The export file contains the
28718 export table (list of symbols in the DLL) and is used to create the DLL.
28719
28720 @item --output-lib @i{libfile}
28721 @cindex @option{--output-lib} (@command{dlltool})
28722 Generate a static import library @var{libfile}.
28723
28724 @item -v
28725 @cindex @option{-v} (@command{dlltool})
28726 Verbose mode.
28727
28728 @item --as @i{assembler-name}
28729 @cindex @option{--as} (@command{dlltool})
28730 Use @i{assembler-name} as the assembler. The default is @code{as}.
28731 @end table
28732
28733 @node GNAT and Windows Resources
28734 @section GNAT and Windows Resources
28735 @cindex Resources, windows
28736
28737 @menu
28738 * Building Resources::
28739 * Compiling Resources::
28740 * Using Resources::
28741 @end menu
28742
28743 @noindent
28744 Resources are an easy way to add Windows specific objects to your
28745 application. The objects that can be added as resources include:
28746
28747 @itemize @bullet
28748 @item
28749 menus
28750
28751 @item
28752 accelerators
28753
28754 @item
28755 dialog boxes
28756
28757 @item
28758 string tables
28759
28760 @item
28761 bitmaps
28762
28763 @item
28764 cursors
28765
28766 @item
28767 icons
28768
28769 @item
28770 fonts
28771 @end itemize
28772
28773 @noindent
28774 This section explains how to build, compile and use resources.
28775
28776 @node Building Resources
28777 @subsection Building Resources
28778 @cindex Resources, building
28779
28780 @noindent
28781 A resource file is an ASCII file. By convention resource files have an
28782 @file{.rc} extension.
28783 The easiest way to build a resource file is to use Microsoft tools
28784 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28785 @code{dlgedit.exe} to build dialogs.
28786 It is always possible to build an @file{.rc} file yourself by writing a
28787 resource script.
28788
28789 It is not our objective to explain how to write a resource file. A
28790 complete description of the resource script language can be found in the
28791 Microsoft documentation.
28792
28793 @node Compiling Resources
28794 @subsection Compiling Resources
28795 @findex rc
28796 @findex windres
28797 @cindex Resources, compiling
28798
28799 @noindent
28800 This section describes how to build a GNAT-compatible (COFF) object file
28801 containing the resources. This is done using the Resource Compiler
28802 @code{windres} as follows:
28803
28804 @smallexample
28805 $ windres -i myres.rc -o myres.o
28806 @end smallexample
28807
28808 @noindent
28809 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28810 file. You can specify an alternate preprocessor (usually named
28811 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28812 parameter. A list of all possible options may be obtained by entering
28813 the command @code{windres} @option{--help}.
28814
28815 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28816 to produce a @file{.res} file (binary resource file). See the
28817 corresponding Microsoft documentation for further details. In this case
28818 you need to use @code{windres} to translate the @file{.res} file to a
28819 GNAT-compatible object file as follows:
28820
28821 @smallexample
28822 $ windres -i myres.res -o myres.o
28823 @end smallexample
28824
28825 @node Using Resources
28826 @subsection Using Resources
28827 @cindex Resources, using
28828
28829 @noindent
28830 To include the resource file in your program just add the
28831 GNAT-compatible object file for the resource(s) to the linker
28832 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28833 option:
28834
28835 @smallexample
28836 $ gnatmake myprog -largs myres.o
28837 @end smallexample
28838
28839 @node Debugging a DLL
28840 @section Debugging a DLL
28841 @cindex DLL debugging
28842
28843 @menu
28844 * Program and DLL Both Built with GCC/GNAT::
28845 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28846 @end menu
28847
28848 @noindent
28849 Debugging a DLL is similar to debugging a standard program. But
28850 we have to deal with two different executable parts: the DLL and the
28851 program that uses it. We have the following four possibilities:
28852
28853 @enumerate 1
28854 @item
28855 The program and the DLL are built with @code{GCC/GNAT}.
28856 @item
28857 The program is built with foreign tools and the DLL is built with
28858 @code{GCC/GNAT}.
28859 @item
28860 The program is built with @code{GCC/GNAT} and the DLL is built with
28861 foreign tools.
28862 @item
28863 @end enumerate
28864
28865 @noindent
28866 In this section we address only cases one and two above.
28867 There is no point in trying to debug
28868 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28869 information in it. To do so you must use a debugger compatible with the
28870 tools suite used to build the DLL.
28871
28872 @node Program and DLL Both Built with GCC/GNAT
28873 @subsection Program and DLL Both Built with GCC/GNAT
28874
28875 @noindent
28876 This is the simplest case. Both the DLL and the program have @code{GDB}
28877 compatible debugging information. It is then possible to break anywhere in
28878 the process. Let's suppose here that the main procedure is named
28879 @code{ada_main} and that in the DLL there is an entry point named
28880 @code{ada_dll}.
28881
28882 @noindent
28883 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28884 program must have been built with the debugging information (see GNAT -g
28885 switch). Here are the step-by-step instructions for debugging it:
28886
28887 @enumerate 1
28888 @item Launch @code{GDB} on the main program.
28889
28890 @smallexample
28891 $ gdb -nw ada_main
28892 @end smallexample
28893
28894 @item Start the program and stop at the beginning of the main procedure
28895
28896 @smallexample
28897 (gdb) start
28898 @end smallexample
28899
28900 @noindent
28901 This step is required to be able to set a breakpoint inside the DLL. As long
28902 as the program is not run, the DLL is not loaded. This has the
28903 consequence that the DLL debugging information is also not loaded, so it is not
28904 possible to set a breakpoint in the DLL.
28905
28906 @item Set a breakpoint inside the DLL
28907
28908 @smallexample
28909 (gdb) break ada_dll
28910 (gdb) cont
28911 @end smallexample
28912
28913 @end enumerate
28914
28915 @noindent
28916 At this stage a breakpoint is set inside the DLL. From there on
28917 you can use the standard approach to debug the whole program
28918 (@pxref{Running and Debugging Ada Programs}).
28919
28920 @ignore
28921 @c This used to work, probably because the DLLs were non-relocatable
28922 @c keep this section around until the problem is sorted out.
28923
28924 To break on the @code{DllMain} routine it is not possible to follow
28925 the procedure above. At the time the program stop on @code{ada_main}
28926 the @code{DllMain} routine as already been called. Either you can use
28927 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28928
28929 @enumerate 1
28930 @item Launch @code{GDB} on the main program.
28931
28932 @smallexample
28933 $ gdb ada_main
28934 @end smallexample
28935
28936 @item Load DLL symbols
28937
28938 @smallexample
28939 (gdb) add-sym api.dll
28940 @end smallexample
28941
28942 @item Set a breakpoint inside the DLL
28943
28944 @smallexample
28945 (gdb) break ada_dll.adb:45
28946 @end smallexample
28947
28948 Note that at this point it is not possible to break using the routine symbol
28949 directly as the program is not yet running. The solution is to break
28950 on the proper line (break in @file{ada_dll.adb} line 45).
28951
28952 @item Start the program
28953
28954 @smallexample
28955 (gdb) run
28956 @end smallexample
28957
28958 @end enumerate
28959 @end ignore
28960
28961 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28962 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28963
28964 @menu
28965 * Debugging the DLL Directly::
28966 * Attaching to a Running Process::
28967 @end menu
28968
28969 @noindent
28970 In this case things are slightly more complex because it is not possible to
28971 start the main program and then break at the beginning to load the DLL and the
28972 associated DLL debugging information. It is not possible to break at the
28973 beginning of the program because there is no @code{GDB} debugging information,
28974 and therefore there is no direct way of getting initial control. This
28975 section addresses this issue by describing some methods that can be used
28976 to break somewhere in the DLL to debug it.
28977
28978 @noindent
28979 First suppose that the main procedure is named @code{main} (this is for
28980 example some C code built with Microsoft Visual C) and that there is a
28981 DLL named @code{test.dll} containing an Ada entry point named
28982 @code{ada_dll}.
28983
28984 @noindent
28985 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28986 been built with debugging information (see GNAT -g option).
28987
28988 @node Debugging the DLL Directly
28989 @subsubsection Debugging the DLL Directly
28990
28991 @enumerate 1
28992 @item
28993 Find out the executable starting address
28994
28995 @smallexample
28996 $ objdump --file-header main.exe
28997 @end smallexample
28998
28999 The starting address is reported on the last line. For example:
29000
29001 @smallexample
29002 main.exe:     file format pei-i386
29003 architecture: i386, flags 0x0000010a:
29004 EXEC_P, HAS_DEBUG, D_PAGED
29005 start address 0x00401010
29006 @end smallexample
29007
29008 @item
29009 Launch the debugger on the executable.
29010
29011 @smallexample
29012 $ gdb main.exe
29013 @end smallexample
29014
29015 @item
29016 Set a breakpoint at the starting address, and launch the program.
29017
29018 @smallexample
29019 $ (gdb) break *0x00401010
29020 $ (gdb) run
29021 @end smallexample
29022
29023 The program will stop at the given address.
29024
29025 @item
29026 Set a breakpoint on a DLL subroutine.
29027
29028 @smallexample
29029 (gdb) break ada_dll.adb:45
29030 @end smallexample
29031
29032 Or if you want to break using a symbol on the DLL, you need first to
29033 select the Ada language (language used by the DLL).
29034
29035 @smallexample
29036 (gdb) set language ada
29037 (gdb) break ada_dll
29038 @end smallexample
29039
29040 @item
29041 Continue the program.
29042
29043 @smallexample
29044 (gdb) cont
29045 @end smallexample
29046
29047 @noindent
29048 This will run the program until it reaches the breakpoint that has been
29049 set. From that point you can use the standard way to debug a program
29050 as described in (@pxref{Running and Debugging Ada Programs}).
29051
29052 @end enumerate
29053
29054 @noindent
29055 It is also possible to debug the DLL by attaching to a running process.
29056
29057 @node Attaching to a Running Process
29058 @subsubsection Attaching to a Running Process
29059 @cindex DLL debugging, attach to process
29060
29061 @noindent
29062 With @code{GDB} it is always possible to debug a running process by
29063 attaching to it. It is possible to debug a DLL this way. The limitation
29064 of this approach is that the DLL must run long enough to perform the
29065 attach operation. It may be useful for instance to insert a time wasting
29066 loop in the code of the DLL to meet this criterion.
29067
29068 @enumerate 1
29069
29070 @item Launch the main program @file{main.exe}.
29071
29072 @smallexample
29073 $ main
29074 @end smallexample
29075
29076 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29077 that the process PID for @file{main.exe} is 208.
29078
29079 @item Launch gdb.
29080
29081 @smallexample
29082 $ gdb
29083 @end smallexample
29084
29085 @item Attach to the running process to be debugged.
29086
29087 @smallexample
29088 (gdb) attach 208
29089 @end smallexample
29090
29091 @item Load the process debugging information.
29092
29093 @smallexample
29094 (gdb) symbol-file main.exe
29095 @end smallexample
29096
29097 @item Break somewhere in the DLL.
29098
29099 @smallexample
29100 (gdb) break ada_dll
29101 @end smallexample
29102
29103 @item Continue process execution.
29104
29105 @smallexample
29106 (gdb) cont
29107 @end smallexample
29108
29109 @end enumerate
29110
29111 @noindent
29112 This last step will resume the process execution, and stop at
29113 the breakpoint we have set. From there you can use the standard
29114 approach to debug a program as described in
29115 (@pxref{Running and Debugging Ada Programs}).
29116
29117 @node Setting Stack Size from gnatlink
29118 @section Setting Stack Size from @command{gnatlink}
29119
29120 @noindent
29121 It is possible to specify the program stack size at link time. On modern
29122 versions of Windows, starting with XP, this is mostly useful to set the size of
29123 the main stack (environment task). The other task stacks are set with pragma
29124 Storage_Size or with gnatbind -d.
29125
29126 Older versions of Windows (2000, NT4, etc.) do
29127 not provide any means of setting the reserve size of individual tasks, thus the
29128 link-time stack size applies to all tasks and pragma Storage_Size has no effect.
29129 It means, in particular, that Stack Overflow checks are made against this
29130 link-time specified size.
29131
29132 This setting can be done with
29133 @command{gnatlink} using either:
29134
29135 @itemize @bullet
29136
29137 @item using @option{-Xlinker} linker option
29138
29139 @smallexample
29140 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29141 @end smallexample
29142
29143 This sets the stack reserve size to 0x10000 bytes and the stack commit
29144 size to 0x1000 bytes.
29145
29146 @item using @option{-Wl} linker option
29147
29148 @smallexample
29149 $ gnatlink hello -Wl,--stack=0x1000000
29150 @end smallexample
29151
29152 This sets the stack reserve size to 0x1000000 bytes. Note that with
29153 @option{-Wl} option it is not possible to set the stack commit size
29154 because the coma is a separator for this option.
29155
29156 @end itemize
29157
29158 @node Setting Heap Size from gnatlink
29159 @section Setting Heap Size from @command{gnatlink}
29160
29161 @noindent
29162 Under Windows systems, it is possible to specify the program heap size from
29163 @command{gnatlink} using either:
29164
29165 @itemize @bullet
29166
29167 @item using @option{-Xlinker} linker option
29168
29169 @smallexample
29170 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29171 @end smallexample
29172
29173 This sets the heap reserve size to 0x10000 bytes and the heap commit
29174 size to 0x1000 bytes.
29175
29176 @item using @option{-Wl} linker option
29177
29178 @smallexample
29179 $ gnatlink hello -Wl,--heap=0x1000000
29180 @end smallexample
29181
29182 This sets the heap reserve size to 0x1000000 bytes. Note that with
29183 @option{-Wl} option it is not possible to set the heap commit size
29184 because the coma is a separator for this option.
29185
29186 @end itemize
29187
29188 @end ifset
29189
29190 @c **********************************
29191 @c * GNU Free Documentation License *
29192 @c **********************************
29193 @include fdl.texi
29194 @c GNU Free Documentation License
29195
29196 @node Index,,GNU Free Documentation License, Top
29197 @unnumbered Index
29198
29199 @printindex cp
29200
29201 @contents
29202 @c Put table of contents at end, otherwise it precedes the "title page" in
29203 @c the .txt version
29204 @c Edit the pdf file to move the contents to the beginning, after the title
29205 @c page
29206
29207 @bye