OSDN Git Service

2005-07-07 Sergey Rybin <rybin@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-2005 Ada Core Technologies, Inc.               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 * Creating Sample Bodies Using gnatstub::
195 * Other Utility Programs::
196 * Running and Debugging Ada Programs::
197 @ifset vms
198 * Compatibility with DEC Ada::
199 @end ifset
200 * Platform-Specific Information for the Run-Time Libraries::
201 * Example of Binder Output File::
202 * Elaboration Order Handling in GNAT::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 * Introduction to Glide and GVD::
232 @end ifclear
233
234 The GNAT Compilation Model
235
236 * Source Representation::
237 * Foreign Language Representation::
238 * File Naming Rules::
239 * Using Other File Names::
240 * Alternative File Naming Schemes::
241 * Generating Object Files::
242 * Source Dependencies::
243 * The Ada Library Information Files::
244 * Binding an Ada Program::
245 * Mixed Language Programming::
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 * Comparison between GNAT and Conventional Ada Library Models::
249 @ifset vms
250 * Placement of temporary files::
251 @end ifset
252
253 Foreign Language Representation
254
255 * Latin-1::
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
258
259 Compiling Ada Programs With gcc
260
261 * Compiling Programs::
262 * Switches for gcc::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
265 * Examples::
266
267 Switches for gcc
268
269 * Output and Error Message Control::
270 * Warning Message Control::
271 * Debugging and Assertion Control::
272 * Validity Checking::
273 * Style Checking::
274 * Run-Time Checks::
275 * Stack Overflow Checking::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312 * Setting Stack Size from gnatlink::
313 * Setting Heap Size from gnatlink::
314
315 The GNAT Make Program gnatmake
316
317 * Running gnatmake::
318 * Switches for gnatmake::
319 * Mode Switches for gnatmake::
320 * Notes on the Command Line::
321 * How gnatmake Works::
322 * Examples of gnatmake Usage::
323
324 Improving Performance
325 * Performance Considerations::
326 * Reducing the Size of Ada Executables with gnatelim::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Optimization and Strict Aliasing::
335 @ifset vms
336 * Coverage Analysis::
337 @end ifset
338
339 Reducing the Size of Ada Executables with gnatelim
340 * About gnatelim::
341 * Running gnatelim::
342 * Correcting the List of Eliminate Pragmas::
343 * Making Your Executables Smaller::
344 * Summary of the gnatelim Usage Cycle::
345
346 Renaming Files Using gnatchop
347
348 * Handling Files with Multiple Units::
349 * Operating gnatchop in Compilation Mode::
350 * Command Line for gnatchop::
351 * Switches for gnatchop::
352 * Examples of gnatchop Usage::
353
354 Configuration Pragmas
355
356 * Handling of Configuration Pragmas::
357 * The Configuration Pragmas Files::
358
359 Handling Arbitrary File Naming Conventions Using gnatname
360
361 * Arbitrary File Naming Conventions::
362 * Running gnatname::
363 * Switches for gnatname::
364 * Examples of gnatname Usage::
365
366 GNAT Project Manager
367
368 * Introduction::
369 * Examples of Project Files::
370 * Project File Syntax::
371 * Objects and Sources in Project Files::
372 * Importing Projects::
373 * Project Extension::
374 * Project Hierarchy Extension::
375 * External References in Project Files::
376 * Packages in Project Files::
377 * Variables from Imported Projects::
378 * Naming Schemes::
379 * Library Projects::
380 * Stand-alone Library Projects::
381 * Switches Related to Project Files::
382 * Tools Supporting Project Files::
383 * An Extended Example::
384 * Project File Complete Syntax::
385
386 The Cross-Referencing Tools gnatxref and gnatfind
387
388 * gnatxref Switches::
389 * gnatfind Switches::
390 * Project Files for gnatxref and gnatfind::
391 * Regular Expressions in gnatfind and gnatxref::
392 * Examples of gnatxref Usage::
393 * Examples of gnatfind Usage::
394
395 The GNAT Pretty-Printer gnatpp
396
397 * Switches for gnatpp::
398 * Formatting Rules::
399
400 The GNAT Metrics Tool gnatmetric
401
402 * Switches for gnatmetric::
403
404 File Name Krunching Using gnatkr
405
406 * About gnatkr::
407 * Using gnatkr::
408 * Krunching Method::
409 * Examples of gnatkr Usage::
410
411 Preprocessing Using gnatprep
412
413 * Using gnatprep::
414 * Switches for gnatprep::
415 * Form of Definitions File::
416 * Form of Input Text for gnatprep::
417
418 @ifset vms
419 The GNAT Run-Time Library Builder gnatlbr
420
421 * Running gnatlbr::
422 * Switches for gnatlbr::
423 * Examples of gnatlbr Usage::
424 @end ifset
425
426 The GNAT Library Browser gnatls
427
428 * Running gnatls::
429 * Switches for gnatls::
430 * Examples of gnatls Usage::
431
432 Cleaning Up Using gnatclean
433
434 * Running gnatclean::
435 * Switches for gnatclean::
436 @c * Examples of gnatclean Usage::
437
438 @ifclear vms
439
440 GNAT and Libraries
441
442 * Introduction to Libraries in GNAT::
443 * General Ada Libraries::
444 * Stand-alone Ada Libraries::
445 * Rebuilding the GNAT Run-Time Library::
446
447 Using the GNU make Utility
448
449 * Using gnatmake in a Makefile::
450 * Automatically Creating a List of Directories::
451 * Generating the Command Line Switches::
452 * Overcoming Command Line Length Limits::
453 @end ifclear
454
455 Memory Management Issues
456
457 * Some Useful Memory Pools::
458 * The GNAT Debug Pool Facility::
459 @ifclear vms
460 * The gnatmem Tool::
461 @end ifclear
462
463 Some Useful Memory Pools
464
465 The GNAT Debug Pool Facility
466
467 @ifclear vms
468 The gnatmem Tool
469
470 * Running gnatmem::
471 * Switches for gnatmem::
472 * Example of gnatmem Usage::
473 @end ifclear
474
475  Sample Bodies Using gnatstub
476
477 * Running gnatstub::
478 * Switches for gnatstub::
479
480 Other Utility Programs
481
482 * Using Other Utility Programs with GNAT::
483 * The External Symbol Naming Scheme of GNAT::
484 @ifclear vms
485 * Ada Mode for Glide::
486 @end ifclear
487 * Converting Ada Files to html with gnathtml::
488
489 Running and Debugging Ada Programs
490
491 * The GNAT Debugger GDB::
492 * Running GDB::
493 * Introduction to GDB Commands::
494 * Using Ada Expressions::
495 * Calling User-Defined Subprograms::
496 * Using the Next Command in a Function::
497 * Ada Exceptions::
498 * Ada Tasks::
499 * Debugging Generic Units::
500 * GNAT Abnormal Termination or Failure to Terminate::
501 * Naming Conventions for GNAT Source Files::
502 * Getting Internal Debugging Information::
503 * Stack Traceback::
504
505 @ifset vms
506 * LSE::
507 @end ifset
508
509 @ifset vms
510 Compatibility with DEC Ada
511
512 * Ada 95 Compatibility::
513 * Differences in the Definition of Package System::
514 * Language-Related Features::
515 * The Package STANDARD::
516 * The Package SYSTEM::
517 * Tasking and Task-Related Features::
518 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
519 * Pragmas and Pragma-Related Features::
520 * Library of Predefined Units::
521 * Bindings::
522 * Main Program Definition::
523 * Implementation-Defined Attributes::
524 * Compiler and Run-Time Interfacing::
525 * Program Compilation and Library Management::
526 * Input-Output::
527 * Implementation Limits::
528 * Tools::
529
530 Language-Related Features
531
532 * Integer Types and Representations::
533 * Floating-Point Types and Representations::
534 * Pragmas Float_Representation and Long_Float::
535 * Fixed-Point Types and Representations::
536 * Record and Array Component Alignment::
537 * Address Clauses::
538 * Other Representation Clauses::
539
540 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
541
542 * Assigning Task IDs::
543 * Task IDs and Delays::
544 * Task-Related Pragmas::
545 * Scheduling and Task Priority::
546 * The Task Stack::
547 * External Interrupts::
548
549 Pragmas and Pragma-Related Features
550
551 * Restrictions on the Pragma INLINE::
552 * Restrictions on the Pragma INTERFACE::
553 * Restrictions on the Pragma SYSTEM_NAME::
554
555 Library of Predefined Units
556
557 * Changes to DECLIB::
558
559 Bindings
560
561 * Shared Libraries and Options Files::
562 * Interfaces to C::
563 @end ifset
564
565 Platform-Specific Information for the Run-Time Libraries
566
567 * Summary of Run-Time Configurations::
568 * Specifying a Run-Time Library::
569 * Choosing the Scheduling Policy::
570 * Solaris-Specific Considerations::
571 * IRIX-Specific Considerations::
572 * Linux-Specific Considerations::
573 * AIX-Specific Considerations::
574
575 Example of Binder Output File
576
577 Elaboration Order Handling in GNAT
578
579 * Elaboration Code in Ada 95::
580 * Checking the Elaboration Order in Ada 95::
581 * Controlling the Elaboration Order in Ada 95::
582 * Controlling Elaboration in GNAT - Internal Calls::
583 * Controlling Elaboration in GNAT - External Calls::
584 * Default Behavior in GNAT - Ensuring Safety::
585 * Treatment of Pragma Elaborate::
586 * Elaboration Issues for Library Tasks::
587 * Mixing Elaboration Models::
588 * What to Do If the Default Elaboration Behavior Fails::
589 * Elaboration for Access-to-Subprogram Values::
590 * Summary of Procedures for Elaboration Control::
591 * Other Elaboration Order Considerations::
592
593 Inline Assembler
594
595 * Basic Assembler Syntax::
596 * A Simple Example of Inline Assembler::
597 * Output Variables in Inline Assembler::
598 * Input Variables in Inline Assembler::
599 * Inlining Inline Assembler Code::
600 * Other Asm Functionality::
601
602 Compatibility and Porting Guide
603
604 * Compatibility with Ada 83::
605 * Implementation-dependent characteristics::
606 * Compatibility with DEC Ada 83::
607 * Compatibility with Other Ada 95 Systems::
608 * Representation Clauses::
609 @ifset vms
610 * Transitioning from Alpha to Integrity OpenVMS::
611 @end ifset
612
613 @ifset unw
614 Microsoft Windows Topics
615
616 * Using GNAT on Windows::
617 * CONSOLE and WINDOWS subsystems::
618 * Temporary Files::
619 * Mixed-Language Programming on Windows::
620 * Windows Calling Conventions::
621 * Introduction to Dynamic Link Libraries (DLLs)::
622 * Using DLLs with GNAT::
623 * Building DLLs with GNAT::
624 * GNAT and Windows Resources::
625 * Debugging a DLL::
626 * GNAT and COM/DCOM Objects::
627 @end ifset
628
629 * Index::
630 @end menu
631 @end ifnottex
632
633 @node About This Guide
634 @unnumbered About This Guide
635
636 @noindent
637 @ifset vms
638 This guide describes the use of @value{EDITION},
639 a full language compiler for the Ada
640 95 programming language, implemented on HP's Alpha and
641 Integrity (ia64) OpenVMS platforms.
642 @end ifset
643 @ifclear vms
644 This guide describes the use of @value{EDITION},
645 a compiler and software development
646 toolset for the full Ada 95 programming language.
647 @end ifclear
648 It describes the features of the compiler and tools, and details
649 how to use them to build Ada 95 applications.
650
651 @ifset PROEDITION
652 For ease of exposition, ``GNAT Pro'' will be referred to simply as
653 ``GNAT'' in the remainder of this document.
654 @end ifset
655
656 @menu
657 * What This Guide Contains::
658 * What You Should Know before Reading This Guide::
659 * Related Information::
660 * Conventions::
661 @end menu
662
663 @node What This Guide Contains
664 @unnumberedsec What This Guide Contains
665
666 @noindent
667 This guide contains the following chapters:
668 @itemize @bullet
669
670 @item
671 @ref{Getting Started with GNAT}, describes how to get started compiling
672 and running Ada programs with the GNAT Ada programming environment.
673 @item
674 @ref{The GNAT Compilation Model}, describes the compilation model used
675 by GNAT.
676
677 @item
678 @ref{Compiling Using gcc}, describes how to compile
679 Ada programs with @command{gcc}, the Ada compiler.
680
681 @item
682 @ref{Binding Using gnatbind}, describes how to
683 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
684 utility.
685
686 @item
687 @ref{Linking Using gnatlink},
688 describes @command{gnatlink}, a
689 program that provides for linking using the GNAT run-time library to
690 construct a program. @command{gnatlink} can also incorporate foreign language
691 object units into the executable.
692
693 @item
694 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
695 utility that automatically determines the set of sources
696 needed by an Ada compilation unit, and executes the necessary compilations
697 binding and link.
698
699 @item
700 @ref{Improving Performance}, shows various techniques for making your
701 Ada program run faster or take less space.
702 It discusses the effect of the compiler's optimization switch and
703 also describes the @command{gnatelim} tool.
704
705 @item
706 @ref{Renaming Files Using gnatchop}, describes
707 @code{gnatchop}, a utility that allows you to preprocess a file that
708 contains Ada source code, and split it into one or more new files, one
709 for each compilation unit.
710
711 @item
712 @ref{Configuration Pragmas}, describes the configuration pragmas
713 handled by GNAT.
714
715 @item
716 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
717 shows how to override the default GNAT file naming conventions,
718 either for an individual unit or globally.
719
720 @item
721 @ref{GNAT Project Manager}, describes how to use project files
722 to organize large projects.
723
724 @item
725 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
726 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
727 way to navigate through sources.
728
729 @item
730 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
731 version of an Ada source file with control over casing, indentation,
732 comment placement, and other elements of program presentation style.
733
734 @item
735 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
736 metrics for an Ada source file, such as the number of types and subprograms,
737 and assorted complexity measures.
738
739 @item
740 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
741 file name krunching utility, used to handle shortened
742 file names on operating systems with a limit on the length of names.
743
744 @item
745 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
746 preprocessor utility that allows a single source file to be used to
747 generate multiple or parameterized source files, by means of macro
748 substitution.
749
750 @ifset vms
751 @item
752 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
753 a tool for rebuilding the GNAT run time with user-supplied
754 configuration pragmas.
755 @end ifset
756
757 @item
758 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
759 utility that displays information about compiled units, including dependences
760 on the corresponding sources files, and consistency of compilations.
761
762 @item
763 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
764 to delete files that are produced by the compiler, binder and linker.
765
766 @ifclear vms
767 @item
768 @ref{GNAT and Libraries}, describes the process of creating and using
769 Libraries with GNAT. It also describes how to recompile the GNAT run-time
770 library.
771
772 @item
773 @ref{Using the GNU make Utility}, describes some techniques for using
774 the GNAT toolset in Makefiles.
775 @end ifclear
776
777 @item
778 @ref{Memory Management Issues}, describes some useful predefined storage pools
779 and in particular the GNAT Debug Pool facility, which helps detect incorrect
780 memory references.
781 @ifclear vms
782 It also describes @command{gnatmem}, a utility that monitors dynamic
783 allocation and deallocation and helps detect ``memory leaks''.
784 @end ifclear
785
786 @item
787 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
788 a utility that generates empty but compilable bodies for library units.
789
790 @item
791 @ref{Other Utility Programs}, discusses several other GNAT utilities,
792 including @code{gnathtml}.
793
794 @item
795 @ref{Running and Debugging Ada Programs}, describes how to run and debug
796 Ada programs.
797
798 @ifset vms
799 @item
800 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
801 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
802 developed by Digital Equipment Corporation and currently supported by HP.}
803 for OpenVMS Alpha.
804 @end ifset
805
806 @item
807 @ref{Platform-Specific Information for the Run-Time Libraries},
808 describes the various run-time
809 libraries supported by GNAT on various platforms and explains how to
810 choose a particular library.
811
812 @item
813 @ref{Example of Binder Output File}, shows the source code for the binder
814 output file for a sample program.
815
816 @item
817 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
818 you deal with elaboration order issues.
819
820 @item
821 @ref{Inline Assembler}, shows how to use the inline assembly facility
822 in an Ada program.
823
824 @item
825 @ref{Compatibility and Porting Guide}, includes sections on compatibility
826 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
827 in porting code from other environments.
828
829 @ifset unw
830 @item
831 @ref{Microsoft Windows Topics}, presents information relevant to the
832 Microsoft Windows platform.
833 @end ifset
834 @end itemize
835
836 @c *************************************************
837 @node What You Should Know before Reading This Guide
838 @c *************************************************
839 @unnumberedsec What You Should Know before Reading This Guide
840
841 @cindex Ada 95 Language Reference Manual
842 @noindent
843 This user's guide assumes that you are familiar with Ada 95 language, as
844 described in the International Standard ANSI/ISO/IEC-8652:1995, January
845 1995.
846
847 @node Related Information
848 @unnumberedsec Related Information
849
850 @noindent
851 For further information about related tools, refer to the following
852 documents:
853
854 @itemize @bullet
855 @item
856 @cite{GNAT Reference Manual}, which contains all reference
857 material for the GNAT implementation of Ada 95.
858
859 @ifset unw
860 @item
861 @cite{Using the GNAT Programming System}, which describes the GPS
862 integrated development environment.
863
864 @item
865 @cite{GNAT Programming System Tutorial}, which introduces the
866 main GPS features through examples.
867 @end ifset
868
869 @item
870 @cite{Ada 95 Language Reference Manual}, which contains all reference
871 material for the Ada 95 programming language.
872
873 @item
874 @cite{Debugging with GDB}
875 @ifset vms
876 , located in the GNU:[DOCS] directory,
877 @end ifset
878 contains all details on the use of the GNU source-level debugger.
879
880 @item
881 @cite{GNU Emacs Manual}
882 @ifset vms
883 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
884 @end ifset
885 contains full information on the extensible editor and programming
886 environment Emacs.
887
888 @end itemize
889
890 @c **************
891 @node Conventions
892 @unnumberedsec Conventions
893 @cindex Conventions
894 @cindex Typographical conventions
895
896 @noindent
897 Following are examples of the typographical and graphic conventions used
898 in this guide:
899
900 @itemize @bullet
901 @item
902 @code{Functions}, @code{utility program names}, @code{standard names},
903 and @code{classes}.
904
905 @item
906 @samp{Option flags}
907
908 @item
909 @file{File Names}, @file{button names}, and @file{field names}.
910
911 @item
912 @var{Variables}.
913
914 @item
915 @emph{Emphasis}.
916
917 @item
918 [optional information or parameters]
919
920 @item
921 Examples are described by text
922 @smallexample
923 and then shown this way.
924 @end smallexample
925 @end itemize
926
927 @noindent
928 Commands that are entered by the user are preceded in this manual by the
929 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
930 uses this sequence as a prompt, then the commands will appear exactly as
931 you see them in the manual. If your system uses some other prompt, then
932 the command will appear with the @code{$} replaced by whatever prompt
933 character you are using.
934
935 @ifset unw
936 Full file names are shown with the ``@code{/}'' character
937 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
938 If you are using GNAT on a Windows platform, please note that
939 the ``@code{\}'' character should be used instead.
940 @end ifset
941
942 @c ****************************
943 @node Getting Started with GNAT
944 @chapter Getting Started with GNAT
945
946 @noindent
947 This chapter describes some simple ways of using GNAT to build
948 executable Ada programs.
949 @ifset unw
950 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
951 show how to use the command line environment.
952 @ref{Introduction to Glide and GVD}, provides a brief
953 introduction to the visually-oriented IDE for GNAT.
954 Supplementing Glide on some platforms is GPS, the
955 GNAT Programming System, which offers a richer graphical
956 ``look and feel'', enhanced configurability, support for
957 development in other programming language, comprehensive
958 browsing features, and many other capabilities.
959 For information on GPS please refer to
960 @cite{Using the GNAT Programming System}.
961 @end ifset
962
963 @menu
964 * Running GNAT::
965 * Running a Simple Ada Program::
966 * Running a Program with Multiple Units::
967 * Using the gnatmake Utility::
968 @ifset vms
969 * Editing with Emacs::
970 @end ifset
971 @ifclear vms
972 * Introduction to GPS::
973 * Introduction to Glide and GVD::
974 @end ifclear
975 @end menu
976
977 @node Running GNAT
978 @section Running GNAT
979
980 @noindent
981 Three steps are needed to create an executable file from an Ada source
982 file:
983
984 @enumerate
985 @item
986 The source file(s) must be compiled.
987 @item
988 The file(s) must be bound using the GNAT binder.
989 @item
990 All appropriate object files must be linked to produce an executable.
991 @end enumerate
992
993 @noindent
994 All three steps are most commonly handled by using the @command{gnatmake}
995 utility program that, given the name of the main program, automatically
996 performs the necessary compilation, binding and linking steps.
997
998 @node Running a Simple Ada Program
999 @section Running a Simple Ada Program
1000
1001 @noindent
1002 Any text editor may be used to prepare an Ada program.
1003 @ifclear vms
1004 If @code{Glide} is
1005 used, the optional Ada mode may be helpful in laying out the program.
1006 @end ifclear
1007 The
1008 program text is a normal text file. We will suppose in our initial
1009 example that you have used your editor to prepare the following
1010 standard format text file:
1011
1012 @smallexample @c ada
1013 @cartouche
1014 with Ada.Text_IO; use Ada.Text_IO;
1015 procedure Hello is
1016 begin
1017    Put_Line ("Hello WORLD!");
1018 end Hello;
1019 @end cartouche
1020 @end smallexample
1021
1022 @noindent
1023 This file should be named @file{hello.adb}.
1024 With the normal default file naming conventions, GNAT requires
1025 that each file
1026 contain a single compilation unit whose file name is the
1027 unit name,
1028 with periods replaced by hyphens; the
1029 extension is @file{ads} for a
1030 spec and @file{adb} for a body.
1031 You can override this default file naming convention by use of the
1032 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1033 Alternatively, if you want to rename your files according to this default
1034 convention, which is probably more convenient if you will be using GNAT
1035 for all your compilations, then the @code{gnatchop} utility
1036 can be used to generate correctly-named source files
1037 (@pxref{Renaming Files Using gnatchop}).
1038
1039 You can compile the program using the following command (@code{$} is used
1040 as the command prompt in the examples in this document):
1041
1042 @smallexample
1043 $ gcc -c hello.adb
1044 @end smallexample
1045
1046 @noindent
1047 @command{gcc} is the command used to run the compiler. This compiler is
1048 capable of compiling programs in several languages, including Ada 95 and
1049 C. It assumes that you have given it an Ada program if the file extension is
1050 either @file{.ads} or @file{.adb}, and it will then call
1051 the GNAT compiler to compile the specified file.
1052
1053 @ifclear vms
1054 The @option{-c} switch is required. It tells @command{gcc} to only do a
1055 compilation. (For C programs, @command{gcc} can also do linking, but this
1056 capability is not used directly for Ada programs, so the @option{-c}
1057 switch must always be present.)
1058 @end ifclear
1059
1060 This compile command generates a file
1061 @file{hello.o}, which is the object
1062 file corresponding to your Ada program. It also generates
1063 an ``Ada Library Information'' file @file{hello.ali},
1064 which contains additional information used to check
1065 that an Ada program is consistent.
1066 To build an executable file,
1067 use @code{gnatbind} to bind the program
1068 and @command{gnatlink} to link it. The
1069 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1070 @file{ALI} file, but the default extension of @file{.ali} can
1071 be omitted. This means that in the most common case, the argument
1072 is simply the name of the main program:
1073
1074 @smallexample
1075 $ gnatbind hello
1076 $ gnatlink hello
1077 @end smallexample
1078
1079 @noindent
1080 A simpler method of carrying out these steps is to use
1081 @command{gnatmake},
1082 a master program that invokes all the required
1083 compilation, binding and linking tools in the correct order. In particular,
1084 @command{gnatmake} automatically recompiles any sources that have been
1085 modified since they were last compiled, or sources that depend
1086 on such modified sources, so that ``version skew'' is avoided.
1087 @cindex Version skew (avoided by @command{gnatmake})
1088
1089 @smallexample
1090 $ gnatmake hello.adb
1091 @end smallexample
1092
1093 @noindent
1094 The result is an executable program called @file{hello}, which can be
1095 run by entering:
1096
1097 @smallexample
1098 $ ^hello^RUN HELLO^
1099 @end smallexample
1100
1101 @noindent
1102 assuming that the current directory is on the search path
1103 for executable programs.
1104
1105 @noindent
1106 and, if all has gone well, you will see
1107
1108 @smallexample
1109 Hello WORLD!
1110 @end smallexample
1111
1112 @noindent
1113 appear in response to this command.
1114
1115 @c ****************************************
1116 @node Running a Program with Multiple Units
1117 @section Running a Program with Multiple Units
1118
1119 @noindent
1120 Consider a slightly more complicated example that has three files: a
1121 main program, and the spec and body of a package:
1122
1123 @smallexample @c ada
1124 @cartouche
1125 @group
1126 package Greetings is
1127    procedure Hello;
1128    procedure Goodbye;
1129 end Greetings;
1130
1131 with Ada.Text_IO; use Ada.Text_IO;
1132 package body Greetings is
1133    procedure Hello is
1134    begin
1135       Put_Line ("Hello WORLD!");
1136    end Hello;
1137
1138    procedure Goodbye is
1139    begin
1140       Put_Line ("Goodbye WORLD!");
1141    end Goodbye;
1142 end Greetings;
1143 @end group
1144
1145 @group
1146 with Greetings;
1147 procedure Gmain is
1148 begin
1149    Greetings.Hello;
1150    Greetings.Goodbye;
1151 end Gmain;
1152 @end group
1153 @end cartouche
1154 @end smallexample
1155
1156 @noindent
1157 Following the one-unit-per-file rule, place this program in the
1158 following three separate files:
1159
1160 @table @file
1161 @item greetings.ads
1162 spec of package @code{Greetings}
1163
1164 @item greetings.adb
1165 body of package @code{Greetings}
1166
1167 @item gmain.adb
1168 body of main program
1169 @end table
1170
1171 @noindent
1172 To build an executable version of
1173 this program, we could use four separate steps to compile, bind, and link
1174 the program, as follows:
1175
1176 @smallexample
1177 $ gcc -c gmain.adb
1178 $ gcc -c greetings.adb
1179 $ gnatbind gmain
1180 $ gnatlink gmain
1181 @end smallexample
1182
1183 @noindent
1184 Note that there is no required order of compilation when using GNAT.
1185 In particular it is perfectly fine to compile the main program first.
1186 Also, it is not necessary to compile package specs in the case where
1187 there is an accompanying body; you only need to compile the body. If you want
1188 to submit these files to the compiler for semantic checking and not code
1189 generation, then use the
1190 @option{-gnatc} switch:
1191
1192 @smallexample
1193 $ gcc -c greetings.ads -gnatc
1194 @end smallexample
1195
1196 @noindent
1197 Although the compilation can be done in separate steps as in the
1198 above example, in practice it is almost always more convenient
1199 to use the @command{gnatmake} tool. All you need to know in this case
1200 is the name of the main program's source file. The effect of the above four
1201 commands can be achieved with a single one:
1202
1203 @smallexample
1204 $ gnatmake gmain.adb
1205 @end smallexample
1206
1207 @noindent
1208 In the next section we discuss the advantages of using @command{gnatmake} in
1209 more detail.
1210
1211 @c *****************************
1212 @node Using the gnatmake Utility
1213 @section Using the @command{gnatmake} Utility
1214
1215 @noindent
1216 If you work on a program by compiling single components at a time using
1217 @command{gcc}, you typically keep track of the units you modify. In order to
1218 build a consistent system, you compile not only these units, but also any
1219 units that depend on the units you have modified.
1220 For example, in the preceding case,
1221 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1222 you edit @file{greetings.ads}, you must recompile both
1223 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1224 units that depend on @file{greetings.ads}.
1225
1226 @code{gnatbind} will warn you if you forget one of these compilation
1227 steps, so that it is impossible to generate an inconsistent program as a
1228 result of forgetting to do a compilation. Nevertheless it is tedious and
1229 error-prone to keep track of dependencies among units.
1230 One approach to handle the dependency-bookkeeping is to use a
1231 makefile. However, makefiles present maintenance problems of their own:
1232 if the dependencies change as you change the program, you must make
1233 sure that the makefile is kept up-to-date manually, which is also an
1234 error-prone process.
1235
1236 The @command{gnatmake} utility takes care of these details automatically.
1237 Invoke it using either one of the following forms:
1238
1239 @smallexample
1240 $ gnatmake gmain.adb
1241 $ gnatmake ^gmain^GMAIN^
1242 @end smallexample
1243
1244 @noindent
1245 The argument is the name of the file containing the main program;
1246 you may omit the extension. @command{gnatmake}
1247 examines the environment, automatically recompiles any files that need
1248 recompiling, and binds and links the resulting set of object files,
1249 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1250 In a large program, it
1251 can be extremely helpful to use @command{gnatmake}, because working out by hand
1252 what needs to be recompiled can be difficult.
1253
1254 Note that @command{gnatmake}
1255 takes into account all the Ada 95 rules that
1256 establish dependencies among units. These include dependencies that result
1257 from inlining subprogram bodies, and from
1258 generic instantiation. Unlike some other
1259 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1260 found by the compiler on a previous compilation, which may possibly
1261 be wrong when sources change. @command{gnatmake} determines the exact set of
1262 dependencies from scratch each time it is run.
1263
1264 @ifset vms
1265 @node Editing with Emacs
1266 @section Editing with Emacs
1267 @cindex Emacs
1268
1269 @noindent
1270 Emacs is an extensible self-documenting text editor that is available in a
1271 separate VMSINSTAL kit.
1272
1273 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1274 click on the Emacs Help menu and run the Emacs Tutorial.
1275 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1276 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1277
1278 Documentation on Emacs and other tools is available in Emacs under the
1279 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1280 use the middle mouse button to select a topic (e.g. Emacs).
1281
1282 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1283 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1284 get to the Emacs manual.
1285 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1286 prompt.
1287
1288 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1289 which is sufficiently extensible to provide for a complete programming
1290 environment and shell for the sophisticated user.
1291 @end ifset
1292
1293 @ifclear vms
1294 @node Introduction to GPS
1295 @section Introduction to GPS
1296 @cindex GPS (GNAT Programming System)
1297 @cindex GNAT Programming System (GPS)
1298 @noindent
1299 Although the command line interface (@command{gnatmake}, etc.) alone
1300 is sufficient, a graphical Interactive Development
1301 Environment can make it easier for you to compose, navigate, and debug
1302 programs.  This section describes the main features of GPS
1303 (``GNAT Programming System''), the GNAT graphical IDE.
1304 You will see how to use GPS to build and debug an executable, and
1305 you will also learn some of the basics of the GNAT ``project'' facility.
1306
1307 GPS enables you to do much more than is presented here;
1308 e.g., you can produce a call graph, interface to a third-party
1309 Version Control System, and inspect the generated assembly language
1310 for a program.
1311 Indeed, GPS also supports languages other than Ada.
1312 Such additional information, and an explanation of all of the GPS menu
1313 items. may be found in the on-line help, which includes
1314 a user's guide and a tutorial (these are also accessible from the GNAT
1315 startup menu).
1316
1317 @menu
1318 * Building a New Program with GPS::
1319 * Simple Debugging with GPS::
1320 @end menu
1321
1322 @node Building a New Program with GPS
1323 @subsection Building a New Program with GPS
1324 @noindent
1325 GPS invokes the GNAT compilation tools using information
1326 contained in a @emph{project} (also known as a @emph{project file}):
1327 a collection of properties such
1328 as source directories, identities of main subprograms, tool switches, etc.,
1329 and their associated values.
1330 See @ref{GNAT Project Manager} for details.
1331 In order to run GPS, you will need to either create a new project
1332 or else open an existing one.
1333
1334 This section will explain how you can use GPS to create a project,
1335 to associate Ada source files with a project, and to build and run
1336 programs.
1337
1338 @enumerate
1339 @item @emph{Creating a project}
1340
1341 Invoke GPS, either from the command line or the platform's IDE.
1342 After it starts, GPS will display a ``Welcome'' screen with three
1343 radio buttons:
1344
1345 @itemize @bullet
1346 @item
1347 @code{Start with default project in directory}
1348
1349 @item
1350 @code{Create new project with wizard}
1351
1352 @item
1353 @code{Open existing project}
1354 @end itemize
1355
1356 @noindent
1357 Select @code{Create new project with wizard} and press @code{OK}.
1358 A new window will appear.  In the text box labeled with
1359 @code{Enter the name of the project to create}, type @file{sample}
1360 as the project name.
1361 In the next box, browse to choose the directory in which you
1362 would like to create the project file.
1363 After selecting an appropriate directory, press @code{Forward}.
1364
1365 A window will appear with the title
1366 @code{Version Control System Configuration}.
1367 Simply press @code{Forward}.
1368
1369 A window will appear with the title
1370 @code{Please select the source directories for this project}.
1371 The directory that you specified for the project file will be selected
1372 by default as the one to use for sources; simply press @code{Forward}.
1373
1374 A window will appear with the title
1375 @code{Please select the build directory for this project}.
1376 The directory that you specified for the project file will be selected
1377 by default for object files and executables;
1378 simply press @code{Forward}.
1379
1380 A window will appear with the title
1381 @code{Please select the main units for this project}.
1382 You will supply this information later, after creating the source file.
1383 Simply press @code{Forward} for now.
1384
1385 A window will appear with the title
1386 @code{Please select the switches to build the project}.
1387 Press @code{Apply}.  This will create a project file named
1388 @file{sample.prj} in the directory that you had specified.
1389
1390 @item @emph{Creating and saving the source file}
1391
1392 After you create the new project, a GPS window will appear, which is
1393 partitioned into two main sections:
1394
1395 @itemize @bullet
1396 @item
1397 A @emph{Workspace area}, initially greyed out, which you will use for
1398 creating and editing source files
1399
1400 @item
1401 Directly below, a @emph{Messages area}, which initially displays a
1402 ``Welcome'' message.
1403 (If the Messages area is not visible, drag its border upward to expand it.)
1404 @end itemize
1405
1406 @noindent
1407 Select @code{File} on the menu bar, and then the @code{New} command.
1408 The Workspace area will become white, and you can now
1409 enter the source program explicitly.
1410 Type the following text
1411
1412 @smallexample @c ada
1413 @group
1414 with Ada.Text_IO; use Ada.Text_IO;
1415 procedure Hello is
1416 begin
1417   Put_Line("Hello from GPS!");
1418 end Hello;
1419 @end group
1420 @end smallexample
1421
1422 @noindent
1423 Select @code{File}, then @code{Save As}, and enter the source file name
1424 @file{hello.adb}.
1425 The file will be saved in the same directory you specified as the
1426 location of the default project file.
1427
1428 @item @emph{Updating the project file}
1429
1430 You need to add the new source file to the project.
1431 To do this, select
1432 the @code{Project} menu and then @code{Edit project properties}.
1433 Click the @code{Main files} tab on the left, and then the
1434 @code{Add} button.
1435 Choose @file{hello.adb} from the list, and press @code{Open}.
1436 The project settings window will reflect this action.
1437 Click @code{OK}.
1438
1439 @item @emph{Building and running the program}
1440
1441 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1442 and select @file{hello.adb}.
1443 The Messages window will display the resulting invocations of @command{gcc},
1444 @command{gnatbind}, and @command{gnatlink}
1445 (reflecting the default switch settings from the
1446 project file that you created) and then a ``successful compilation/build''
1447 message.
1448
1449 To run the program, choose the @code{Build} menu, then @code{Run}, and
1450 select @command{hello}.
1451 An @emph{Arguments Selection} window will appear.
1452 There are no command line arguments, so just click @code{OK}.
1453
1454 The Messages window will now display the program's output (the string
1455 @code{Hello from GPS}), and at the bottom of the GPS window a status
1456 update is displayed (@code{Run: hello}).
1457 Close the GPS window (or select @code{File}, then @code{Exit}) to
1458 terminate this GPS session.
1459 @end enumerate
1460
1461 @node Simple Debugging with GPS
1462 @subsection Simple Debugging with GPS
1463 @noindent
1464 This section illustrates basic debugging techniques (setting breakpoints,
1465 examining/modifying variables, single stepping).
1466
1467 @enumerate
1468 @item @emph{Opening a project}
1469
1470 Start GPS and select @code{Open existing project}; browse to
1471 specify the project file @file{sample.prj} that you had created in the
1472 earlier example.
1473
1474 @item @emph{Creating a source file}
1475
1476 Select @code{File}, then @code{New}, and type in the following program:
1477
1478 @smallexample @c ada
1479 @group
1480 with Ada.Text_IO; use Ada.Text_IO;
1481 procedure Example is
1482    Line : String (1..80);
1483    N    : Natural;
1484 begin
1485    Put_Line("Type a line of text at each prompt; an empty line to exit");
1486    loop
1487       Put(": ");
1488       Get_Line (Line, N);
1489       Put_Line (Line (1..N) );
1490       exit when N=0;
1491    end loop;
1492 end Example;
1493 @end group
1494 @end smallexample
1495
1496 @noindent
1497 Select @code{File}, then @code{Save as}, and enter the file name
1498 @file{example.adb}.
1499
1500 @item @emph{Updating the project file}
1501
1502 Add @code{Example} as a new main unit for the project:
1503 @enumerate a
1504 @item
1505 Select @code{Project}, then @code{Edit Project Properties}.
1506
1507 @item
1508 Select the @code{Main files} tab, click @code{Add}, then
1509 select the file @file{example.adb} from the list, and
1510 click @code{Open}.
1511 You will see the file name appear in the list of main units
1512
1513 @item
1514 Click @code{OK}
1515 @end enumerate
1516
1517 @item @emph{Building/running the executable}
1518
1519 To build the executable
1520 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1521
1522 Run the program to see its effect (in the Messages area).
1523 Each line that you enter is displayed; an empty line will
1524 cause the loop to exit and the program to terminate.
1525
1526 @item @emph{Debugging the program}
1527
1528 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1529 which are required for debugging, are on by default when you create
1530 a new project.
1531 Thus unless you intentionally remove these settings, you will be able
1532 to debug any program that you develop using GPS.
1533
1534 @enumerate a
1535 @item @emph{Initializing}
1536
1537 Select @code{Debug}, then @code{Initialize}, then @file{example}
1538
1539 @item @emph{Setting a breakpoint}
1540
1541 After performing the initialization step, you will observe a small
1542 icon to the right of each line number.
1543 This serves as a toggle for breakpoints; clicking the icon will
1544 set a breakpoint at the corresponding line (the icon will change to
1545 a red circle with an ``x''), and clicking it again
1546 will remove the breakpoint / reset the icon.
1547
1548 For purposes of this example, set a breakpoint at line 10 (the
1549 statement @code{Put_Line@ (Line@ (1..N));}
1550
1551 @item @emph{Starting program execution}
1552
1553 Select @code{Debug}, then @code{Run}.  When the
1554 @code{Program Arguments} window appears, click @code{OK}.
1555 A console window will appear; enter some line of text,
1556 e.g. @code{abcde}, at the prompt.
1557 The program will pause execution when it gets to the
1558 breakpoint, and the corresponding line is highlighted.
1559
1560 @item @emph{Examining a variable}
1561
1562 Move the mouse over one of the occurrences of the variable @code{N}.
1563 You will see the value (5) displayed, in ``tool tip'' fashion.
1564 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1565 You will see information about @code{N} appear in the @code{Debugger Data}
1566 pane, showing the value as 5.
1567
1568 @item @emph{Assigning a new value to a variable}
1569
1570 Right click on the @code{N} in the @code{Debugger Data} pane, and
1571 select @code{Set value of N}.
1572 When the input window appears, enter the value @code{4} and click
1573 @code{OK}.
1574 This value does not automatically appear in the @code{Debugger Data}
1575 pane; to see it, right click again on the @code{N} in the
1576 @code{Debugger Data} pane and select @code{Update value}.
1577 The new value, 4, will appear in red.
1578
1579 @item @emph{Single stepping}
1580
1581 Select @code{Debug}, then @code{Next}.
1582 This will cause the next statement to be executed, in this case the
1583 call of @code{Put_Line} with the string slice.
1584 Notice in the console window that the displayed string is simply
1585 @code{abcd} and not @code{abcde} which you had entered.
1586 This is because the upper bound of the slice is now 4 rather than 5.
1587
1588 @item @emph{Removing a breakpoint}
1589
1590 Toggle the breakpoint icon at line 10.
1591
1592 @item @emph{Resuming execution from a breakpoint}
1593
1594 Select @code{Debug}, then @code{Continue}.
1595 The program will reach the next iteration of the loop, and
1596 wait for input after displaying the prompt.
1597 This time, just hit the @kbd{Enter} key.
1598 The value of @code{N} will be 0, and the program will terminate.
1599 The console window will disappear.
1600 @end enumerate
1601 @end enumerate
1602
1603 @node Introduction to Glide and GVD
1604 @section Introduction to Glide and GVD
1605 @cindex Glide
1606 @cindex GVD
1607 @noindent
1608 This section describes the main features of Glide,
1609 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1610 the GNU Visual Debugger.
1611 These tools may be present in addition to, or in place of, GPS on some
1612 platforms.
1613 Additional information on Glide and GVD may be found
1614 in the on-line help for these tools.
1615
1616 @menu
1617 * Building a New Program with Glide::
1618 * Simple Debugging with GVD::
1619 * Other Glide Features::
1620 @end menu
1621
1622 @node Building a New Program with Glide
1623 @subsection Building a New Program with Glide
1624 @noindent
1625 The simplest way to invoke Glide is to enter @command{glide}
1626 at the command prompt.  It will generally be useful to issue this
1627 as a background command, thus allowing you to continue using
1628 your command window for other purposes while Glide is running:
1629
1630 @smallexample
1631 $ glide&
1632 @end smallexample
1633
1634 @noindent
1635 Glide will start up with an initial screen displaying the top-level menu items
1636 as well as some other information.  The menu selections are as follows
1637 @itemize @bullet
1638 @item @code{Buffers}
1639 @item @code{Files}
1640 @item @code{Tools}
1641 @item @code{Edit}
1642 @item @code{Search}
1643 @item @code{Mule}
1644 @item @code{Glide}
1645 @item @code{Help}
1646 @end itemize
1647
1648 @noindent
1649 For this introductory example, you will need to create a new Ada source file.
1650 First, select the @code{Files} menu.  This will pop open a menu with around
1651 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1652 Depending on the platform, you may see a pop-up window where you can browse
1653 to an appropriate directory and then enter the file name, or else simply
1654 see a line at the bottom of the Glide window where you can likewise enter
1655 the file name.  Note that in Glide, when you attempt to open a non-existent
1656 file, the effect is to create a file with that name.  For this example enter
1657 @file{hello.adb} as the name of the file.
1658
1659 A new buffer will now appear, occupying the entire Glide window,
1660 with the file name at the top.  The menu selections are slightly different
1661 from the ones you saw on the opening screen; there is an @code{Entities} item,
1662 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1663 the file extension to identify the source language, so @file{adb} indicates
1664 an Ada source file.
1665
1666 You will enter some of the source program lines explicitly,
1667 and use the syntax-oriented template mechanism to enter other lines.
1668 First, type the following text:
1669 @smallexample
1670 with Ada.Text_IO; use Ada.Text_IO;
1671 procedure Hello is
1672 begin
1673 @end smallexample
1674
1675 @noindent
1676 Observe that Glide uses different colors to distinguish reserved words from
1677 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1678 automatically indented in anticipation of declarations.  When you enter
1679 @code{begin}, Glide recognizes that there are no declarations and thus places
1680 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1681 indented, where the statement(s) will be placed.
1682
1683 The main part of the program will be a @code{for} loop.  Instead of entering
1684 the text explicitly, however, use a statement template.  Select the @code{Ada}
1685 item on the top menu bar, move the mouse to the @code{Statements} item,
1686 and you will see a large selection of alternatives.  Choose @code{for loop}.
1687 You will be prompted (at the bottom of the buffer) for a loop name;
1688 simply press the @key{Enter} key since a loop name is not needed.
1689 You should see the beginning of a @code{for} loop appear in the source
1690 program window.  You will now be prompted for the name of the loop variable;
1691 enter a line with the identifier @code{ind} (lower case).  Note that,
1692 by default, Glide capitalizes the name (you can override such behavior
1693 if you wish, although this is outside the scope of this introduction).
1694 Next, Glide prompts you for the loop range; enter a line containing
1695 @code{1..5} and you will see this also appear in the source program,
1696 together with the remaining elements of the @code{for} loop syntax.
1697
1698 Next enter the statement (with an intentional error, a missing semicolon)
1699 that will form the body of the loop:
1700 @smallexample
1701 Put_Line("Hello, World" & Integer'Image(I))
1702 @end smallexample
1703
1704 @noindent
1705 Finally, type @code{end Hello;} as the last line in the program.
1706 Now save the file: choose the @code{File} menu item, and then the
1707 @code{Save buffer} selection.  You will see a message at the bottom
1708 of the buffer confirming that the file has been saved.
1709
1710 You are now ready to attempt to build the program.  Select the @code{Ada}
1711 item from the top menu bar.  Although we could choose simply to compile
1712 the file, we will instead attempt to do a build (which invokes
1713 @command{gnatmake}) since, if the compile is successful, we want to build
1714 an executable.  Thus select @code{Ada build}.  This will fail because of the
1715 compilation error, and you will notice that the Glide window has been split:
1716 the top window contains the source file, and the bottom window contains the
1717 output from the GNAT tools. Glide allows you to navigate from a compilation
1718 error to the source file position corresponding to the error: click the
1719 middle mouse button (or simultaneously press the left and right buttons,
1720 on a two-button mouse) on the diagnostic line in the tool window.  The
1721 focus will shift to the source window, and the cursor will be positioned
1722 on the character at which the error was detected.
1723
1724 Correct the error: type in a semicolon to terminate the statement.
1725 Although you can again save the file explicitly, you can also simply invoke
1726 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1727 This time the build will succeed; the tool output window shows you the
1728 options that are supplied by default.  The GNAT tools' output (e.g.
1729 object and ALI files, executable) will go in the directory from which
1730 Glide was launched.
1731
1732 To execute the program, choose @code{Ada} and then @code{Run}.
1733 You should see the program's output displayed in the bottom window:
1734
1735 @smallexample
1736 Hello, world 1
1737 Hello, world 2
1738 Hello, world 3
1739 Hello, world 4
1740 Hello, world 5
1741 @end smallexample
1742
1743 @node Simple Debugging with GVD
1744 @subsection Simple Debugging with GVD
1745
1746 @noindent
1747 This section describes how to set breakpoints, examine/modify variables,
1748 and step through execution.
1749
1750 In order to enable debugging, you need to pass the @option{-g} switch
1751 to both the compiler and to @command{gnatlink}.  If you are using
1752 the command line, passing @option{-g} to @command{gnatmake} will have
1753 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1754 by issuing the command:
1755
1756 @smallexample
1757 $ gvd hello
1758 @end smallexample
1759
1760 @noindent
1761 If you are using Glide, then @option{-g} is passed to the relevant tools
1762 by default when you do a build.  Start the debugger by selecting the
1763 @code{Ada} menu item, and then @code{Debug}.
1764
1765 GVD comes up in a multi-part window.  One pane shows the names of files
1766 comprising your executable; another pane shows the source code of the current
1767 unit (initially your main subprogram), another pane shows the debugger output
1768 and user interactions, and the fourth pane (the data canvas at the top
1769 of the window) displays data objects that you have selected.
1770
1771 To the left of the source file pane, you will notice green dots adjacent
1772 to some lines.  These are lines for which object code exists and where
1773 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1774 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1775 in a red circle.  Clicking the circle toggles the breakpoint off,
1776 and the red circle is replaced by the green dot.
1777
1778 For this example, set a breakpoint at the statement where @code{Put_Line}
1779 is invoked.
1780
1781 Start program execution by selecting the @code{Run} button on the top menu bar.
1782 (The @code{Start} button will also start your program, but it will
1783 cause program execution to break at the entry to your main subprogram.)
1784 Evidence of reaching the breakpoint will appear: the source file line will be
1785 highlighted, and the debugger interactions pane will display
1786 a relevant message.
1787
1788 You can examine the values of variables in several ways.  Move the mouse
1789 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1790 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1791 and select @code{Display Ind}; a box showing the variable's name and value
1792 will appear in the data canvas.
1793
1794 Although a loop index is a constant with respect to Ada semantics,
1795 you can change its value in the debugger.  Right-click in the box
1796 for @code{Ind}, and select the @code{Set Value of Ind} item.
1797 Enter @code{2} as the new value, and press @command{OK}.
1798 The box for @code{Ind} shows the update.
1799
1800 Press the @code{Step} button on the top menu bar; this will step through
1801 one line of program text (the invocation of @code{Put_Line}), and you can
1802 observe the effect of having modified @code{Ind} since the value displayed
1803 is @code{2}.
1804
1805 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1806 button.  You will see the remaining output lines displayed in the debugger
1807 interaction window, along with a message confirming normal program
1808 termination.
1809
1810 @node Other Glide Features
1811 @subsection Other Glide Features
1812
1813 @noindent
1814 You may have observed that some of the menu selections contain abbreviations;
1815 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1816 These are @emph{shortcut keys} that you can use instead of selecting
1817 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1818 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1819 of selecting @code{Files} and then @code{Open file...}.
1820
1821 To abort a Glide command, type @key{Ctrl-g}.
1822
1823 If you want Glide to start with an existing source file, you can either
1824 launch Glide as above and then open the file via @code{Files} @result{}
1825 @code{Open file...}, or else simply pass the name of the source file
1826 on the command line:
1827
1828 @smallexample
1829 $ glide hello.adb&
1830 @end smallexample
1831
1832 @noindent
1833 While you are using Glide, a number of @emph{buffers} exist.
1834 You create some explicitly; e.g., when you open/create a file.
1835 Others arise as an effect of the commands that you issue; e.g., the buffer
1836 containing the output of the tools invoked during a build.  If a buffer
1837 is hidden, you can bring it into a visible window by first opening
1838 the @code{Buffers} menu and then selecting the desired entry.
1839
1840 If a buffer occupies only part of the Glide screen and you want to expand it
1841 to fill the entire screen, then click in the buffer and then select
1842 @code{Files} @result{} @code{One Window}.
1843
1844 If a window is occupied by one buffer and you want to split the window
1845 to bring up a second buffer, perform the following steps:
1846 @itemize @bullet
1847 @item Select @code{Files} @result{} @code{Split Window};
1848 this will produce two windows each of which holds the original buffer
1849 (these are not copies, but rather different views of the same buffer contents)
1850
1851 @item With the focus in one of the windows,
1852 select the desired buffer from the @code{Buffers} menu
1853 @end itemize
1854
1855 @noindent
1856 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1857 @end ifclear
1858
1859 @node The GNAT Compilation Model
1860 @chapter The GNAT Compilation Model
1861 @cindex GNAT compilation model
1862 @cindex Compilation model
1863
1864 @menu
1865 * Source Representation::
1866 * Foreign Language Representation::
1867 * File Naming Rules::
1868 * Using Other File Names::
1869 * Alternative File Naming Schemes::
1870 * Generating Object Files::
1871 * Source Dependencies::
1872 * The Ada Library Information Files::
1873 * Binding an Ada Program::
1874 * Mixed Language Programming::
1875 * Building Mixed Ada & C++ Programs::
1876 * Comparison between GNAT and C/C++ Compilation Models::
1877 * Comparison between GNAT and Conventional Ada Library Models::
1878 @ifset vms
1879 * Placement of temporary files::
1880 @end ifset
1881 @end menu
1882
1883 @noindent
1884 This chapter describes the compilation model used by GNAT. Although
1885 similar to that used by other languages, such as C and C++, this model
1886 is substantially different from the traditional Ada compilation models,
1887 which are based on a library. The model is initially described without
1888 reference to the library-based model. If you have not previously used an
1889 Ada compiler, you need only read the first part of this chapter. The
1890 last section describes and discusses the differences between the GNAT
1891 model and the traditional Ada compiler models. If you have used other
1892 Ada compilers, this section will help you to understand those
1893 differences, and the advantages of the GNAT model.
1894
1895 @node Source Representation
1896 @section Source Representation
1897 @cindex Latin-1
1898
1899 @noindent
1900 Ada source programs are represented in standard text files, using
1901 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1902 7-bit ASCII set, plus additional characters used for
1903 representing foreign languages (@pxref{Foreign Language Representation}
1904 for support of non-USA character sets). The format effector characters
1905 are represented using their standard ASCII encodings, as follows:
1906
1907 @table @code
1908 @item VT
1909 @findex VT
1910 Vertical tab, @code{16#0B#}
1911
1912 @item HT
1913 @findex HT
1914 Horizontal tab, @code{16#09#}
1915
1916 @item CR
1917 @findex CR
1918 Carriage return, @code{16#0D#}
1919
1920 @item LF
1921 @findex LF
1922 Line feed, @code{16#0A#}
1923
1924 @item FF
1925 @findex FF
1926 Form feed, @code{16#0C#}
1927 @end table
1928
1929 @noindent
1930 Source files are in standard text file format. In addition, GNAT will
1931 recognize a wide variety of stream formats, in which the end of
1932 physical lines is marked by any of the following sequences:
1933 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1934 in accommodating files that are imported from other operating systems.
1935
1936 @cindex End of source file
1937 @cindex Source file, end
1938 @findex SUB
1939 The end of a source file is normally represented by the physical end of
1940 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1941 recognized as signalling the end of the source file. Again, this is
1942 provided for compatibility with other operating systems where this
1943 code is used to represent the end of file.
1944
1945 Each file contains a single Ada compilation unit, including any pragmas
1946 associated with the unit. For example, this means you must place a
1947 package declaration (a package @dfn{spec}) and the corresponding body in
1948 separate files. An Ada @dfn{compilation} (which is a sequence of
1949 compilation units) is represented using a sequence of files. Similarly,
1950 you will place each subunit or child unit in a separate file.
1951
1952 @node Foreign Language Representation
1953 @section Foreign Language Representation
1954
1955 @noindent
1956 GNAT supports the standard character sets defined in Ada 95 as well as
1957 several other non-standard character sets for use in localized versions
1958 of the compiler (@pxref{Character Set Control}).
1959 @menu
1960 * Latin-1::
1961 * Other 8-Bit Codes::
1962 * Wide Character Encodings::
1963 @end menu
1964
1965 @node Latin-1
1966 @subsection Latin-1
1967 @cindex Latin-1
1968
1969 @noindent
1970 The basic character set is Latin-1. This character set is defined by ISO
1971 standard 8859, part 1. The lower half (character codes @code{16#00#}
1972 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1973 is used to represent additional characters. These include extended letters
1974 used by European languages, such as French accents, the vowels with umlauts
1975 used in German, and the extra letter A-ring used in Swedish.
1976
1977 @findex Ada.Characters.Latin_1
1978 For a complete list of Latin-1 codes and their encodings, see the source
1979 file of library unit @code{Ada.Characters.Latin_1} in file
1980 @file{a-chlat1.ads}.
1981 You may use any of these extended characters freely in character or
1982 string literals. In addition, the extended characters that represent
1983 letters can be used in identifiers.
1984
1985 @node Other 8-Bit Codes
1986 @subsection Other 8-Bit Codes
1987
1988 @noindent
1989 GNAT also supports several other 8-bit coding schemes:
1990
1991 @table @asis
1992 @item ISO 8859-2 (Latin-2)
1993 @cindex Latin-2
1994 @cindex ISO 8859-2
1995 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1996 equivalence.
1997
1998 @item ISO 8859-3 (Latin-3)
1999 @cindex Latin-3
2000 @cindex ISO 8859-3
2001 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2002 equivalence.
2003
2004 @item ISO 8859-4 (Latin-4)
2005 @cindex Latin-4
2006 @cindex ISO 8859-4
2007 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2008 equivalence.
2009
2010 @item ISO 8859-5 (Cyrillic)
2011 @cindex ISO 8859-5
2012 @cindex Cyrillic
2013 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2014 lowercase equivalence.
2015
2016 @item ISO 8859-15 (Latin-9)
2017 @cindex ISO 8859-15
2018 @cindex Latin-9
2019 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2020 lowercase equivalence
2021
2022 @item IBM PC (code page 437)
2023 @cindex code page 437
2024 This code page is the normal default for PCs in the U.S. It corresponds
2025 to the original IBM PC character set. This set has some, but not all, of
2026 the extended Latin-1 letters, but these letters do not have the same
2027 encoding as Latin-1. In this mode, these letters are allowed in
2028 identifiers with uppercase and lowercase equivalence.
2029
2030 @item IBM PC (code page 850)
2031 @cindex code page 850
2032 This code page is a modification of 437 extended to include all the
2033 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2034 mode, all these letters are allowed in identifiers with uppercase and
2035 lowercase equivalence.
2036
2037 @item Full Upper 8-bit
2038 Any character in the range 80-FF allowed in identifiers, and all are
2039 considered distinct. In other words, there are no uppercase and lowercase
2040 equivalences in this range. This is useful in conjunction with
2041 certain encoding schemes used for some foreign character sets (e.g.
2042 the typical method of representing Chinese characters on the PC).
2043
2044 @item No Upper-Half
2045 No upper-half characters in the range 80-FF are allowed in identifiers.
2046 This gives Ada 83 compatibility for identifier names.
2047 @end table
2048
2049 @noindent
2050 For precise data on the encodings permitted, and the uppercase and lowercase
2051 equivalences that are recognized, see the file @file{csets.adb} in
2052 the GNAT compiler sources. You will need to obtain a full source release
2053 of GNAT to obtain this file.
2054
2055 @node Wide Character Encodings
2056 @subsection Wide Character Encodings
2057
2058 @noindent
2059 GNAT allows wide character codes to appear in character and string
2060 literals, and also optionally in identifiers, by means of the following
2061 possible encoding schemes:
2062
2063 @table @asis
2064
2065 @item Hex Coding
2066 In this encoding, a wide character is represented by the following five
2067 character sequence:
2068
2069 @smallexample
2070 ESC a b c d
2071 @end smallexample
2072
2073 @noindent
2074 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2075 characters (using uppercase letters) of the wide character code. For
2076 example, ESC A345 is used to represent the wide character with code
2077 @code{16#A345#}.
2078 This scheme is compatible with use of the full Wide_Character set.
2079
2080 @item Upper-Half Coding
2081 @cindex Upper-Half Coding
2082 The wide character with encoding @code{16#abcd#} where the upper bit is on
2083 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2084 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2085 character, but is not required to be in the upper half. This method can
2086 be also used for shift-JIS or EUC, where the internal coding matches the
2087 external coding.
2088
2089 @item Shift JIS Coding
2090 @cindex Shift JIS Coding
2091 A wide character is represented by a two-character sequence,
2092 @code{16#ab#} and
2093 @code{16#cd#}, with the restrictions described for upper-half encoding as
2094 described above. The internal character code is the corresponding JIS
2095 character according to the standard algorithm for Shift-JIS
2096 conversion. Only characters defined in the JIS code set table can be
2097 used with this encoding method.
2098
2099 @item EUC Coding
2100 @cindex EUC Coding
2101 A wide character is represented by a two-character sequence
2102 @code{16#ab#} and
2103 @code{16#cd#}, with both characters being in the upper half. The internal
2104 character code is the corresponding JIS character according to the EUC
2105 encoding algorithm. Only characters defined in the JIS code set table
2106 can be used with this encoding method.
2107
2108 @item UTF-8 Coding
2109 A wide character is represented using
2110 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2111 10646-1/Am.2. Depending on the character value, the representation
2112 is a one, two, or three byte sequence:
2113 @smallexample
2114 @iftex
2115 @leftskip=.7cm
2116 @end iftex
2117 16#0000#-16#007f#: 2#0xxxxxxx#
2118 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2119 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2120
2121 @end smallexample
2122
2123 @noindent
2124 where the xxx bits correspond to the left-padded bits of the
2125 16-bit character value. Note that all lower half ASCII characters
2126 are represented as ASCII bytes and all upper half characters and
2127 other wide characters are represented as sequences of upper-half
2128 (The full UTF-8 scheme allows for encoding 31-bit characters as
2129 6-byte sequences, but in this implementation, all UTF-8 sequences
2130 of four or more bytes length will be treated as illegal).
2131 @item Brackets Coding
2132 In this encoding, a wide character is represented by the following eight
2133 character sequence:
2134
2135 @smallexample
2136 [ " a b c d " ]
2137 @end smallexample
2138
2139 @noindent
2140 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2141 characters (using uppercase letters) of the wide character code. For
2142 example, [``A345''] is used to represent the wide character with code
2143 @code{16#A345#}. It is also possible (though not required) to use the
2144 Brackets coding for upper half characters. For example, the code
2145 @code{16#A3#} can be represented as @code{[``A3'']}.
2146
2147 This scheme is compatible with use of the full Wide_Character set,
2148 and is also the method used for wide character encoding in the standard
2149 ACVC (Ada Compiler Validation Capability) test suite distributions.
2150
2151 @end table
2152
2153 @noindent
2154 Note: Some of these coding schemes do not permit the full use of the
2155 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2156 use of the upper half of the Latin-1 set.
2157
2158 @node File Naming Rules
2159 @section File Naming Rules
2160
2161 @noindent
2162 The default file name is determined by the name of the unit that the
2163 file contains. The name is formed by taking the full expanded name of
2164 the unit and replacing the separating dots with hyphens and using
2165 ^lowercase^uppercase^ for all letters.
2166
2167 An exception arises if the file name generated by the above rules starts
2168 with one of the characters
2169 @ifset vms
2170 A,G,I, or S,
2171 @end ifset
2172 @ifclear vms
2173 a,g,i, or s,
2174 @end ifclear
2175 and the second character is a
2176 minus. In this case, the character ^tilde^dollar sign^ is used in place
2177 of the minus. The reason for this special rule is to avoid clashes with
2178 the standard names for child units of the packages System, Ada,
2179 Interfaces, and GNAT, which use the prefixes
2180 @ifset vms
2181 S- A- I- and G-
2182 @end ifset
2183 @ifclear vms
2184 s- a- i- and g-
2185 @end ifclear
2186 respectively.
2187
2188 The file extension is @file{.ads} for a spec and
2189 @file{.adb} for a body. The following list shows some
2190 examples of these rules.
2191
2192 @table @file
2193 @item main.ads
2194 Main (spec)
2195 @item main.adb
2196 Main (body)
2197 @item arith_functions.ads
2198 Arith_Functions (package spec)
2199 @item arith_functions.adb
2200 Arith_Functions (package body)
2201 @item func-spec.ads
2202 Func.Spec (child package spec)
2203 @item func-spec.adb
2204 Func.Spec (child package body)
2205 @item main-sub.adb
2206 Sub (subunit of Main)
2207 @item ^a~bad.adb^A$BAD.ADB^
2208 A.Bad (child package body)
2209 @end table
2210
2211 @noindent
2212 Following these rules can result in excessively long
2213 file names if corresponding
2214 unit names are long (for example, if child units or subunits are
2215 heavily nested). An option is available to shorten such long file names
2216 (called file name ``krunching''). This may be particularly useful when
2217 programs being developed with GNAT are to be used on operating systems
2218 with limited file name lengths. @xref{Using gnatkr}.
2219
2220 Of course, no file shortening algorithm can guarantee uniqueness over
2221 all possible unit names; if file name krunching is used, it is your
2222 responsibility to ensure no name clashes occur. Alternatively you
2223 can specify the exact file names that you want used, as described
2224 in the next section. Finally, if your Ada programs are migrating from a
2225 compiler with a different naming convention, you can use the gnatchop
2226 utility to produce source files that follow the GNAT naming conventions.
2227 (For details @pxref{Renaming Files Using gnatchop}.)
2228
2229 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2230 systems, case is not significant. So for example on @code{Windows XP}
2231 if the canonical name is @code{main-sub.adb}, you can use the file name
2232 @code{Main-Sub.adb} instead. However, case is significant for other
2233 operating systems, so for example, if you want to use other than
2234 canonically cased file names on a Unix system, you need to follow
2235 the procedures described in the next section.
2236
2237 @node Using Other File Names
2238 @section Using Other File Names
2239 @cindex File names
2240
2241 @noindent
2242 In the previous section, we have described the default rules used by
2243 GNAT to determine the file name in which a given unit resides. It is
2244 often convenient to follow these default rules, and if you follow them,
2245 the compiler knows without being explicitly told where to find all
2246 the files it needs.
2247
2248 However, in some cases, particularly when a program is imported from
2249 another Ada compiler environment, it may be more convenient for the
2250 programmer to specify which file names contain which units. GNAT allows
2251 arbitrary file names to be used by means of the Source_File_Name pragma.
2252 The form of this pragma is as shown in the following examples:
2253 @cindex Source_File_Name pragma
2254
2255 @smallexample @c ada
2256 @cartouche
2257 pragma Source_File_Name (My_Utilities.Stacks,
2258   Spec_File_Name => "myutilst_a.ada");
2259 pragma Source_File_name (My_Utilities.Stacks,
2260   Body_File_Name => "myutilst.ada");
2261 @end cartouche
2262 @end smallexample
2263
2264 @noindent
2265 As shown in this example, the first argument for the pragma is the unit
2266 name (in this example a child unit). The second argument has the form
2267 of a named association. The identifier
2268 indicates whether the file name is for a spec or a body;
2269 the file name itself is given by a string literal.
2270
2271 The source file name pragma is a configuration pragma, which means that
2272 normally it will be placed in the @file{gnat.adc}
2273 file used to hold configuration
2274 pragmas that apply to a complete compilation environment.
2275 For more details on how the @file{gnat.adc} file is created and used
2276 see @ref{Handling of Configuration Pragmas}.
2277 @cindex @file{gnat.adc}
2278
2279 @ifclear vms
2280 GNAT allows completely arbitrary file names to be specified using the
2281 source file name pragma. However, if the file name specified has an
2282 extension other than @file{.ads} or @file{.adb} it is necessary to use
2283 a special syntax when compiling the file. The name in this case must be
2284 preceded by the special sequence @code{-x} followed by a space and the name
2285 of the language, here @code{ada}, as in:
2286
2287 @smallexample
2288 $ gcc -c -x ada peculiar_file_name.sim
2289 @end smallexample
2290 @end ifclear
2291
2292 @noindent
2293 @command{gnatmake} handles non-standard file names in the usual manner (the
2294 non-standard file name for the main program is simply used as the
2295 argument to gnatmake). Note that if the extension is also non-standard,
2296 then it must be included in the gnatmake command, it may not be omitted.
2297
2298 @node Alternative File Naming Schemes
2299 @section Alternative File Naming Schemes
2300 @cindex File naming schemes, alternative
2301 @cindex File names
2302
2303 In the previous section, we described the use of the @code{Source_File_Name}
2304 pragma to allow arbitrary names to be assigned to individual source files.
2305 However, this approach requires one pragma for each file, and especially in
2306 large systems can result in very long @file{gnat.adc} files, and also create
2307 a maintenance problem.
2308
2309 GNAT also provides a facility for specifying systematic file naming schemes
2310 other than the standard default naming scheme previously described. An
2311 alternative scheme for naming is specified by the use of
2312 @code{Source_File_Name} pragmas having the following format:
2313 @cindex Source_File_Name pragma
2314
2315 @smallexample @c ada
2316 pragma Source_File_Name (
2317    Spec_File_Name  => FILE_NAME_PATTERN
2318  [,Casing          => CASING_SPEC]
2319  [,Dot_Replacement => STRING_LITERAL]);
2320
2321 pragma Source_File_Name (
2322    Body_File_Name  => FILE_NAME_PATTERN
2323  [,Casing          => CASING_SPEC]
2324  [,Dot_Replacement => STRING_LITERAL]);
2325
2326 pragma Source_File_Name (
2327    Subunit_File_Name  => FILE_NAME_PATTERN
2328  [,Casing             => CASING_SPEC]
2329  [,Dot_Replacement    => STRING_LITERAL]);
2330
2331 FILE_NAME_PATTERN ::= STRING_LITERAL
2332 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2333 @end smallexample
2334
2335 @noindent
2336 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2337 It contains a single asterisk character, and the unit name is substituted
2338 systematically for this asterisk. The optional parameter
2339 @code{Casing} indicates
2340 whether the unit name is to be all upper-case letters, all lower-case letters,
2341 or mixed-case. If no
2342 @code{Casing} parameter is used, then the default is all
2343 ^lower-case^upper-case^.
2344
2345 The optional @code{Dot_Replacement} string is used to replace any periods
2346 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2347 argument is used then separating dots appear unchanged in the resulting
2348 file name.
2349 Although the above syntax indicates that the
2350 @code{Casing} argument must appear
2351 before the @code{Dot_Replacement} argument, but it
2352 is also permissible to write these arguments in the opposite order.
2353
2354 As indicated, it is possible to specify different naming schemes for
2355 bodies, specs, and subunits. Quite often the rule for subunits is the
2356 same as the rule for bodies, in which case, there is no need to give
2357 a separate @code{Subunit_File_Name} rule, and in this case the
2358 @code{Body_File_name} rule is used for subunits as well.
2359
2360 The separate rule for subunits can also be used to implement the rather
2361 unusual case of a compilation environment (e.g. a single directory) which
2362 contains a subunit and a child unit with the same unit name. Although
2363 both units cannot appear in the same partition, the Ada Reference Manual
2364 allows (but does not require) the possibility of the two units coexisting
2365 in the same environment.
2366
2367 The file name translation works in the following steps:
2368
2369 @itemize @bullet
2370
2371 @item
2372 If there is a specific @code{Source_File_Name} pragma for the given unit,
2373 then this is always used, and any general pattern rules are ignored.
2374
2375 @item
2376 If there is a pattern type @code{Source_File_Name} pragma that applies to
2377 the unit, then the resulting file name will be used if the file exists. If
2378 more than one pattern matches, the latest one will be tried first, and the
2379 first attempt resulting in a reference to a file that exists will be used.
2380
2381 @item
2382 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2383 for which the corresponding file exists, then the standard GNAT default
2384 naming rules are used.
2385
2386 @end itemize
2387
2388 @noindent
2389 As an example of the use of this mechanism, consider a commonly used scheme
2390 in which file names are all lower case, with separating periods copied
2391 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2392 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2393 two pragmas appear:
2394
2395 @smallexample @c ada
2396 pragma Source_File_Name
2397   (Spec_File_Name => "*.1.ada");
2398 pragma Source_File_Name
2399   (Body_File_Name => "*.2.ada");
2400 @end smallexample
2401
2402 @noindent
2403 The default GNAT scheme is actually implemented by providing the following
2404 default pragmas internally:
2405
2406 @smallexample @c ada
2407 pragma Source_File_Name
2408   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2409 pragma Source_File_Name
2410   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2411 @end smallexample
2412
2413 @noindent
2414 Our final example implements a scheme typically used with one of the
2415 Ada 83 compilers, where the separator character for subunits was ``__''
2416 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2417 by adding @file{.ADA}, and subunits by
2418 adding @file{.SEP}. All file names were
2419 upper case. Child units were not present of course since this was an
2420 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2421 the same double underscore separator for child units.
2422
2423 @smallexample @c ada
2424 pragma Source_File_Name
2425   (Spec_File_Name => "*_.ADA",
2426    Dot_Replacement => "__",
2427    Casing = Uppercase);
2428 pragma Source_File_Name
2429   (Body_File_Name => "*.ADA",
2430    Dot_Replacement => "__",
2431    Casing = Uppercase);
2432 pragma Source_File_Name
2433   (Subunit_File_Name => "*.SEP",
2434    Dot_Replacement => "__",
2435    Casing = Uppercase);
2436 @end smallexample
2437
2438 @node Generating Object Files
2439 @section Generating Object Files
2440
2441 @noindent
2442 An Ada program consists of a set of source files, and the first step in
2443 compiling the program is to generate the corresponding object files.
2444 These are generated by compiling a subset of these source files.
2445 The files you need to compile are the following:
2446
2447 @itemize @bullet
2448 @item
2449 If a package spec has no body, compile the package spec to produce the
2450 object file for the package.
2451
2452 @item
2453 If a package has both a spec and a body, compile the body to produce the
2454 object file for the package. The source file for the package spec need
2455 not be compiled in this case because there is only one object file, which
2456 contains the code for both the spec and body of the package.
2457
2458 @item
2459 For a subprogram, compile the subprogram body to produce the object file
2460 for the subprogram. The spec, if one is present, is as usual in a
2461 separate file, and need not be compiled.
2462
2463 @item
2464 @cindex Subunits
2465 In the case of subunits, only compile the parent unit. A single object
2466 file is generated for the entire subunit tree, which includes all the
2467 subunits.
2468
2469 @item
2470 Compile child units independently of their parent units
2471 (though, of course, the spec of all the ancestor unit must be present in order
2472 to compile a child unit).
2473
2474 @item
2475 @cindex Generics
2476 Compile generic units in the same manner as any other units. The object
2477 files in this case are small dummy files that contain at most the
2478 flag used for elaboration checking. This is because GNAT always handles generic
2479 instantiation by means of macro expansion. However, it is still necessary to
2480 compile generic units, for dependency checking and elaboration purposes.
2481 @end itemize
2482
2483 @noindent
2484 The preceding rules describe the set of files that must be compiled to
2485 generate the object files for a program. Each object file has the same
2486 name as the corresponding source file, except that the extension is
2487 @file{.o} as usual.
2488
2489 You may wish to compile other files for the purpose of checking their
2490 syntactic and semantic correctness. For example, in the case where a
2491 package has a separate spec and body, you would not normally compile the
2492 spec. However, it is convenient in practice to compile the spec to make
2493 sure it is error-free before compiling clients of this spec, because such
2494 compilations will fail if there is an error in the spec.
2495
2496 GNAT provides an option for compiling such files purely for the
2497 purposes of checking correctness; such compilations are not required as
2498 part of the process of building a program. To compile a file in this
2499 checking mode, use the @option{-gnatc} switch.
2500
2501 @node Source Dependencies
2502 @section Source Dependencies
2503
2504 @noindent
2505 A given object file clearly depends on the source file which is compiled
2506 to produce it. Here we are using @dfn{depends} in the sense of a typical
2507 @code{make} utility; in other words, an object file depends on a source
2508 file if changes to the source file require the object file to be
2509 recompiled.
2510 In addition to this basic dependency, a given object may depend on
2511 additional source files as follows:
2512
2513 @itemize @bullet
2514 @item
2515 If a file being compiled @code{with}'s a unit @var{X}, the object file
2516 depends on the file containing the spec of unit @var{X}. This includes
2517 files that are @code{with}'ed implicitly either because they are parents
2518 of @code{with}'ed child units or they are run-time units required by the
2519 language constructs used in a particular unit.
2520
2521 @item
2522 If a file being compiled instantiates a library level generic unit, the
2523 object file depends on both the spec and body files for this generic
2524 unit.
2525
2526 @item
2527 If a file being compiled instantiates a generic unit defined within a
2528 package, the object file depends on the body file for the package as
2529 well as the spec file.
2530
2531 @item
2532 @findex Inline
2533 @cindex @option{-gnatn} switch
2534 If a file being compiled contains a call to a subprogram for which
2535 pragma @code{Inline} applies and inlining is activated with the
2536 @option{-gnatn} switch, the object file depends on the file containing the
2537 body of this subprogram as well as on the file containing the spec. Note
2538 that for inlining to actually occur as a result of the use of this switch,
2539 it is necessary to compile in optimizing mode.
2540
2541 @cindex @option{-gnatN} switch
2542 The use of @option{-gnatN} activates a more extensive inlining optimization
2543 that is performed by the front end of the compiler. This inlining does
2544 not require that the code generation be optimized. Like @option{-gnatn},
2545 the use of this switch generates additional dependencies.
2546 Note that
2547 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2548 to specify both options.
2549
2550 @item
2551 If an object file O  depends on the proper body of a subunit through inlining
2552 or instantiation, it depends on the parent unit of the subunit. This means that
2553 any modification of the parent unit or one of its subunits affects the
2554 compilation of O.
2555
2556 @item
2557 The object file for a parent unit depends on all its subunit body files.
2558
2559 @item
2560 The previous two rules meant that for purposes of computing dependencies and
2561 recompilation, a body and all its subunits are treated as an indivisible whole.
2562
2563 @noindent
2564 These rules are applied transitively: if unit @code{A} @code{with}'s
2565 unit @code{B}, whose elaboration calls an inlined procedure in package
2566 @code{C}, the object file for unit @code{A} will depend on the body of
2567 @code{C}, in file @file{c.adb}.
2568
2569 The set of dependent files described by these rules includes all the
2570 files on which the unit is semantically dependent, as described in the
2571 Ada 95 Language Reference Manual. However, it is a superset of what the
2572 ARM describes, because it includes generic, inline, and subunit dependencies.
2573
2574 An object file must be recreated by recompiling the corresponding source
2575 file if any of the source files on which it depends are modified. For
2576 example, if the @code{make} utility is used to control compilation,
2577 the rule for an Ada object file must mention all the source files on
2578 which the object file depends, according to the above definition.
2579 The determination of the necessary
2580 recompilations is done automatically when one uses @command{gnatmake}.
2581 @end itemize
2582
2583 @node The Ada Library Information Files
2584 @section The Ada Library Information Files
2585 @cindex Ada Library Information files
2586 @cindex @file{ALI} files
2587
2588 @noindent
2589 Each compilation actually generates two output files. The first of these
2590 is the normal object file that has a @file{.o} extension. The second is a
2591 text file containing full dependency information. It has the same
2592 name as the source file, but an @file{.ali} extension.
2593 This file is known as the Ada Library Information (@file{ALI}) file.
2594 The following information is contained in the @file{ALI} file.
2595
2596 @itemize @bullet
2597 @item
2598 Version information (indicates which version of GNAT was used to compile
2599 the unit(s) in question)
2600
2601 @item
2602 Main program information (including priority and time slice settings,
2603 as well as the wide character encoding used during compilation).
2604
2605 @item
2606 List of arguments used in the @command{gcc} command for the compilation
2607
2608 @item
2609 Attributes of the unit, including configuration pragmas used, an indication
2610 of whether the compilation was successful, exception model used etc.
2611
2612 @item
2613 A list of relevant restrictions applying to the unit (used for consistency)
2614 checking.
2615
2616 @item
2617 Categorization information (e.g. use of pragma @code{Pure}).
2618
2619 @item
2620 Information on all @code{with}'ed units, including presence of
2621 @code{Elaborate} or @code{Elaborate_All} pragmas.
2622
2623 @item
2624 Information from any @code{Linker_Options} pragmas used in the unit
2625
2626 @item
2627 Information on the use of @code{Body_Version} or @code{Version}
2628 attributes in the unit.
2629
2630 @item
2631 Dependency information. This is a list of files, together with
2632 time stamp and checksum information. These are files on which
2633 the unit depends in the sense that recompilation is required
2634 if any of these units are modified.
2635
2636 @item
2637 Cross-reference data. Contains information on all entities referenced
2638 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2639 provide cross-reference information.
2640
2641 @end itemize
2642
2643 @noindent
2644 For a full detailed description of the format of the @file{ALI} file,
2645 see the source of the body of unit @code{Lib.Writ}, contained in file
2646 @file{lib-writ.adb} in the GNAT compiler sources.
2647
2648 @node Binding an Ada Program
2649 @section Binding an Ada Program
2650
2651 @noindent
2652 When using languages such as C and C++, once the source files have been
2653 compiled the only remaining step in building an executable program
2654 is linking the object modules together. This means that it is possible to
2655 link an inconsistent version of a program, in which two units have
2656 included different versions of the same header.
2657
2658 The rules of Ada do not permit such an inconsistent program to be built.
2659 For example, if two clients have different versions of the same package,
2660 it is illegal to build a program containing these two clients.
2661 These rules are enforced by the GNAT binder, which also determines an
2662 elaboration order consistent with the Ada rules.
2663
2664 The GNAT binder is run after all the object files for a program have
2665 been created. It is given the name of the main program unit, and from
2666 this it determines the set of units required by the program, by reading the
2667 corresponding ALI files. It generates error messages if the program is
2668 inconsistent or if no valid order of elaboration exists.
2669
2670 If no errors are detected, the binder produces a main program, in Ada by
2671 default, that contains calls to the elaboration procedures of those
2672 compilation unit that require them, followed by
2673 a call to the main program. This Ada program is compiled to generate the
2674 object file for the main program. The name of
2675 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2676 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2677 main program unit.
2678
2679 Finally, the linker is used to build the resulting executable program,
2680 using the object from the main program from the bind step as well as the
2681 object files for the Ada units of the program.
2682
2683 @node Mixed Language Programming
2684 @section Mixed Language Programming
2685 @cindex Mixed Language Programming
2686
2687 @noindent
2688 This section describes how to develop a mixed-language program,
2689 specifically one that comprises units in both Ada and C.
2690
2691 @menu
2692 * Interfacing to C::
2693 * Calling Conventions::
2694 @end menu
2695
2696 @node Interfacing to C
2697 @subsection Interfacing to C
2698 @noindent
2699 Interfacing Ada with a foreign language such as C involves using
2700 compiler directives to import and/or export entity definitions in each
2701 language---using @code{extern} statements in C, for instance, and the
2702 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2703 a full treatment of these topics, read Appendix B, section 1 of the Ada
2704 95 Language Reference Manual.
2705
2706 There are two ways to build a program using GNAT that contains some Ada
2707 sources and some foreign language sources, depending on whether or not
2708 the main subprogram is written in Ada.  Here is a source example with
2709 the main subprogram in Ada:
2710
2711 @smallexample
2712 /* file1.c */
2713 #include <stdio.h>
2714
2715 void print_num (int num)
2716 @{
2717   printf ("num is %d.\n", num);
2718   return;
2719 @}
2720
2721 /* file2.c */
2722
2723 /* num_from_Ada is declared in my_main.adb */
2724 extern int num_from_Ada;
2725
2726 int get_num (void)
2727 @{
2728   return num_from_Ada;
2729 @}
2730 @end smallexample
2731
2732 @smallexample @c ada
2733 --  my_main.adb
2734 procedure My_Main is
2735
2736    --  Declare then export an Integer entity called num_from_Ada
2737    My_Num : Integer := 10;
2738    pragma Export (C, My_Num, "num_from_Ada");
2739
2740    --  Declare an Ada function spec for Get_Num, then use
2741    --  C function get_num for the implementation.
2742    function Get_Num return Integer;
2743    pragma Import (C, Get_Num, "get_num");
2744
2745    --  Declare an Ada procedure spec for Print_Num, then use
2746    --  C function print_num for the implementation.
2747    procedure Print_Num (Num : Integer);
2748    pragma Import (C, Print_Num, "print_num");
2749
2750 begin
2751    Print_Num (Get_Num);
2752 end My_Main;
2753 @end smallexample
2754
2755 @enumerate
2756 @item
2757 To build this example, first compile the foreign language files to
2758 generate object files:
2759 @smallexample
2760 gcc -c file1.c
2761 gcc -c file2.c
2762 @end smallexample
2763
2764 @item
2765 Then, compile the Ada units to produce a set of object files and ALI
2766 files:
2767 @smallexample
2768 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2769 @end smallexample
2770
2771 @item
2772 Run the Ada binder on the Ada main program:
2773 @smallexample
2774 gnatbind my_main.ali
2775 @end smallexample
2776
2777 @item
2778 Link the Ada main program, the Ada objects and the other language
2779 objects:
2780 @smallexample
2781 gnatlink my_main.ali file1.o file2.o
2782 @end smallexample
2783 @end enumerate
2784
2785 The last three steps can be grouped in a single command:
2786 @smallexample
2787 gnatmake my_main.adb -largs file1.o file2.o
2788 @end smallexample
2789
2790 @cindex Binder output file
2791 @noindent
2792 If the main program is in a language other than Ada, then you may have
2793 more than one entry point into the Ada subsystem. You must use a special
2794 binder option to generate callable routines that initialize and
2795 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2796 Calls to the initialization and finalization routines must be inserted
2797 in the main program, or some other appropriate point in the code. The
2798 call to initialize the Ada units must occur before the first Ada
2799 subprogram is called, and the call to finalize the Ada units must occur
2800 after the last Ada subprogram returns. The binder will place the
2801 initialization and finalization subprograms into the
2802 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2803 sources.  To illustrate, we have the following example:
2804
2805 @smallexample
2806 /* main.c */
2807 extern void adainit (void);
2808 extern void adafinal (void);
2809 extern int add (int, int);
2810 extern int sub (int, int);
2811
2812 int main (int argc, char *argv[])
2813 @{
2814   int a = 21, b = 7;
2815
2816   adainit();
2817
2818   /* Should print "21 + 7 = 28" */
2819   printf ("%d + %d = %d\n", a, b, add (a, b));
2820   /* Should print "21 - 7 = 14" */
2821   printf ("%d - %d = %d\n", a, b, sub (a, b));
2822
2823   adafinal();
2824 @}
2825 @end smallexample
2826
2827 @smallexample @c ada
2828 --  unit1.ads
2829 package Unit1 is
2830    function Add (A, B : Integer) return Integer;
2831    pragma Export (C, Add, "add");
2832 end Unit1;
2833
2834 --  unit1.adb
2835 package body Unit1 is
2836    function Add (A, B : Integer) return Integer is
2837    begin
2838       return A + B;
2839    end Add;
2840 end Unit1;
2841
2842 --  unit2.ads
2843 package Unit2 is
2844    function Sub (A, B : Integer) return Integer;
2845    pragma Export (C, Sub, "sub");
2846 end Unit2;
2847
2848 --  unit2.adb
2849 package body Unit2 is
2850    function Sub (A, B : Integer) return Integer is
2851    begin
2852       return A - B;
2853    end Sub;
2854 end Unit2;
2855 @end smallexample
2856
2857 @enumerate
2858 @item
2859 The build procedure for this application is similar to the last
2860 example's.  First, compile the foreign language files to generate object
2861 files:
2862 @smallexample
2863 ^gcc -c main.c^gcc -c main.c^
2864 @end smallexample
2865
2866 @item
2867 Next, compile the Ada units to produce a set of object files and ALI
2868 files:
2869 @smallexample
2870 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2871 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2872 @end smallexample
2873
2874 @item
2875 Run the Ada binder on every generated ALI file.  Make sure to use the
2876 @option{-n} option to specify a foreign main program:
2877 @smallexample
2878 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2879 @end smallexample
2880
2881 @item
2882 Link the Ada main program, the Ada objects and the foreign language
2883 objects. You need only list the last ALI file here:
2884 @smallexample
2885 gnatlink unit2.ali main.o -o exec_file
2886 @end smallexample
2887
2888 This procedure yields a binary executable called @file{exec_file}.
2889 @end enumerate
2890
2891 @node Calling Conventions
2892 @subsection Calling Conventions
2893 @cindex Foreign Languages
2894 @cindex Calling Conventions
2895 GNAT follows standard calling sequence conventions and will thus interface
2896 to any other language that also follows these conventions. The following
2897 Convention identifiers are recognized by GNAT:
2898
2899 @table @code
2900 @cindex Interfacing to Ada
2901 @cindex Other Ada compilers
2902 @cindex Convention Ada
2903 @item Ada
2904 This indicates that the standard Ada calling sequence will be
2905 used and all Ada data items may be passed without any limitations in the
2906 case where GNAT is used to generate both the caller and callee. It is also
2907 possible to mix GNAT generated code and code generated by another Ada
2908 compiler. In this case, the data types should be restricted to simple
2909 cases, including primitive types. Whether complex data types can be passed
2910 depends on the situation. Probably it is safe to pass simple arrays, such
2911 as arrays of integers or floats. Records may or may not work, depending
2912 on whether both compilers lay them out identically. Complex structures
2913 involving variant records, access parameters, tasks, or protected types,
2914 are unlikely to be able to be passed.
2915
2916 Note that in the case of GNAT running
2917 on a platform that supports DEC Ada 83, a higher degree of compatibility
2918 can be guaranteed, and in particular records are layed out in an identical
2919 manner in the two compilers. Note also that if output from two different
2920 compilers is mixed, the program is responsible for dealing with elaboration
2921 issues. Probably the safest approach is to write the main program in the
2922 version of Ada other than GNAT, so that it takes care of its own elaboration
2923 requirements, and then call the GNAT-generated adainit procedure to ensure
2924 elaboration of the GNAT components. Consult the documentation of the other
2925 Ada compiler for further details on elaboration.
2926
2927 However, it is not possible to mix the tasking run time of GNAT and
2928 DEC Ada 83, All the tasking operations must either be entirely within
2929 GNAT compiled sections of the program, or entirely within DEC Ada 83
2930 compiled sections of the program.
2931
2932 @cindex Interfacing to Assembly
2933 @cindex Convention Assembler
2934 @item Assembler
2935 Specifies assembler as the convention. In practice this has the
2936 same effect as convention Ada (but is not equivalent in the sense of being
2937 considered the same convention).
2938
2939 @cindex Convention Asm
2940 @findex Asm
2941 @item Asm
2942 Equivalent to Assembler.
2943
2944 @cindex Interfacing to COBOL
2945 @cindex Convention COBOL
2946 @findex COBOL
2947 @item COBOL
2948 Data will be passed according to the conventions described
2949 in section B.4 of the Ada 95 Reference Manual.
2950
2951 @findex C
2952 @cindex Interfacing to C
2953 @cindex Convention C
2954 @item C
2955 Data will be passed according to the conventions described
2956 in section B.3 of the Ada 95 Reference Manual.
2957
2958 @findex C varargs function
2959 @cindex Intefacing to C varargs function
2960 @cindex varargs function interfaces
2961 @item C varargs function
2962 In C, @code{varargs} allows a function to take a variable number of
2963 arguments. There is no direct equivalent in this to Ada. One
2964 approach that can be used is to create a C wrapper for each
2965 different profile and then interface to this C wrapper. For
2966 example, to print an @code{int} value using @code{printf},
2967 create a C function @code{printfi} that takes two arguments, a
2968 pointer to a string and an int, and calls @code{printf}.
2969 Then in the Ada program, use pragma @code{Import} to
2970 interface to printfi.
2971
2972 It may work on some platforms to directly interface to
2973 a @code{varargs} function by providing a specific Ada profile
2974 for a a particular call. However, this does not work on
2975 all platforms, since there is no guarantee that the
2976 calling sequence for a two argument normal C function
2977 is the same as for calling a @code{varargs} C function with
2978 the same two arguments.
2979
2980 @cindex Convention Default
2981 @findex Default
2982 @item Default
2983 Equivalent to C.
2984
2985 @cindex Convention External
2986 @findex External
2987 @item External
2988 Equivalent to C.
2989
2990 @findex C++
2991 @cindex Interfacing to C++
2992 @cindex Convention C++
2993 @item CPP
2994 This stands for C++. For most purposes this is identical to C.
2995 See the separate description of the specialized GNAT pragmas relating to
2996 C++ interfacing for further details.
2997
2998 @findex Fortran
2999 @cindex Interfacing to Fortran
3000 @cindex Convention Fortran
3001 @item Fortran
3002 Data will be passed according to the conventions described
3003 in section B.5 of the Ada 95 Reference Manual.
3004
3005 @item Intrinsic
3006 This applies to an intrinsic operation, as defined in the Ada 95
3007 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3008 this means that the body of the subprogram is provided by the compiler itself,
3009 usually by means of an efficient code sequence, and that the user does not
3010 supply an explicit body for it. In an application program, the pragma can
3011 only be applied to the following two sets of names, which the GNAT compiler
3012 recognizes.
3013
3014 @itemize @bullet
3015 @item
3016 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3017 Arithmetic.  The corresponding subprogram declaration must have
3018 two formal parameters. The
3019 first one must be a signed integer type or a modular type with a binary
3020 modulus, and the second parameter must be of type Natural.
3021 The return type must be the same as the type of the first argument. The size
3022 of this type can only be 8, 16, 32, or 64.
3023 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3024 The corresponding operator declaration must have parameters and result type
3025 that have the same root numeric type (for example, all three are long_float
3026 types). This simplifies the definition of operations that use type checking
3027 to perform dimensional checks:
3028
3029 @smallexample @c ada
3030 type Distance is new Long_Float;
3031 type Time     is new Long_Float;
3032 type Velocity is new Long_Float;
3033 function "/" (D : Distance; T : Time)
3034   return Velocity;
3035 pragma Import (Intrinsic, "/");
3036 @end smallexample
3037
3038 @noindent
3039 This common idiom is often programmed with a generic definition and an
3040 explicit body. The pragma makes it simpler to introduce such declarations.
3041 It incurs no overhead in compilation time or code size, because it is
3042 implemented as a single machine instruction.
3043 @end itemize
3044 @noindent
3045
3046 @ifset unw
3047 @findex Stdcall
3048 @cindex Convention Stdcall
3049 @item Stdcall
3050 This is relevant only to NT/Win95 implementations of GNAT,
3051 and specifies that the Stdcall calling sequence will be used, as defined
3052 by the NT API. Nevertheless, to ease building cross-platform bindings this
3053 convention will be handled as a C calling convention on non Windows
3054 platforms.
3055
3056 @findex DLL
3057 @cindex Convention DLL
3058 @item DLL
3059 This is equivalent to Stdcall.
3060
3061 @findex Win32
3062 @cindex Convention Win32
3063 @item Win32
3064 This is equivalent to Stdcall.
3065 @end ifset
3066
3067 @findex Stubbed
3068 @cindex Convention Stubbed
3069 @item Stubbed
3070 This is a special convention that indicates that the compiler
3071 should provide a stub body that raises @code{Program_Error}.
3072 @end table
3073
3074 @noindent
3075 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3076 that can be used to parametrize conventions and allow additional synonyms
3077 to be specified. For example if you have legacy code in which the convention
3078 identifier Fortran77 was used for Fortran, you can use the configuration
3079 pragma:
3080
3081 @smallexample @c ada
3082 pragma Convention_Identifier (Fortran77, Fortran);
3083 @end smallexample
3084
3085 @noindent
3086 And from now on the identifier Fortran77 may be used as a convention
3087 identifier (for example in an @code{Import} pragma) with the same
3088 meaning as Fortran.
3089
3090 @node Building Mixed Ada & C++ Programs
3091 @section Building Mixed Ada & C++ Programs
3092
3093 @noindent
3094 A programmer inexperienced with mixed-language development may find that
3095 building an application containing both Ada and C++ code can be a
3096 challenge. As a matter of fact, interfacing with C++ has not been
3097 standardized in the Ada 95 Reference Manual due to the immaturity of --
3098 and lack of standards for -- C++ at the time. This section gives a few
3099 hints that should make this task easier. The first section addresses
3100 the differences regarding interfacing with C. The second section
3101 looks into the delicate problem of linking the complete application from
3102 its Ada and C++ parts. The last section gives some hints on how the GNAT
3103 run time can be adapted in order to allow inter-language dispatching
3104 with a new C++ compiler.
3105
3106 @menu
3107 * Interfacing to C++::
3108 * Linking a Mixed C++ & Ada Program::
3109 * A Simple Example::
3110 * Adapting the Run Time to a New C++ Compiler::
3111 @end menu
3112
3113 @node Interfacing to C++
3114 @subsection Interfacing to C++
3115
3116 @noindent
3117 GNAT supports interfacing with C++ compilers generating code that is
3118 compatible with the standard Application Binary Interface of the given
3119 platform.
3120
3121 @noindent
3122 Interfacing can be done at 3 levels: simple data, subprograms, and
3123 classes. In the first two cases, GNAT offers a specific @var{Convention
3124 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3125 the names of subprograms, and currently, GNAT does not provide any help
3126 to solve the demangling problem. This problem can be addressed in two
3127 ways:
3128 @itemize @bullet
3129 @item
3130 by modifying the C++ code in order to force a C convention using
3131 the @code{extern "C"} syntax.
3132
3133 @item
3134 by figuring out the mangled name and use it as the Link_Name argument of
3135 the pragma import.
3136 @end itemize
3137
3138 @noindent
3139 Interfacing at the class level can be achieved by using the GNAT specific
3140 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3141 Reference Manual for additional information.
3142
3143 @node Linking a Mixed C++ & Ada Program
3144 @subsection Linking a Mixed C++ & Ada Program
3145
3146 @noindent
3147 Usually the linker of the C++ development system must be used to link
3148 mixed applications because most C++ systems will resolve elaboration
3149 issues (such as calling constructors on global class instances)
3150 transparently during the link phase. GNAT has been adapted to ease the
3151 use of a foreign linker for the last phase. Three cases can be
3152 considered:
3153 @enumerate
3154
3155 @item
3156 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3157 The C++ linker can simply be called by using the C++ specific driver
3158 called @code{c++}. Note that this setup is not very common because it
3159 may involve recompiling the whole GCC tree from sources, which makes it
3160 harder to upgrade the compilation system for one language without
3161 destabilizing the other.
3162
3163 @smallexample
3164 $ c++ -c file1.C
3165 $ c++ -c file2.C
3166 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3167 @end smallexample
3168
3169 @item
3170 Using GNAT and G++ from two different GCC installations: If both
3171 compilers are on the PATH, the previous method may be used. It is
3172 important to note that environment variables such as C_INCLUDE_PATH,
3173 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3174 at the same time and may make one of the two compilers operate
3175 improperly if set during invocation of the wrong compiler.  It is also
3176 very important that the linker uses the proper @file{libgcc.a} GCC
3177 library -- that is, the one from the C++ compiler installation. The
3178 implicit link command as suggested in the gnatmake command from the
3179 former example can be replaced by an explicit link command with the
3180 full-verbosity option in order to verify which library is used:
3181 @smallexample
3182 $ gnatbind ada_unit
3183 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3184 @end smallexample
3185 If there is a problem due to interfering environment variables, it can
3186 be worked around by using an intermediate script. The following example
3187 shows the proper script to use when GNAT has not been installed at its
3188 default location and g++ has been installed at its default location:
3189
3190 @smallexample
3191 $ cat ./my_script
3192 #!/bin/sh
3193 unset BINUTILS_ROOT
3194 unset GCC_ROOT
3195 c++ $*
3196 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3197 @end smallexample
3198
3199 @item
3200 Using a non-GNU C++ compiler: The commands previously described can be
3201 used to insure that the C++ linker is used. Nonetheless, you need to add
3202 a few more parameters to the link command line, depending on the exception
3203 mechanism used.
3204
3205 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3206 to the libgcc libraries are required:
3207
3208 @smallexample
3209 $ cat ./my_script
3210 #!/bin/sh
3211 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3212 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3213 @end smallexample
3214
3215 Where CC is the name of the non-GNU C++ compiler.
3216
3217 If the @code{zero cost} exception mechanism is used, and the platform
3218 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3219 paths to more objects are required:
3220
3221 @smallexample
3222 $ cat ./my_script
3223 #!/bin/sh
3224 CC `gcc -print-file-name=crtbegin.o` $* \
3225 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3226 `gcc -print-file-name=crtend.o`
3227 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3228 @end smallexample
3229
3230 If the @code{zero cost} exception mechanism is used, and the platform
3231 doesn't support automatic registration of exception tables (e.g. HP-UX,
3232 Tru64 or AIX), the simple approach described above will not work and
3233 a pre-linking phase using GNAT will be necessary.
3234
3235 @end enumerate
3236
3237 @node A Simple Example
3238 @subsection  A Simple Example
3239 @noindent
3240 The following example, provided as part of the GNAT examples, shows how
3241 to achieve procedural interfacing between Ada and C++ in both
3242 directions. The C++ class A has two methods. The first method is exported
3243 to Ada by the means of an extern C wrapper function. The second method
3244 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3245 a limited record with a layout comparable to the C++ class. The Ada
3246 subprogram, in turn, calls the C++ method. So, starting from the C++
3247 main program, the process passes back and forth between the two
3248 languages.
3249
3250 @noindent
3251 Here are the compilation commands:
3252 @smallexample
3253 $ gnatmake -c simple_cpp_interface
3254 $ c++ -c cpp_main.C
3255 $ c++ -c ex7.C
3256 $ gnatbind -n simple_cpp_interface
3257 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3258       -lstdc++ ex7.o cpp_main.o
3259 @end smallexample
3260
3261 @noindent
3262 Here are the corresponding sources:
3263 @smallexample
3264
3265 //cpp_main.C
3266
3267 #include "ex7.h"
3268
3269 extern "C" @{
3270   void adainit (void);
3271   void adafinal (void);
3272   void method1 (A *t);
3273 @}
3274
3275 void method1 (A *t)
3276 @{
3277   t->method1 ();
3278 @}
3279
3280 int main ()
3281 @{
3282   A obj;
3283   adainit ();
3284   obj.method2 (3030);
3285   adafinal ();
3286 @}
3287
3288 //ex7.h
3289
3290 class Origin @{
3291  public:
3292   int o_value;
3293 @};
3294 class A : public Origin @{
3295  public:
3296   void method1 (void);
3297   void method2 (int v);
3298   A();
3299   int   a_value;
3300 @};
3301
3302 //ex7.C
3303
3304 #include "ex7.h"
3305 #include <stdio.h>
3306
3307 extern "C" @{ void ada_method2 (A *t, int v);@}
3308
3309 void A::method1 (void)
3310 @{
3311   a_value = 2020;
3312   printf ("in A::method1, a_value = %d \n",a_value);
3313
3314 @}
3315
3316 void A::method2 (int v)
3317 @{
3318    ada_method2 (this, v);
3319    printf ("in A::method2, a_value = %d \n",a_value);
3320
3321 @}
3322
3323 A::A(void)
3324 @{
3325    a_value = 1010;
3326   printf ("in A::A, a_value = %d \n",a_value);
3327 @}
3328
3329 -- Ada sources
3330 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3331
3332    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3333    @b{begin}
3334       Method1 (This);
3335       This.A_Value := V;
3336    @b{end} Ada_Method2;
3337
3338 @b{end} Simple_Cpp_Interface;
3339
3340 @b{package} Simple_Cpp_Interface @b{is}
3341    @b{type} A @b{is} @b{limited}
3342       @b{record}
3343          O_Value : Integer;
3344          A_Value : Integer;
3345       @b{end} @b{record};
3346    @b{pragma} Convention (C, A);
3347
3348    @b{procedure} Method1 (This : @b{in} @b{out} A);
3349    @b{pragma} Import (C, Method1);
3350
3351    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3352    @b{pragma} Export (C, Ada_Method2);
3353
3354 @b{end} Simple_Cpp_Interface;
3355 @end smallexample
3356
3357 @node Adapting the Run Time to a New C++ Compiler
3358 @subsection Adapting the Run Time to a New C++ Compiler
3359 @noindent
3360 GNAT offers the capability to derive Ada 95 tagged types directly from
3361 preexisting C++ classes and . See ``Interfacing with C++'' in the
3362 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3363 such a goal
3364 has been made user configurable through a GNAT library unit
3365 @code{Interfaces.CPP}. The default version of this file is adapted to
3366 the GNU C++ compiler. Internal knowledge of the virtual
3367 table layout used by the new C++ compiler is needed to configure
3368 properly this unit. The Interface of this unit is known by the compiler
3369 and cannot be changed except for the value of the constants defining the
3370 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3371 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3372 of this unit for more details.
3373
3374 @node Comparison between GNAT and C/C++ Compilation Models
3375 @section Comparison between GNAT and C/C++ Compilation Models
3376
3377 @noindent
3378 The GNAT model of compilation is close to the C and C++ models. You can
3379 think of Ada specs as corresponding to header files in C. As in C, you
3380 don't need to compile specs; they are compiled when they are used. The
3381 Ada @code{with} is similar in effect to the @code{#include} of a C
3382 header.
3383
3384 One notable difference is that, in Ada, you may compile specs separately
3385 to check them for semantic and syntactic accuracy. This is not always
3386 possible with C headers because they are fragments of programs that have
3387 less specific syntactic or semantic rules.
3388
3389 The other major difference is the requirement for running the binder,
3390 which performs two important functions. First, it checks for
3391 consistency. In C or C++, the only defense against assembling
3392 inconsistent programs lies outside the compiler, in a makefile, for
3393 example. The binder satisfies the Ada requirement that it be impossible
3394 to construct an inconsistent program when the compiler is used in normal
3395 mode.
3396
3397 @cindex Elaboration order control
3398 The other important function of the binder is to deal with elaboration
3399 issues. There are also elaboration issues in C++ that are handled
3400 automatically. This automatic handling has the advantage of being
3401 simpler to use, but the C++ programmer has no control over elaboration.
3402 Where @code{gnatbind} might complain there was no valid order of
3403 elaboration, a C++ compiler would simply construct a program that
3404 malfunctioned at run time.
3405
3406 @node Comparison between GNAT and Conventional Ada Library Models
3407 @section Comparison between GNAT and Conventional Ada Library Models
3408
3409 @noindent
3410 This section is intended to be useful to Ada programmers who have
3411 previously used an Ada compiler implementing the traditional Ada library
3412 model, as described in the Ada 95 Language Reference Manual. If you
3413 have not used such a system, please go on to the next section.
3414
3415 @cindex GNAT library
3416 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3417 source files themselves acts as the library. Compiling Ada programs does
3418 not generate any centralized information, but rather an object file and
3419 a ALI file, which are of interest only to the binder and linker.
3420 In a traditional system, the compiler reads information not only from
3421 the source file being compiled, but also from the centralized library.
3422 This means that the effect of a compilation depends on what has been
3423 previously compiled. In particular:
3424
3425 @itemize @bullet
3426 @item
3427 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3428 to the version of the unit most recently compiled into the library.
3429
3430 @item
3431 Inlining is effective only if the necessary body has already been
3432 compiled into the library.
3433
3434 @item
3435 Compiling a unit may obsolete other units in the library.
3436 @end itemize
3437
3438 @noindent
3439 In GNAT, compiling one unit never affects the compilation of any other
3440 units because the compiler reads only source files. Only changes to source
3441 files can affect the results of a compilation. In particular:
3442
3443 @itemize @bullet
3444 @item
3445 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3446 to the source version of the unit that is currently accessible to the
3447 compiler.
3448
3449 @item
3450 @cindex Inlining
3451 Inlining requires the appropriate source files for the package or
3452 subprogram bodies to be available to the compiler. Inlining is always
3453 effective, independent of the order in which units are complied.
3454
3455 @item
3456 Compiling a unit never affects any other compilations. The editing of
3457 sources may cause previous compilations to be out of date if they
3458 depended on the source file being modified.
3459 @end itemize
3460
3461 @noindent
3462 The most important result of these differences is that order of compilation
3463 is never significant in GNAT. There is no situation in which one is
3464 required to do one compilation before another. What shows up as order of
3465 compilation requirements in the traditional Ada library becomes, in
3466 GNAT, simple source dependencies; in other words, there is only a set
3467 of rules saying what source files must be present when a file is
3468 compiled.
3469
3470 @ifset vms
3471 @node Placement of temporary files
3472 @section Placement of temporary files
3473 @cindex Temporary files (user control over placement)
3474
3475 @noindent
3476 GNAT creates temporary files in the directory designated by the environment
3477 variable @env{TMPDIR}.
3478 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3479 for detailed information on how environment variables are resolved.
3480 For most users the easiest way to make use of this feature is to simply
3481 define @env{TMPDIR} as a job level logical name).
3482 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3483 for compiler temporary files, then you can include something like the
3484 following command in your @file{LOGIN.COM} file:
3485
3486 @smallexample
3487 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3488 @end smallexample
3489
3490 @noindent
3491 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3492 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3493 designated by @env{TEMP}.
3494 If none of these environment variables are defined then GNAT uses the
3495 directory designated by the logical name @code{SYS$SCRATCH:}
3496 (by default the user's home directory). If all else fails
3497 GNAT uses the current directory for temporary files.
3498 @end ifset
3499
3500 @c *************************
3501 @node Compiling Using gcc
3502 @chapter Compiling Using @command{gcc}
3503
3504 @noindent
3505 This chapter discusses how to compile Ada programs using the @command{gcc}
3506 command. It also describes the set of switches
3507 that can be used to control the behavior of the compiler.
3508 @menu
3509 * Compiling Programs::
3510 * Switches for gcc::
3511 * Search Paths and the Run-Time Library (RTL)::
3512 * Order of Compilation Issues::
3513 * Examples::
3514 @end menu
3515
3516 @node Compiling Programs
3517 @section Compiling Programs
3518
3519 @noindent
3520 The first step in creating an executable program is to compile the units
3521 of the program using the @command{gcc} command. You must compile the
3522 following files:
3523
3524 @itemize @bullet
3525 @item
3526 the body file (@file{.adb}) for a library level subprogram or generic
3527 subprogram
3528
3529 @item
3530 the spec file (@file{.ads}) for a library level package or generic
3531 package that has no body
3532
3533 @item
3534 the body file (@file{.adb}) for a library level package
3535 or generic package that has a body
3536
3537 @end itemize
3538
3539 @noindent
3540 You need @emph{not} compile the following files
3541
3542 @itemize @bullet
3543
3544 @item
3545 the spec of a library unit which has a body
3546
3547 @item
3548 subunits
3549 @end itemize
3550
3551 @noindent
3552 because they are compiled as part of compiling related units. GNAT
3553 package specs
3554 when the corresponding body is compiled, and subunits when the parent is
3555 compiled.
3556
3557 @cindex cannot generate code
3558 If you attempt to compile any of these files, you will get one of the
3559 following error messages (where fff is the name of the file you compiled):
3560
3561 @smallexample
3562 cannot generate code for file @var{fff} (package spec)
3563 to check package spec, use -gnatc
3564
3565 cannot generate code for file @var{fff} (missing subunits)
3566 to check parent unit, use -gnatc
3567
3568 cannot generate code for file @var{fff} (subprogram spec)
3569 to check subprogram spec, use -gnatc
3570
3571 cannot generate code for file @var{fff} (subunit)
3572 to check subunit, use -gnatc
3573 @end smallexample
3574
3575 @noindent
3576 As indicated by the above error messages, if you want to submit
3577 one of these files to the compiler to check for correct semantics
3578 without generating code, then use the @option{-gnatc} switch.
3579
3580 The basic command for compiling a file containing an Ada unit is
3581
3582 @smallexample
3583 $ gcc -c [@var{switches}] @file{file name}
3584 @end smallexample
3585
3586 @noindent
3587 where @var{file name} is the name of the Ada file (usually
3588 having an extension
3589 @file{.ads} for a spec or @file{.adb} for a body).
3590 @ifclear vms
3591 You specify the
3592 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3593 @end ifclear
3594 The result of a successful compilation is an object file, which has the
3595 same name as the source file but an extension of @file{.o} and an Ada
3596 Library Information (ALI) file, which also has the same name as the
3597 source file, but with @file{.ali} as the extension. GNAT creates these
3598 two output files in the current directory, but you may specify a source
3599 file in any directory using an absolute or relative path specification
3600 containing the directory information.
3601
3602 @findex gnat1
3603 @command{gcc} is actually a driver program that looks at the extensions of
3604 the file arguments and loads the appropriate compiler. For example, the
3605 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3606 These programs are in directories known to the driver program (in some
3607 configurations via environment variables you set), but need not be in
3608 your path. The @command{gcc} driver also calls the assembler and any other
3609 utilities needed to complete the generation of the required object
3610 files.
3611
3612 It is possible to supply several file names on the same @command{gcc}
3613 command. This causes @command{gcc} to call the appropriate compiler for
3614 each file. For example, the following command lists three separate
3615 files to be compiled:
3616
3617 @smallexample
3618 $ gcc -c x.adb y.adb z.c
3619 @end smallexample
3620
3621 @noindent
3622 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3623 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3624 The compiler generates three object files @file{x.o}, @file{y.o} and
3625 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3626 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3627 @ifclear vms
3628 except for
3629 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3630 @end ifclear
3631
3632 @node Switches for gcc
3633 @section Switches for @command{gcc}
3634
3635 @noindent
3636 The @command{gcc} command accepts switches that control the
3637 compilation process. These switches are fully described in this section.
3638 First we briefly list all the switches, in alphabetical order, then we
3639 describe the switches in more detail in functionally grouped sections.
3640
3641 More switches exist for GCC than those documented here, especially
3642 for specific targets. However, their use is not recommended as
3643 they may change code generation in ways that are incompatible with
3644 the Ada run-time library, or can cause inconsistencies between
3645 compilation units.
3646
3647 @menu
3648 * Output and Error Message Control::
3649 * Warning Message Control::
3650 * Debugging and Assertion Control::
3651 * Validity Checking::
3652 * Style Checking::
3653 * Run-Time Checks::
3654 * Stack Overflow Checking::
3655 * Using gcc for Syntax Checking::
3656 * Using gcc for Semantic Checking::
3657 * Compiling Different Versions of Ada::
3658 * Character Set Control::
3659 * File Naming Control::
3660 * Subprogram Inlining Control::
3661 * Auxiliary Output Control::
3662 * Debugging Control::
3663 * Exception Handling Control::
3664 * Units to Sources Mapping Files::
3665 * Integrated Preprocessing::
3666 * Code Generation Control::
3667 @ifset vms
3668 * Return Codes::
3669 @end ifset
3670 @end menu
3671
3672 @table @option
3673 @c !sort!
3674 @ifclear vms
3675 @cindex @option{-b} (@command{gcc})
3676 @item -b @var{target}
3677 Compile your program to run on @var{target}, which is the name of a
3678 system configuration. You must have a GNAT cross-compiler built if
3679 @var{target} is not the same as your host system.
3680
3681 @item -B@var{dir}
3682 @cindex @option{-B} (@command{gcc})
3683 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3684 from @var{dir} instead of the default location. Only use this switch
3685 when multiple versions of the GNAT compiler are available. See the
3686 @command{gcc} manual page for further details. You would normally use the
3687 @option{-b} or @option{-V} switch instead.
3688
3689 @item -c
3690 @cindex @option{-c} (@command{gcc})
3691 Compile. Always use this switch when compiling Ada programs.
3692
3693 Note: for some other languages when using @command{gcc}, notably in
3694 the case of C and C++, it is possible to use
3695 use @command{gcc} without a @option{-c} switch to
3696 compile and link in one step. In the case of GNAT, you
3697 cannot use this approach, because the binder must be run
3698 and @command{gcc} cannot be used to run the GNAT binder.
3699 @end ifclear
3700
3701 @item -fno-inline
3702 @cindex @option{-fno-inline} (@command{gcc})
3703 Suppresses all back-end inlining, even if other optimization or inlining
3704 switches are set.
3705 This includes suppression of inlining that results
3706 from the use of the pragma @code{Inline_Always}.
3707 See also @option{-gnatn} and @option{-gnatN}.
3708
3709 @item -fno-strict-aliasing
3710 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3711 Causes the compiler to avoid assumptions regarding non-aliasing
3712 of objects of different types. See
3713 @ref{Optimization and Strict Aliasing} for details.
3714
3715 @item -fstack-check
3716 @cindex @option{-fstack-check} (@command{gcc})
3717 Activates stack checking.
3718 See @ref{Stack Overflow Checking} for details of the use of this option.
3719
3720 @item -fstack-usage
3721 @cindex @option{-fstack-usage} (@command{gcc})
3722 Makes the compiler output stack usage information for the program, on a
3723 per-function basis.  The description of the format is to be found in
3724 the GCC documentation.
3725
3726 @item -fcallgraph-info
3727 @cindex @option{-fcallgraph-info} (@command{gcc})
3728 Makes the compiler output callgraph information for the program, on a
3729 per-file basis.  The information is generated in the VCG format.  It can
3730 be decorated with additional, per-node information if other debugging
3731 options are enabled (only works with -fstack-usage as of this writing).
3732
3733 @item ^-g^/DEBUG^
3734 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3735 Generate debugging information. This information is stored in the object
3736 file and copied from there to the final executable file by the linker,
3737 where it can be read by the debugger. You must use the
3738 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3739
3740 @item -gnat83
3741 @cindex @option{-gnat83} (@command{gcc})
3742 Enforce Ada 83 restrictions.
3743
3744 @item -gnat95
3745 @cindex @option{-gnat95} (@command{gcc})
3746 Enforce Ada 95 restrictions.
3747
3748 @item -gnat05
3749 @cindex @option{-gnat05} (@command{gcc})
3750 Allow full Ada 2005 features.
3751
3752 @item -gnata
3753 @cindex @option{-gnata} (@command{gcc})
3754 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3755 activated.
3756
3757 @item -gnatA
3758 @cindex @option{-gnatA} (@command{gcc})
3759 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3760 it will be ignored.
3761
3762 @item -gnatb
3763 @cindex @option{-gnatb} (@command{gcc})
3764 Generate brief messages to @file{stderr} even if verbose mode set.
3765
3766 @item -gnatc
3767 @cindex @option{-gnatc} (@command{gcc})
3768 Check syntax and semantics only (no code generation attempted).
3769
3770 @item -gnatd
3771 @cindex @option{-gnatd} (@command{gcc})
3772 Specify debug options for the compiler. The string of characters after
3773 the @option{-gnatd} specify the specific debug options. The possible
3774 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3775 compiler source file @file{debug.adb} for details of the implemented
3776 debug options. Certain debug options are relevant to applications
3777 programmers, and these are documented at appropriate points in this
3778 users guide.
3779
3780 @item -gnatD
3781 @cindex @option{-gnatD} (@command{gcc})
3782 Create expanded source files for source level debugging. This switch
3783 also suppress generation of cross-reference information
3784 (see @option{-gnatx}).
3785
3786 @item -gnatec=@var{path}
3787 @cindex @option{-gnatec} (@command{gcc})
3788 Specify a configuration pragma file
3789 @ifclear vms
3790 (the equal sign is optional)
3791 @end ifclear
3792 (@pxref{The Configuration Pragmas Files}).
3793
3794 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3795 @cindex @option{-gnateD} (@command{gcc})
3796 Defines a symbol, associated with value, for preprocessing.
3797 (@pxref{Integrated Preprocessing}).
3798
3799 @item -gnatef
3800 @cindex @option{-gnatef} (@command{gcc})
3801 Display full source path name in brief error messages.
3802
3803 @item -gnatem=@var{path}
3804 @cindex @option{-gnatem} (@command{gcc})
3805 Specify a mapping file
3806 @ifclear vms
3807 (the equal sign is optional)
3808 @end ifclear
3809 (@pxref{Units to Sources Mapping Files}).
3810
3811 @item -gnatep=@var{file}
3812 @cindex @option{-gnatep} (@command{gcc})
3813 Specify a preprocessing data file
3814 @ifclear vms
3815 (the equal sign is optional)
3816 @end ifclear
3817 (@pxref{Integrated Preprocessing}).
3818
3819 @item -gnatE
3820 @cindex @option{-gnatE} (@command{gcc})
3821 Full dynamic elaboration checks.
3822
3823 @item -gnatf
3824 @cindex @option{-gnatf} (@command{gcc})
3825 Full errors. Multiple errors per line, all undefined references, do not
3826 attempt to suppress cascaded errors.
3827
3828 @item -gnatF
3829 @cindex @option{-gnatF} (@command{gcc})
3830 Externals names are folded to all uppercase.
3831
3832 @item -gnatg
3833 @cindex @option{-gnatg} (@command{gcc})
3834 Internal GNAT implementation mode. This should not be used for
3835 applications programs, it is intended only for use by the compiler
3836 and its run-time library. For documentation, see the GNAT sources.
3837 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3838 are generated on unreferenced entities, and all warnings are treated
3839 as errors.
3840
3841 @item -gnatG
3842 @cindex @option{-gnatG} (@command{gcc})
3843 List generated expanded code in source form.
3844
3845 @item ^-gnath^/HELP^
3846 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3847 Output usage information. The output is written to @file{stdout}.
3848
3849 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3850 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3851 Identifier character set
3852 @ifclear vms
3853 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3854 @end ifclear
3855 @ifset vms
3856 For details of the possible selections for @var{c},
3857 see @ref{Character Set Control}.
3858 @end ifset
3859
3860 @item -gnatk=@var{n}
3861 @cindex @option{-gnatk} (@command{gcc})
3862 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3863
3864 @item -gnatl
3865 @cindex @option{-gnatl} (@command{gcc})
3866 Output full source listing with embedded error messages.
3867
3868 @item -gnatL
3869 @cindex @option{-gnatL} (@command{gcc})
3870 This switch is deprecated. You can use @option{--RTS=sjlj} instead to enable
3871 @code{setjmp/longjmp} exception mechanism.
3872
3873 @item -gnatm=@var{n}
3874 @cindex @option{-gnatm} (@command{gcc})
3875 Limit number of detected error or warning messages to @var{n}
3876 where @var{n} is in the range 1..999_999. The default setting if
3877 no switch is given is 9999. Compilation is terminated if this
3878 limit is exceeded.
3879
3880 @item -gnatn
3881 @cindex @option{-gnatn} (@command{gcc})
3882 Activate inlining for subprograms for which
3883 pragma @code{inline} is specified. This inlining is performed
3884 by the GCC back-end.
3885
3886 @item -gnatN
3887 @cindex @option{-gnatN} (@command{gcc})
3888 Activate front end inlining for subprograms for which
3889 pragma @code{Inline} is specified. This inlining is performed
3890 by the front end and will be visible in the
3891 @option{-gnatG} output.
3892 In some cases, this has proved more effective than the back end
3893 inlining resulting from the use of
3894 @option{-gnatn}.
3895 Note that
3896 @option{-gnatN} automatically implies
3897 @option{-gnatn} so it is not necessary
3898 to specify both options. There are a few cases that the back-end inlining
3899 catches that cannot be dealt with in the front-end.
3900
3901 @item -gnato
3902 @cindex @option{-gnato} (@command{gcc})
3903 Enable numeric overflow checking (which is not normally enabled by
3904 default). Not that division by zero is a separate check that is not
3905 controlled by this switch (division by zero checking is on by default).
3906
3907 @item -gnatp
3908 @cindex @option{-gnatp} (@command{gcc})
3909 Suppress all checks.
3910
3911 @item -gnatP
3912 @cindex @option{-gnatP} (@command{gcc})
3913 Enable polling. This is required on some systems (notably Windows NT) to
3914 obtain asynchronous abort and asynchronous transfer of control capability.
3915 See the description of pragma Polling in the GNAT Reference Manual for
3916 full details.
3917
3918 @item -gnatq
3919 @cindex @option{-gnatq} (@command{gcc})
3920 Don't quit; try semantics, even if parse errors.
3921
3922 @item -gnatQ
3923 @cindex @option{-gnatQ} (@command{gcc})
3924 Don't quit; generate @file{ALI} and tree files even if illegalities.
3925
3926 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3927 @cindex @option{-gnatR} (@command{gcc})
3928 Output representation information for declared types and objects.
3929
3930 @item -gnats
3931 @cindex @option{-gnats} (@command{gcc})
3932 Syntax check only.
3933
3934 @item -gnatS
3935 @cindex @option{-gnatS} (@command{gcc})
3936 Print package Standard.
3937
3938 @item -gnatt
3939 @cindex @option{-gnatt} (@command{gcc})
3940 Generate tree output file.
3941
3942 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3943 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3944 All compiler tables start at @var{nnn} times usual starting size.
3945
3946 @item -gnatu
3947 @cindex @option{-gnatu} (@command{gcc})
3948 List units for this compilation.
3949
3950 @item -gnatU
3951 @cindex @option{-gnatU} (@command{gcc})
3952 Tag all error messages with the unique string ``error:''
3953
3954 @item -gnatv
3955 @cindex @option{-gnatv} (@command{gcc})
3956 Verbose mode. Full error output with source lines to @file{stdout}.
3957
3958 @item -gnatV
3959 @cindex @option{-gnatV} (@command{gcc})
3960 Control level of validity checking. See separate section describing
3961 this feature.
3962
3963 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3964 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
3965 Warning mode where
3966 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3967 the exact warnings that
3968 are enabled or disabled (@pxref{Warning Message Control}).
3969
3970 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3971 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
3972 Wide character encoding method
3973 @ifclear vms
3974 (@var{e}=n/h/u/s/e/8).
3975 @end ifclear
3976 @ifset vms
3977 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3978 @end ifset
3979
3980 @item -gnatx
3981 @cindex @option{-gnatx} (@command{gcc})
3982 Suppress generation of cross-reference information.
3983
3984 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3985 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
3986 Enable built-in style checks (@pxref{Style Checking}).
3987
3988 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3989 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
3990 Distribution stub generation and compilation
3991 @ifclear vms
3992 (@var{m}=r/c for receiver/caller stubs).
3993 @end ifclear
3994 @ifset vms
3995 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3996 to be generated and compiled).
3997 @end ifset
3998
3999 @item -gnatZ
4000 This switch is deprecated. When zero cost exception handling is not the
4001 default and this is supported, you can use @option{--RTS=zcx} instead.
4002
4003 @item ^-I^/SEARCH=^@var{dir}
4004 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4005 @cindex RTL
4006 Direct GNAT to search the @var{dir} directory for source files needed by
4007 the current compilation
4008 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4009
4010 @item ^-I-^/NOCURRENT_DIRECTORY^
4011 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4012 @cindex RTL
4013 Except for the source file named in the command line, do not look for source
4014 files in the directory containing the source file named in the command line
4015 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4016
4017 @ifclear vms
4018 @item -mbig-switch
4019 @cindex @option{-mbig-switch} (@command{gcc})
4020 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4021 This standard gcc switch causes the compiler to use larger offsets in its
4022 jump table representation for @code{case} statements.
4023 This may result in less efficient code, but is sometimes necessary
4024 (for example on HP-UX targets)
4025 @cindex HP-UX and @option{-mbig-switch} option
4026 in order to compile large and/or nested @code{case} statements.
4027
4028 @item -o @var{file}
4029 @cindex @option{-o} (@command{gcc})
4030 This switch is used in @command{gcc} to redirect the generated object file
4031 and its associated ALI file. Beware of this switch with GNAT, because it may
4032 cause the object file and ALI file to have different names which in turn
4033 may confuse the binder and the linker.
4034 @end ifclear
4035
4036 @item -nostdinc
4037 @cindex @option{-nostdinc} (@command{gcc})
4038 Inhibit the search of the default location for the GNAT Run Time
4039 Library (RTL) source files.
4040
4041 @item -nostdlib
4042 @cindex @option{-nostdlib} (@command{gcc})
4043 Inhibit the search of the default location for the GNAT Run Time
4044 Library (RTL) ALI files.
4045
4046 @ifclear vms
4047 @item -O[@var{n}]
4048 @cindex @option{-O} (@command{gcc})
4049 @var{n} controls the optimization level.
4050
4051 @table @asis
4052 @item n = 0
4053 No optimization, the default setting if no @option{-O} appears
4054
4055 @item n = 1
4056 Normal optimization, the default if you specify @option{-O} without
4057 an operand.
4058
4059 @item n = 2
4060 Extensive optimization
4061
4062 @item n = 3
4063 Extensive optimization with automatic inlining of subprograms not
4064 specified by pragma @code{Inline}. This applies only to
4065 inlining within a unit. For details on control of inlining
4066 see @ref{Subprogram Inlining Control}.
4067 @end table
4068 @end ifclear
4069
4070 @ifset vms
4071 @item  /NOOPTIMIZE
4072 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4073 Equivalent to @option{/OPTIMIZE=NONE}.
4074 This is the default behavior in the absence of an @option{/OPTMIZE}
4075 qualifier.
4076
4077 @item /OPTIMIZE[=(keyword[,...])]
4078 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4079 Selects the level of optimization for your program. The supported
4080 keywords are as follows:
4081 @table @code
4082 @item   ALL
4083 Perform most optimizations, including those that
4084 are expensive.
4085 This is the default if the @option{/OPTMIZE} qualifier is supplied
4086 without keyword options.
4087
4088 @item   NONE
4089 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4090
4091 @item SOME
4092 Perform some optimizations, but omit ones that are costly.
4093
4094 @item   DEVELOPMENT
4095 Same as @code{SOME}.
4096
4097 @item   INLINING
4098 Full optimization, and also attempt automatic inlining of small
4099 subprograms within a unit even when pragma @code{Inline}
4100 is not specified (@pxref{Inlining of Subprograms}).
4101
4102 @item   UNROLL_LOOPS
4103 Try to unroll loops. This keyword may be specified together with
4104 any keyword above other than @code{NONE}. Loop unrolling
4105 usually, but not always, improves the performance of programs.
4106 @end table
4107 @end ifset
4108
4109 @ifclear vms
4110 @item -pass-exit-codes
4111 @cindex @option{-pass-exit-codes} (@command{gcc})
4112 Catch exit codes from the compiler and use the most meaningful as
4113 exit status.
4114 @end ifclear
4115
4116 @item --RTS=@var{rts-path}
4117 @cindex @option{--RTS} (@command{gcc})
4118 Specifies the default location of the runtime library. Same meaning as the
4119 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4120
4121 @item ^-S^/ASM^
4122 @cindex @option{^-S^/ASM^} (@command{gcc})
4123 ^Used in place of @option{-c} to^Used to^
4124 cause the assembler source file to be
4125 generated, using @file{^.s^.S^} as the extension,
4126 instead of the object file.
4127 This may be useful if you need to examine the generated assembly code.
4128
4129 @item ^-fverbose-asm^/VERBOSE_ASM^
4130 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4131 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4132 to cause the generated assembly code file to be annotated with variable
4133 names, making it significantly easier to follow.
4134
4135 @item ^-v^/VERBOSE^
4136 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4137 Show commands generated by the @command{gcc} driver. Normally used only for
4138 debugging purposes or if you need to be sure what version of the
4139 compiler you are executing.
4140
4141 @ifclear vms
4142 @item -V @var{ver}
4143 @cindex @option{-V} (@command{gcc})
4144 Execute @var{ver} version of the compiler. This is the @command{gcc}
4145 version, not the GNAT version.
4146 @end ifclear
4147
4148 @end table
4149
4150 @ifclear vms
4151 You may combine a sequence of GNAT switches into a single switch. For
4152 example, the combined switch
4153
4154 @cindex Combining GNAT switches
4155 @smallexample
4156 -gnatofi3
4157 @end smallexample
4158
4159 @noindent
4160 is equivalent to specifying the following sequence of switches:
4161
4162 @smallexample
4163 -gnato -gnatf -gnati3
4164 @end smallexample
4165 @end ifclear
4166
4167 @c NEED TO CHECK THIS FOR VMS
4168
4169 @noindent
4170 The following restrictions apply to the combination of switches
4171 in this manner:
4172
4173 @itemize @bullet
4174 @item
4175 The switch @option{-gnatc} if combined with other switches must come
4176 first in the string.
4177
4178 @item
4179 The switch @option{-gnats} if combined with other switches must come
4180 first in the string.
4181
4182 @item
4183 The switches
4184 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4185 may not be combined with any other switches.
4186
4187 @ifclear vms
4188 @item
4189 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4190 switch), then all further characters in the switch are interpreted
4191 as style modifiers (see description of @option{-gnaty}).
4192
4193 @item
4194 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4195 switch), then all further characters in the switch are interpreted
4196 as debug flags (see description of @option{-gnatd}).
4197
4198 @item
4199 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4200 switch), then all further characters in the switch are interpreted
4201 as warning mode modifiers (see description of @option{-gnatw}).
4202
4203 @item
4204 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4205 switch), then all further characters in the switch are interpreted
4206 as validity checking options (see description of @option{-gnatV}).
4207 @end ifclear
4208 @end itemize
4209
4210 @node Output and Error Message Control
4211 @subsection Output and Error Message Control
4212 @findex stderr
4213
4214 @noindent
4215 The standard default format for error messages is called ``brief format''.
4216 Brief format messages are written to @file{stderr} (the standard error
4217 file) and have the following form:
4218
4219 @smallexample
4220 e.adb:3:04: Incorrect spelling of keyword "function"
4221 e.adb:4:20: ";" should be "is"
4222 @end smallexample
4223
4224 @noindent
4225 The first integer after the file name is the line number in the file,
4226 and the second integer is the column number within the line.
4227 @code{glide} can parse the error messages
4228 and point to the referenced character.
4229 The following switches provide control over the error message
4230 format:
4231
4232 @table @option
4233 @c !sort!
4234 @item -gnatv
4235 @cindex @option{-gnatv} (@command{gcc})
4236 @findex stdout
4237 @ifclear vms
4238 The v stands for verbose.
4239 @end ifclear
4240 The effect of this setting is to write long-format error
4241 messages to @file{stdout} (the standard output file.
4242 The same program compiled with the
4243 @option{-gnatv} switch would generate:
4244
4245 @smallexample
4246 @cartouche
4247 3. funcion X (Q : Integer)
4248    |
4249 >>> Incorrect spelling of keyword "function"
4250 4. return Integer;
4251                  |
4252 >>> ";" should be "is"
4253 @end cartouche
4254 @end smallexample
4255
4256 @noindent
4257 The vertical bar indicates the location of the error, and the @samp{>>>}
4258 prefix can be used to search for error messages. When this switch is
4259 used the only source lines output are those with errors.
4260
4261 @item -gnatl
4262 @cindex @option{-gnatl} (@command{gcc})
4263 @ifclear vms
4264 The @code{l} stands for list.
4265 @end ifclear
4266 This switch causes a full listing of
4267 the file to be generated. The output might look as follows:
4268
4269 @smallexample
4270 @cartouche
4271  1. procedure E is
4272  2.    V : Integer;
4273  3.    funcion X (Q : Integer)
4274        |
4275     >>> Incorrect spelling of keyword "function"
4276  4.     return Integer;
4277                       |
4278     >>> ";" should be "is"
4279  5.    begin
4280  6.       return Q + Q;
4281  7.    end;
4282  8. begin
4283  9.    V := X + X;
4284 10.end E;
4285 @end cartouche
4286 @end smallexample
4287
4288 @noindent
4289 @findex stderr
4290 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4291 standard output is redirected, a brief summary is written to
4292 @file{stderr} (standard error) giving the number of error messages and
4293 warning messages generated.
4294
4295 @item -gnatU
4296 @cindex @option{-gnatU} (@command{gcc})
4297 This switch forces all error messages to be preceded by the unique
4298 string ``error:''. This means that error messages take a few more
4299 characters in space, but allows easy searching for and identification
4300 of error messages.
4301
4302 @item -gnatb
4303 @cindex @option{-gnatb} (@command{gcc})
4304 @ifclear vms
4305 The @code{b} stands for brief.
4306 @end ifclear
4307 This switch causes GNAT to generate the
4308 brief format error messages to @file{stderr} (the standard error
4309 file) as well as the verbose
4310 format message or full listing (which as usual is written to
4311 @file{stdout} (the standard output file).
4312
4313 @item -gnatm^^=^@var{n}
4314 @cindex @option{-gnatm} (@command{gcc})
4315 @ifclear vms
4316 The @code{m} stands for maximum.
4317 @end ifclear
4318 @var{n} is a decimal integer in the
4319 range of 1 to 999 and limits the number of error messages to be
4320 generated. For example, using @option{-gnatm2} might yield
4321
4322 @smallexample
4323 e.adb:3:04: Incorrect spelling of keyword "function"
4324 e.adb:5:35: missing ".."
4325 fatal error: maximum errors reached
4326 compilation abandoned
4327 @end smallexample
4328
4329 @item -gnatf
4330 @cindex @option{-gnatf} (@command{gcc})
4331 @cindex Error messages, suppressing
4332 @ifclear vms
4333 The @code{f} stands for full.
4334 @end ifclear
4335 Normally, the compiler suppresses error messages that are likely to be
4336 redundant. This switch causes all error
4337 messages to be generated. In particular, in the case of
4338 references to undefined variables. If a given variable is referenced
4339 several times, the normal format of messages is
4340 @smallexample
4341 e.adb:7:07: "V" is undefined (more references follow)
4342 @end smallexample
4343
4344 @noindent
4345 where the parenthetical comment warns that there are additional
4346 references to the variable @code{V}. Compiling the same program with the
4347 @option{-gnatf} switch yields
4348
4349 @smallexample
4350 e.adb:7:07: "V" is undefined
4351 e.adb:8:07: "V" is undefined
4352 e.adb:8:12: "V" is undefined
4353 e.adb:8:16: "V" is undefined
4354 e.adb:9:07: "V" is undefined
4355 e.adb:9:12: "V" is undefined
4356 @end smallexample
4357
4358 @noindent
4359 The @option{-gnatf} switch also generates additional information for
4360 some error messages.  Some examples are:
4361
4362 @itemize @bullet
4363 @item
4364 Full details on entities not available in high integrity mode
4365 @item
4366 Details on possibly non-portable unchecked conversion
4367 @item
4368 List possible interpretations for ambiguous calls
4369 @item
4370 Additional details on incorrect parameters
4371 @end itemize
4372
4373 @item -gnatq
4374 @cindex @option{-gnatq} (@command{gcc})
4375 @ifclear vms
4376 The @code{q} stands for quit (really ``don't quit'').
4377 @end ifclear
4378 In normal operation mode, the compiler first parses the program and
4379 determines if there are any syntax errors. If there are, appropriate
4380 error messages are generated and compilation is immediately terminated.
4381 This switch tells
4382 GNAT to continue with semantic analysis even if syntax errors have been
4383 found. This may enable the detection of more errors in a single run. On
4384 the other hand, the semantic analyzer is more likely to encounter some
4385 internal fatal error when given a syntactically invalid tree.
4386
4387 @item -gnatQ
4388 @cindex @option{-gnatQ} (@command{gcc})
4389 In normal operation mode, the @file{ALI} file is not generated if any
4390 illegalities are detected in the program. The use of @option{-gnatQ} forces
4391 generation of the @file{ALI} file. This file is marked as being in
4392 error, so it cannot be used for binding purposes, but it does contain
4393 reasonably complete cross-reference information, and thus may be useful
4394 for use by tools (e.g. semantic browsing tools or integrated development
4395 environments) that are driven from the @file{ALI} file. This switch
4396 implies @option{-gnatq}, since the semantic phase must be run to get a
4397 meaningful ALI file.
4398
4399 In addition, if @option{-gnatt} is also specified, then the tree file is
4400 generated even if there are illegalities. It may be useful in this case
4401 to also specify @option{-gnatq} to ensure that full semantic processing
4402 occurs. The resulting tree file can be processed by ASIS, for the purpose
4403 of providing partial information about illegal units, but if the error
4404 causes the tree to be badly malformed, then ASIS may crash during the
4405 analysis.
4406
4407 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4408 being in error, @command{gnatmake} will attempt to recompile the source when it
4409 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4410
4411 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4412 since ALI files are never generated if @option{-gnats} is set.
4413
4414 @end table
4415
4416 @node Warning Message Control
4417 @subsection Warning Message Control
4418 @cindex Warning messages
4419 @noindent
4420 In addition to error messages, which correspond to illegalities as defined
4421 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4422 situations.
4423
4424 First, the compiler considers some constructs suspicious and generates a
4425 warning message to alert you to a possible error. Second, if the
4426 compiler detects a situation that is sure to raise an exception at
4427 run time, it generates a warning message. The following shows an example
4428 of warning messages:
4429 @smallexample
4430 e.adb:4:24: warning: creation of object may raise Storage_Error
4431 e.adb:10:17: warning: static value out of range
4432 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4433 @end smallexample
4434
4435 @noindent
4436 GNAT considers a large number of situations as appropriate
4437 for the generation of warning messages. As always, warnings are not
4438 definite indications of errors. For example, if you do an out-of-range
4439 assignment with the deliberate intention of raising a
4440 @code{Constraint_Error} exception, then the warning that may be
4441 issued does not indicate an error. Some of the situations for which GNAT
4442 issues warnings (at least some of the time) are given in the following
4443 list. This list is not complete, and new warnings are often added to
4444 subsequent versions of GNAT. The list is intended to give a general idea
4445 of the kinds of warnings that are generated.
4446
4447 @itemize @bullet
4448 @item
4449 Possible infinitely recursive calls
4450
4451 @item
4452 Out-of-range values being assigned
4453
4454 @item
4455 Possible order of elaboration problems
4456
4457 @item
4458 Unreachable code
4459
4460 @item
4461 Fixed-point type declarations with a null range
4462
4463 @item
4464 Direct_IO or Sequential_IO instantiated with a type that has access values
4465
4466 @item
4467 Variables that are never assigned a value
4468
4469 @item
4470 Variables that are referenced before being initialized
4471
4472 @item
4473 Task entries with no corresponding @code{accept} statement
4474
4475 @item
4476 Duplicate accepts for the same task entry in a @code{select}
4477
4478 @item
4479 Objects that take too much storage
4480
4481 @item
4482 Unchecked conversion between types of differing sizes
4483
4484 @item
4485 Missing @code{return} statement along some execution path in a function
4486
4487 @item
4488 Incorrect (unrecognized) pragmas
4489
4490 @item
4491 Incorrect external names
4492
4493 @item
4494 Allocation from empty storage pool
4495
4496 @item
4497 Potentially blocking operation in protected type
4498
4499 @item
4500 Suspicious parenthesization of expressions
4501
4502 @item
4503 Mismatching bounds in an aggregate
4504
4505 @item
4506 Attempt to return local value by reference
4507
4508 @item
4509 Premature instantiation of a generic body
4510
4511 @item
4512 Attempt to pack aliased components
4513
4514 @item
4515 Out of bounds array subscripts
4516
4517 @item
4518 Wrong length on string assignment
4519
4520 @item
4521 Violations of style rules if style checking is enabled
4522
4523 @item
4524 Unused @code{with} clauses
4525
4526 @item
4527 @code{Bit_Order} usage that does not have any effect
4528
4529 @item
4530 @code{Standard.Duration} used to resolve universal fixed expression
4531
4532 @item
4533 Dereference of possibly null value
4534
4535 @item
4536 Declaration that is likely to cause storage error
4537
4538 @item
4539 Internal GNAT unit @code{with}'ed by application unit
4540
4541 @item
4542 Values known to be out of range at compile time
4543
4544 @item
4545 Unreferenced labels and variables
4546
4547 @item
4548 Address overlays that could clobber memory
4549
4550 @item
4551 Unexpected initialization when address clause present
4552
4553 @item
4554 Bad alignment for address clause
4555
4556 @item
4557 Useless type conversions
4558
4559 @item
4560 Redundant assignment statements and other redundant constructs
4561
4562 @item
4563 Useless exception handlers
4564
4565 @item
4566 Accidental hiding of name by child unit
4567
4568 @item
4569 Access before elaboration detected at compile time
4570
4571 @item
4572 A range in a @code{for} loop that is known to be null or might be null
4573
4574 @end itemize
4575
4576 @noindent
4577 The following switches are available to control the handling of
4578 warning messages:
4579
4580 @table @option
4581 @c !sort!
4582 @item -gnatwa
4583 @emph{Activate all optional errors.}
4584 @cindex @option{-gnatwa} (@command{gcc})
4585 This switch activates most optional warning messages, see remaining list
4586 in this section for details on optional warning messages that can be
4587 individually controlled.  The warnings that are not turned on by this
4588 switch are
4589 @option{-gnatwd} (implicit dereferencing),
4590 @option{-gnatwh} (hiding),
4591 and @option{-gnatwl} (elaboration warnings).
4592 All other optional warnings are turned on.
4593
4594 @item -gnatwA
4595 @emph{Suppress all optional errors.}
4596 @cindex @option{-gnatwA} (@command{gcc})
4597 This switch suppresses all optional warning messages, see remaining list
4598 in this section for details on optional warning messages that can be
4599 individually controlled.
4600
4601 @item -gnatwb
4602 @emph{Activate warnings on bad fixed values.}
4603 @cindex @option{-gnatwb} (@command{gcc})
4604 @cindex Bad fixed values
4605 @cindex Fixed-point Small value
4606 @cindex Small value
4607 This switch activates warnings for static fixed-point expressions whose
4608 value is not an exact multiple of Small. Such values are implementation
4609 dependent, since an implementation is free to choose either of the multiples
4610 that surround the value. GNAT always chooses the closer one, but this is not
4611 required behavior, and it is better to specify a value that is an exact
4612 multiple, ensuring predictable execution. The default is that such warnings
4613 are not generated.
4614
4615 @item -gnatwB
4616 @emph{Suppress warnings on bad fixed values.}
4617 @cindex @option{-gnatwB} (@command{gcc})
4618 This switch suppresses warnings for static fixed-point expressions whose
4619 value is not an exact multiple of Small.
4620
4621 @item -gnatwc
4622 @emph{Activate warnings on conditionals.}
4623 @cindex @option{-gnatwc} (@command{gcc})
4624 @cindex Conditionals, constant
4625 This switch activates warnings for conditional expressions used in
4626 tests that are known to be True or False at compile time. The default
4627 is that such warnings are not generated.
4628 Note that this warning does
4629 not get issued for the use of boolean variables or constants whose
4630 values are known at compile time, since this is a standard technique
4631 for conditional compilation in Ada, and this would generate too many
4632 ``false positive'' warnings.
4633 This warning can also be turned on using @option{-gnatwa}.
4634
4635 @item -gnatwC
4636 @emph{Suppress warnings on conditionals.}
4637 @cindex @option{-gnatwC} (@command{gcc})
4638 This switch suppresses warnings for conditional expressions used in
4639 tests that are known to be True or False at compile time.
4640
4641 @item -gnatwd
4642 @emph{Activate warnings on implicit dereferencing.}
4643 @cindex @option{-gnatwd} (@command{gcc})
4644 If this switch is set, then the use of a prefix of an access type
4645 in an indexed component, slice, or selected component without an
4646 explicit @code{.all} will generate a warning. With this warning
4647 enabled, access checks occur only at points where an explicit
4648 @code{.all} appears in the source code (assuming no warnings are
4649 generated as a result of this switch). The default is that such
4650 warnings are not generated.
4651 Note that @option{-gnatwa} does not affect the setting of
4652 this warning option.
4653
4654 @item -gnatwD
4655 @emph{Suppress warnings on implicit dereferencing.}
4656 @cindex @option{-gnatwD} (@command{gcc})
4657 @cindex Implicit dereferencing
4658 @cindex Dereferencing, implicit
4659 This switch suppresses warnings for implicit dereferences in
4660 indexed components, slices, and selected components.
4661
4662 @item -gnatwe
4663 @emph{Treat warnings as errors.}
4664 @cindex @option{-gnatwe} (@command{gcc})
4665 @cindex Warnings, treat as error
4666 This switch causes warning messages to be treated as errors.
4667 The warning string still appears, but the warning messages are counted
4668 as errors, and prevent the generation of an object file.
4669
4670 @item -gnatwf
4671 @emph{Activate warnings on unreferenced formals.}
4672 @cindex @option{-gnatwf} (@command{gcc})
4673 @cindex Formals, unreferenced
4674 This switch causes a warning to be generated if a formal parameter
4675 is not referenced in the body of the subprogram. This warning can
4676 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4677
4678 @item -gnatwF
4679 @emph{Suppress warnings on unreferenced formals.}
4680 @cindex @option{-gnatwF} (@command{gcc})
4681 This switch suppresses warnings for unreferenced formal
4682 parameters. Note that the
4683 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4684 effect of warning on unreferenced entities other than subprogram
4685 formals.
4686
4687 @item -gnatwg
4688 @emph{Activate warnings on unrecognized pragmas.}
4689 @cindex @option{-gnatwg} (@command{gcc})
4690 @cindex Pragmas, unrecognized
4691 This switch causes a warning to be generated if an unrecognized
4692 pragma is encountered. Apart from issuing this warning, the
4693 pragma is ignored and has no effect. This warning can
4694 also be turned on using @option{-gnatwa}. The default
4695 is that such warnings are issued (satisfying the Ada Reference
4696 Manual requirement that such warnings appear).
4697
4698 @item -gnatwG
4699 @emph{Suppress warnings on unrecognized pragmas.}
4700 @cindex @option{-gnatwG} (@command{gcc})
4701 This switch suppresses warnings for unrecognized pragmas.
4702
4703 @item -gnatwh
4704 @emph{Activate warnings on hiding.}
4705 @cindex @option{-gnatwh} (@command{gcc})
4706 @cindex Hiding of Declarations
4707 This switch activates warnings on hiding declarations.
4708 A declaration is considered hiding
4709 if it is for a non-overloadable entity, and it declares an entity with the
4710 same name as some other entity that is directly or use-visible. The default
4711 is that such warnings are not generated.
4712 Note that @option{-gnatwa} does not affect the setting of this warning option.
4713
4714 @item -gnatwH
4715 @emph{Suppress warnings on hiding.}
4716 @cindex @option{-gnatwH} (@command{gcc})
4717 This switch suppresses warnings on hiding declarations.
4718
4719 @item -gnatwi
4720 @emph{Activate warnings on implementation units.}
4721 @cindex @option{-gnatwi} (@command{gcc})
4722 This switch activates warnings for a @code{with} of an internal GNAT
4723 implementation unit, defined as any unit from the @code{Ada},
4724 @code{Interfaces}, @code{GNAT},
4725 ^^@code{DEC},^ or @code{System}
4726 hierarchies that is not
4727 documented in either the Ada Reference Manual or the GNAT
4728 Programmer's Reference Manual. Such units are intended only
4729 for internal implementation purposes and should not be @code{with}'ed
4730 by user programs. The default is that such warnings are generated
4731 This warning can also be turned on using @option{-gnatwa}.
4732
4733 @item -gnatwI
4734 @emph{Disable warnings on implementation units.}
4735 @cindex @option{-gnatwI} (@command{gcc})
4736 This switch disables warnings for a @code{with} of an internal GNAT
4737 implementation unit.
4738
4739 @item -gnatwj
4740 @emph{Activate warnings on obsolescent features (Annex J).}
4741 @cindex @option{-gnatwj} (@command{gcc})
4742 @cindex Features, obsolescent
4743 @cindex Obsolescent features
4744 If this warning option is activated, then warnings are generated for
4745 calls to subprograms marked with @code{pragma Obsolescent} and
4746 for use of features in Annex J of the Ada Reference Manual. In the
4747 case of Annex J, not all features are flagged. In particular use
4748 of the renamed packages (like @code{Text_IO}) and use of package
4749 @code{ASCII} are not flagged, since these are very common and
4750 would generate many annoying positive warnings. The default is that
4751 such warnings are not generated.
4752
4753 In addition to the above cases, warnings are also generated for
4754 GNAT features that have been provided in past versions but which
4755 have been superseded (typically by features in the new Ada standard).
4756 For example, @code{pragma Ravenscar} will be flagged since its
4757 function is replaced by @code{pragma Profile(Ravenscar)}.
4758
4759 Note that this warning option functions differently from the
4760 restriction @code{No_Obsolescent_Features} in two respects.
4761 First, the restriction applies only to annex J features.
4762 Second, the restriction does flag uses of package @code{ASCII}.
4763
4764 @item -gnatwJ
4765 @emph{Suppress warnings on obsolescent features (Annex J).}
4766 @cindex @option{-gnatwJ} (@command{gcc})
4767 This switch disables warnings on use of obsolescent features.
4768
4769 @item -gnatwk
4770 @emph{Activate warnings on variables that could be constants.}
4771 @cindex @option{-gnatwk} (@command{gcc})
4772 This switch activates warnings for variables that are initialized but
4773 never modified, and then could be declared constants.
4774
4775 @item -gnatwK
4776 @emph{Suppress warnings on variables that could be constants.}
4777 @cindex @option{-gnatwK} (@command{gcc})
4778 This switch disables warnings on variables that could be declared constants.
4779
4780 @item -gnatwl
4781 @emph{Activate warnings for missing elaboration pragmas.}
4782 @cindex @option{-gnatwl} (@command{gcc})
4783 @cindex Elaboration, warnings
4784 This switch activates warnings on missing
4785 @code{pragma Elaborate_All} statements.
4786 See the section in this guide on elaboration checking for details on
4787 when such pragma should be used. Warnings are also generated if you
4788 are using the static mode of elaboration, and a @code{pragma Elaborate}
4789 is encountered. The default is that such warnings
4790 are not generated.
4791 This warning is not automatically turned on by the use of @option{-gnatwa}.
4792
4793 @item -gnatwL
4794 @emph{Suppress warnings for missing elaboration pragmas.}
4795 @cindex @option{-gnatwL} (@command{gcc})
4796 This switch suppresses warnings on missing pragma Elaborate_All statements.
4797 See the section in this guide on elaboration checking for details on
4798 when such pragma should be used.
4799
4800 @item -gnatwm
4801 @emph{Activate warnings on modified but unreferenced variables.}
4802 @cindex @option{-gnatwm} (@command{gcc})
4803 This switch activates warnings for variables that are assigned (using
4804 an initialization value or with one or more assignment statements) but
4805 whose value is never read. The warning is suppressed for volatile
4806 variables and also for variables that are renamings of other variables
4807 or for which an address clause is given.
4808 This warning can also be turned on using @option{-gnatwa}.
4809
4810 @item -gnatwM
4811 @emph{Disable warnings on modified but unreferenced variables.}
4812 @cindex @option{-gnatwM} (@command{gcc})
4813 This switch disables warnings for variables that are assigned or
4814 initialized, but never read.
4815
4816 @item -gnatwn
4817 @emph{Set normal warnings mode.}
4818 @cindex @option{-gnatwn} (@command{gcc})
4819 This switch sets normal warning mode, in which enabled warnings are
4820 issued and treated as warnings rather than errors. This is the default
4821 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4822 an explicit @option{-gnatws} or
4823 @option{-gnatwe}. It also cancels the effect of the
4824 implicit @option{-gnatwe} that is activated by the
4825 use of @option{-gnatg}.
4826
4827 @item -gnatwo
4828 @emph{Activate warnings on address clause overlays.}
4829 @cindex @option{-gnatwo} (@command{gcc})
4830 @cindex Address Clauses, warnings
4831 This switch activates warnings for possibly unintended initialization
4832 effects of defining address clauses that cause one variable to overlap
4833 another. The default is that such warnings are generated.
4834 This warning can also be turned on using @option{-gnatwa}.
4835
4836 @item -gnatwO
4837 @emph{Suppress warnings on address clause overlays.}
4838 @cindex @option{-gnatwO} (@command{gcc})
4839 This switch suppresses warnings on possibly unintended initialization
4840 effects of defining address clauses that cause one variable to overlap
4841 another.
4842
4843 @item -gnatwp
4844 @emph{Activate warnings on ineffective pragma Inlines.}
4845 @cindex @option{-gnatwp} (@command{gcc})
4846 @cindex Inlining, warnings
4847 This switch activates warnings for failure of front end inlining
4848 (activated by @option{-gnatN}) to inline a particular call. There are
4849 many reasons for not being able to inline a call, including most
4850 commonly that the call is too complex to inline.
4851 This warning can also be turned on using @option{-gnatwa}.
4852
4853 @item -gnatwP
4854 @emph{Suppress warnings on ineffective pragma Inlines.}
4855 @cindex @option{-gnatwP} (@command{gcc})
4856 This switch suppresses warnings on ineffective pragma Inlines. If the
4857 inlining mechanism cannot inline a call, it will simply ignore the
4858 request silently.
4859
4860 @item -gnatwr
4861 @emph{Activate warnings on redundant constructs.}
4862 @cindex @option{-gnatwr} (@command{gcc})
4863 This switch activates warnings for redundant constructs. The following
4864 is the current list of constructs regarded as redundant:
4865 This warning can also be turned on using @option{-gnatwa}.
4866
4867 @itemize @bullet
4868 @item
4869 Assignment of an item to itself.
4870 @item
4871 Type conversion that converts an expression to its own type.
4872 @item
4873 Use of the attribute @code{Base} where @code{typ'Base} is the same
4874 as @code{typ}.
4875 @item
4876 Use of pragma @code{Pack} when all components are placed by a record
4877 representation clause.
4878 @item
4879 Exception handler containing only a reraise statement (raise with no
4880 operand) which has no effect.
4881 @item
4882 Use of the operator abs on an operand that is known at compile time
4883 to be non-negative
4884 @item
4885 Comparison of boolean expressions to an explicit True value.
4886 @end itemize
4887
4888 @item -gnatwR
4889 @emph{Suppress warnings on redundant constructs.}
4890 @cindex @option{-gnatwR} (@command{gcc})
4891 This switch suppresses warnings for redundant constructs.
4892
4893 @item -gnatws
4894 @emph{Suppress all warnings.}
4895 @cindex @option{-gnatws} (@command{gcc})
4896 This switch completely suppresses the
4897 output of all warning messages from the GNAT front end.
4898 Note that it does not suppress warnings from the @command{gcc} back end.
4899 To suppress these back end warnings as well, use the switch @option{-w}
4900 in addition to @option{-gnatws}.
4901
4902 @item -gnatwu
4903 @emph{Activate warnings on unused entities.}
4904 @cindex @option{-gnatwu} (@command{gcc})
4905 This switch activates warnings to be generated for entities that
4906 are declared but not referenced, and for units that are @code{with}'ed
4907 and not
4908 referenced. In the case of packages, a warning is also generated if
4909 no entities in the package are referenced. This means that if the package
4910 is referenced but the only references are in @code{use}
4911 clauses or @code{renames}
4912 declarations, a warning is still generated. A warning is also generated
4913 for a generic package that is @code{with}'ed but never instantiated.
4914 In the case where a package or subprogram body is compiled, and there
4915 is a @code{with} on the corresponding spec
4916 that is only referenced in the body,
4917 a warning is also generated, noting that the
4918 @code{with} can be moved to the body. The default is that
4919 such warnings are not generated.
4920 This switch also activates warnings on unreferenced formals
4921 (it includes the effect of @option{-gnatwf}).
4922 This warning can also be turned on using @option{-gnatwa}.
4923
4924 @item -gnatwU
4925 @emph{Suppress warnings on unused entities.}
4926 @cindex @option{-gnatwU} (@command{gcc})
4927 This switch suppresses warnings for unused entities and packages.
4928 It also turns off warnings on unreferenced formals (and thus includes
4929 the effect of @option{-gnatwF}).
4930
4931 @item -gnatwv
4932 @emph{Activate warnings on unassigned variables.}
4933 @cindex @option{-gnatwv} (@command{gcc})
4934 @cindex Unassigned variable warnings
4935 This switch activates warnings for access to variables which
4936 may not be properly initialized. The default is that
4937 such warnings are generated.
4938
4939 @item -gnatwV
4940 @emph{Suppress warnings on unassigned variables.}
4941 @cindex @option{-gnatwV} (@command{gcc})
4942 This switch suppresses warnings for access to variables which
4943 may not be properly initialized.
4944
4945 @item -gnatwy
4946 @emph{Activate warnings for Ada 2005 compatibility issues.}
4947 @cindex @option{-gnatwy} (@command{gcc})
4948 @cindex Ada 2005 compatibility issues warnings
4949 For the most part Ada 2005 is upwards compatible with Ada 95,
4950 but there are some exceptions (for example the fact that
4951 @code{interface} is now a reserved word in Ada 2005). This
4952 switch activates several warnings to help in identifying
4953 and correcting such incompatibilities. The default is that
4954 these warnings are generated. Note that at one point Ada 2005
4955 was called Ada 0Y, hence the choice of character.
4956
4957 @item -gnatwY
4958 @emph{Disable warnings for Ada 2005 compatibility issues.}
4959 @cindex @option{-gnatwY} (@command{gcc})
4960 @cindex Ada 2005 compatibility issues warnings
4961 This switch suppresses several warnings intended to help in identifying
4962 incompatibilities between Ada 95 and Ada 2005.
4963
4964 @item -gnatwx
4965 @emph{Activate warnings on Export/Import pragmas.}
4966 @cindex @option{-gnatwx} (@command{gcc})
4967 @cindex Export/Import pragma warnings
4968 This switch activates warnings on Export/Import pragmas when
4969 the compiler detects a possible conflict between the Ada and
4970 foreign language calling sequences. For example, the use of
4971 default parameters in a convention C procedure is dubious
4972 because the C compiler cannot supply the proper default, so
4973 a warning is issued. The default is that such warnings are
4974 generated.
4975
4976 @item -gnatwX
4977 @emph{Suppress warnings on Export/Import pragmas.}
4978 @cindex @option{-gnatwX} (@command{gcc})
4979 This switch suppresses warnings on Export/Import pragmas.
4980 The sense of this is that you are telling the compiler that
4981 you know what you are doing in writing the pragma, and it
4982 should not complain at you.
4983
4984 @item -gnatwz
4985 @emph{Activate warnings on unchecked conversions.}
4986 @cindex @option{-gnatwz} (@command{gcc})
4987 @cindex Unchecked_Conversion warnings
4988 This switch activates warnings for unchecked conversions
4989 where the types are known at compile time to have different
4990 sizes. The default
4991 is that such warnings are generated.
4992
4993 @item -gnatwZ
4994 @emph{Suppress warnings on unchecked conversions.}
4995 @cindex @option{-gnatwZ} (@command{gcc})
4996 This switch suppresses warnings for unchecked conversions
4997 where the types are known at compile time to have different
4998 sizes.
4999
5000 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5001 @cindex @option{-Wuninitialized}
5002 The warnings controlled by the @option{-gnatw} switch are generated by the
5003 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5004 can provide additional warnings. One such useful warning is provided by
5005 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5006 conjunction with tunrning on optimization mode. This causes the flow
5007 analysis circuits of the back end optimizer to output additional
5008 warnings about uninitialized variables.
5009
5010 @item ^-w^/NO_BACK_END_WARNINGS^
5011 @cindex @option{-w}
5012 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
5013 be used in conjunction with @option{-gnatws} to ensure that all warnings
5014 are suppressed during the entire compilation process.
5015
5016 @end table
5017
5018 @noindent
5019 @ifclear vms
5020 A string of warning parameters can be used in the same parameter. For example:
5021
5022 @smallexample
5023 -gnatwaLe
5024 @end smallexample
5025
5026 @noindent
5027 will turn on all optional warnings except for elaboration pragma warnings,
5028 and also specify that warnings should be treated as errors.
5029 @end ifclear
5030 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5031
5032 @table @option
5033 @c !sort!
5034 @item -gnatwC
5035 @item -gnatwD
5036 @item -gnatwF
5037 @item -gnatwg
5038 @item -gnatwH
5039 @item -gnatwi
5040 @item -gnatwJ
5041 @item -gnatwK
5042 @item -gnatwL
5043 @item -gnatwM
5044 @item -gnatwn
5045 @item -gnatwo
5046 @item -gnatwP
5047 @item -gnatwR
5048 @item -gnatwU
5049 @item -gnatwv
5050 @item -gnatwz
5051 @item -gnatwx
5052
5053 @end table
5054
5055 @node Debugging and Assertion Control
5056 @subsection Debugging and Assertion Control
5057
5058 @table @option
5059 @item -gnata
5060 @cindex @option{-gnata} (@command{gcc})
5061 @findex Assert
5062 @findex Debug
5063 @cindex Assertions
5064
5065 @noindent
5066 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5067 are ignored. This switch, where @samp{a} stands for assert, causes
5068 @code{Assert} and @code{Debug} pragmas to be activated.
5069
5070 The pragmas have the form:
5071
5072 @smallexample
5073 @cartouche
5074    @b{pragma} Assert (@var{Boolean-expression} [,
5075                       @var{static-string-expression}])
5076    @b{pragma} Debug (@var{procedure call})
5077 @end cartouche
5078 @end smallexample
5079
5080 @noindent
5081 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5082 If the result is @code{True}, the pragma has no effect (other than
5083 possible side effects from evaluating the expression). If the result is
5084 @code{False}, the exception @code{Assert_Failure} declared in the package
5085 @code{System.Assertions} is
5086 raised (passing @var{static-string-expression}, if present, as the
5087 message associated with the exception). If no string expression is
5088 given the default is a string giving the file name and line number
5089 of the pragma.
5090
5091 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5092 @code{pragma Debug} may appear within a declaration sequence, allowing
5093 debugging procedures to be called between declarations.
5094
5095 @ifset vms
5096 @item /DEBUG[=debug-level]
5097 @itemx  /NODEBUG
5098 Specifies how much debugging information is to be included in
5099 the resulting object file where 'debug-level' is one of the following:
5100 @table @code
5101 @item   TRACEBACK
5102 Include both debugger symbol records and traceback
5103 the object file.
5104 This is the default setting.
5105 @item   ALL
5106 Include both debugger symbol records and traceback in
5107 object file.
5108 @item   NONE
5109 Excludes both debugger symbol records and traceback
5110 the object file. Same as /NODEBUG.
5111 @item   SYMBOLS
5112 Includes only debugger symbol records in the object
5113 file. Note that this doesn't include traceback information.
5114 @end table
5115 @end ifset
5116 @end table
5117
5118 @node Validity Checking
5119 @subsection Validity Checking
5120 @findex Validity Checking
5121
5122 @noindent
5123 The Ada 95 Reference Manual has specific requirements for checking
5124 for invalid values. In particular, RM 13.9.1 requires that the
5125 evaluation of invalid values (for example from unchecked conversions),
5126 not result in erroneous execution. In GNAT, the result of such an
5127 evaluation in normal default mode is to either use the value
5128 unmodified, or to raise Constraint_Error in those cases where use
5129 of the unmodified value would cause erroneous execution. The cases
5130 where unmodified values might lead to erroneous execution are case
5131 statements (where a wild jump might result from an invalid value),
5132 and subscripts on the left hand side (where memory corruption could
5133 occur as a result of an invalid value).
5134
5135 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5136 checking mode.
5137 @ifclear vms
5138 The @code{x} argument is a string of letters that
5139 indicate validity checks that are performed or not performed in addition
5140 to the default checks described above.
5141 @end ifclear
5142 @ifset vms
5143 The options allowed for this qualifier
5144 indicate validity checks that are performed or not performed in addition
5145 to the default checks described above.
5146 @end ifset
5147
5148 @table @option
5149 @c !sort!
5150 @item -gnatVa
5151 @emph{All validity checks.}
5152 @cindex @option{-gnatVa} (@command{gcc})
5153 All validity checks are turned on.
5154 @ifclear vms
5155 That is, @option{-gnatVa} is
5156 equivalent to @option{gnatVcdfimorst}.
5157 @end ifclear
5158
5159 @item -gnatVc
5160 @emph{Validity checks for copies.}
5161 @cindex @option{-gnatVc} (@command{gcc})
5162 The right hand side of assignments, and the initializing values of
5163 object declarations are validity checked.
5164
5165 @item -gnatVd
5166 @emph{Default (RM) validity checks.}
5167 @cindex @option{-gnatVd} (@command{gcc})
5168 Some validity checks are done by default following normal Ada semantics
5169 (RM 13.9.1 (9-11)).
5170 A check is done in case statements that the expression is within the range
5171 of the subtype. If it is not, Constraint_Error is raised.
5172 For assignments to array components, a check is done that the expression used
5173 as index is within the range. If it is not, Constraint_Error is raised.
5174 Both these validity checks may be turned off using switch @option{-gnatVD}.
5175 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5176 switch @option{-gnatVd} will leave the checks turned on.
5177 Switch @option{-gnatVD} should be used only if you are sure that all such
5178 expressions have valid values. If you use this switch and invalid values
5179 are present, then the program is erroneous, and wild jumps or memory
5180 overwriting may occur.
5181
5182 @item -gnatVf
5183 @emph{Validity checks for floating-point values.}
5184 @cindex @option{-gnatVf} (@command{gcc})
5185 In the absence of this switch, validity checking occurs only for discrete
5186 values. If @option{-gnatVf} is specified, then validity checking also applies
5187 for floating-point values, and NaN's and infinities are considered invalid,
5188 as well as out of range values for constrained types. Note that this means
5189 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5190 in which floating-point values are checked depends on the setting of other
5191 options. For example,
5192 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5193 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5194 (the order does not matter) specifies that floating-point parameters of mode
5195 @code{in} should be validity checked.
5196
5197 @item -gnatVi
5198 @emph{Validity checks for @code{in} mode parameters}
5199 @cindex @option{-gnatVi} (@command{gcc})
5200 Arguments for parameters of mode @code{in} are validity checked in function
5201 and procedure calls at the point of call.
5202
5203 @item -gnatVm
5204 @emph{Validity checks for @code{in out} mode parameters.}
5205 @cindex @option{-gnatVm} (@command{gcc})
5206 Arguments for parameters of mode @code{in out} are validity checked in
5207 procedure calls at the point of call. The @code{'m'} here stands for
5208 modify, since this concerns parameters that can be modified by the call.
5209 Note that there is no specific option to test @code{out} parameters,
5210 but any reference within the subprogram will be tested in the usual
5211 manner, and if an invalid value is copied back, any reference to it
5212 will be subject to validity checking.
5213
5214 @item -gnatVn
5215 @emph{No validity checks.}
5216 @cindex @option{-gnatVn} (@command{gcc})
5217 This switch turns off all validity checking, including the default checking
5218 for case statements and left hand side subscripts. Note that the use of
5219 the switch @option{-gnatp} suppresses all run-time checks, including
5220 validity checks, and thus implies @option{-gnatVn}. When this switch
5221 is used, it cancels any other @option{-gnatV} previously issued.
5222
5223 @item -gnatVo
5224 @emph{Validity checks for operator and attribute operands.}
5225 @cindex @option{-gnatVo} (@command{gcc})
5226 Arguments for predefined operators and attributes are validity checked.
5227 This includes all operators in package @code{Standard},
5228 the shift operators defined as intrinsic in package @code{Interfaces}
5229 and operands for attributes such as @code{Pos}. Checks are also made
5230 on individual component values for composite comparisons.
5231
5232 @item -gnatVp
5233 @emph{Validity checks for parameters.}
5234 @cindex @option{-gnatVp} (@command{gcc})
5235 This controls the treatment of parameters within a subprogram (as opposed
5236 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5237 of parameters on a call. If either of these call options is used, then
5238 normally an assumption is made within a subprogram that the input arguments
5239 have been validity checking at the point of call, and do not need checking
5240 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5241 is not made, and parameters are not assumed to be valid, so their validity
5242 will be checked (or rechecked) within the subprogram.
5243
5244 @item -gnatVr
5245 @emph{Validity checks for function returns.}
5246 @cindex @option{-gnatVr} (@command{gcc})
5247 The expression in @code{return} statements in functions is validity
5248 checked.
5249
5250 @item -gnatVs
5251 @emph{Validity checks for subscripts.}
5252 @cindex @option{-gnatVs} (@command{gcc})
5253 All subscripts expressions are checked for validity, whether they appear
5254 on the right side or left side (in default mode only left side subscripts
5255 are validity checked).
5256
5257 @item -gnatVt
5258 @emph{Validity checks for tests.}
5259 @cindex @option{-gnatVt} (@command{gcc})
5260 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5261 statements are checked, as well as guard expressions in entry calls.
5262
5263 @end table
5264
5265 @noindent
5266 The @option{-gnatV} switch may be followed by
5267 ^a string of letters^a list of options^
5268 to turn on a series of validity checking options.
5269 For example,
5270 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5271 specifies that in addition to the default validity checking, copies and
5272 function return expressions are to be validity checked.
5273 In order to make it easier
5274 to specify the desired combination of effects,
5275 @ifclear vms
5276 the upper case letters @code{CDFIMORST} may
5277 be used to turn off the corresponding lower case option.
5278 @end ifclear
5279 @ifset vms
5280 the prefix @code{NO} on an option turns off the corresponding validity
5281 checking:
5282 @itemize @bullet
5283 @item @code{NOCOPIES}
5284 @item @code{NODEFAULT}
5285 @item @code{NOFLOATS}
5286 @item @code{NOIN_PARAMS}
5287 @item @code{NOMOD_PARAMS}
5288 @item @code{NOOPERANDS}
5289 @item @code{NORETURNS}
5290 @item @code{NOSUBSCRIPTS}
5291 @item @code{NOTESTS}
5292 @end itemize
5293 @end ifset
5294 Thus
5295 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5296 turns on all validity checking options except for
5297 checking of @code{@b{in out}} procedure arguments.
5298
5299 The specification of additional validity checking generates extra code (and
5300 in the case of @option{-gnatVa} the code expansion can be substantial.
5301 However, these additional checks can be very useful in detecting
5302 uninitialized variables, incorrect use of unchecked conversion, and other
5303 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5304 is useful in conjunction with the extra validity checking, since this
5305 ensures that wherever possible uninitialized variables have invalid values.
5306
5307 See also the pragma @code{Validity_Checks} which allows modification of
5308 the validity checking mode at the program source level, and also allows for
5309 temporary disabling of validity checks.
5310
5311 @node Style Checking
5312 @subsection Style Checking
5313 @findex Style checking
5314
5315 @noindent
5316 The @option{-gnaty^x^(option,option,...)^} switch
5317 @cindex @option{-gnaty} (@command{gcc})
5318 causes the compiler to
5319 enforce specified style rules. A limited set of style rules has been used
5320 in writing the GNAT sources themselves. This switch allows user programs
5321 to activate all or some of these checks. If the source program fails a
5322 specified style check, an appropriate warning message is given, preceded by
5323 the character sequence ``(style)''.
5324 @ifset vms
5325 @code{(option,option,...)} is a sequence of keywords
5326 @end ifset
5327 @ifclear vms
5328 The string @var{x} is a sequence of letters or digits
5329 @end ifclear
5330 indicating the particular style
5331 checks to be performed. The following checks are defined:
5332
5333 @table @option
5334 @c !sort!
5335 @item 1-9
5336 @emph{Specify indentation level.}
5337 If a digit from 1-9 appears
5338 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5339 then proper indentation is checked, with the digit indicating the
5340 indentation level required.
5341 The general style of required indentation is as specified by
5342 the examples in the Ada Reference Manual. Full line comments must be
5343 aligned with the @code{--} starting on a column that is a multiple of
5344 the alignment level.
5345
5346 @item ^a^ATTRIBUTE^
5347 @emph{Check attribute casing.}
5348 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5349 then attribute names, including the case of keywords such as @code{digits}
5350 used as attributes names, must be written in mixed case, that is, the
5351 initial letter and any letter following an underscore must be uppercase.
5352 All other letters must be lowercase.
5353
5354 @item ^b^BLANKS^
5355 @emph{Blanks not allowed at statement end.}
5356 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5357 trailing blanks are not allowed at the end of statements. The purpose of this
5358 rule, together with h (no horizontal tabs), is to enforce a canonical format
5359 for the use of blanks to separate source tokens.
5360
5361 @item ^c^COMMENTS^
5362 @emph{Check comments.}
5363 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5364 then comments must meet the following set of rules:
5365
5366 @itemize @bullet
5367
5368 @item
5369 The ``@code{--}'' that starts the column must either start in column one,
5370 or else at least one blank must precede this sequence.
5371
5372 @item
5373 Comments that follow other tokens on a line must have at least one blank
5374 following the ``@code{--}'' at the start of the comment.
5375
5376 @item
5377 Full line comments must have two blanks following the ``@code{--}'' that
5378 starts the comment, with the following exceptions.
5379
5380 @item
5381 A line consisting only of the ``@code{--}'' characters, possibly preceded
5382 by blanks is permitted.
5383
5384 @item
5385 A comment starting with ``@code{--x}'' where @code{x} is a special character
5386 is permitted.
5387 This allows proper processing of the output generated by specialized tools
5388 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5389 annotation
5390 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5391 special character is defined as being in one of the ASCII ranges
5392 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5393 Note that this usage is not permitted
5394 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5395
5396 @item
5397 A line consisting entirely of minus signs, possibly preceded by blanks, is
5398 permitted. This allows the construction of box comments where lines of minus
5399 signs are used to form the top and bottom of the box.
5400
5401 @item
5402 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5403 least one blank follows the initial ``@code{--}''. Together with the preceding
5404 rule, this allows the construction of box comments, as shown in the following
5405 example:
5406 @smallexample
5407 ---------------------------
5408 -- This is a box comment --
5409 -- with two text lines.  --
5410 ---------------------------
5411 @end smallexample
5412 @end itemize
5413
5414 @item ^d^DOS_LINE_ENDINGS^
5415 @emph{Check no DOS line terminators present.}
5416 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5417 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5418 character (in particular the DOS line terminator sequence CR/LF is not
5419 allowed).
5420
5421 @item ^e^END^
5422 @emph{Check end/exit labels.}
5423 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5424 optional labels on @code{end} statements ending subprograms and on
5425 @code{exit} statements exiting named loops, are required to be present.
5426
5427 @item ^f^VTABS^
5428 @emph{No form feeds or vertical tabs.}
5429 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5430 neither form feeds nor vertical tab characters are permitted
5431 in the source text.
5432
5433 @item ^h^HTABS^
5434 @emph{No horizontal tabs.}
5435 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5436 horizontal tab characters are not permitted in the source text.
5437 Together with the b (no blanks at end of line) check, this
5438 enforces a canonical form for the use of blanks to separate
5439 source tokens.
5440
5441 @item ^i^IF_THEN^
5442 @emph{Check if-then layout.}
5443 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5444 then the keyword @code{then} must appear either on the same
5445 line as corresponding @code{if}, or on a line on its own, lined
5446 up under the @code{if} with at least one non-blank line in between
5447 containing all or part of the condition to be tested.
5448
5449 @item ^k^KEYWORD^
5450 @emph{Check keyword casing.}
5451 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5452 all keywords must be in lower case (with the exception of keywords
5453 such as @code{digits} used as attribute names to which this check
5454 does not apply).
5455
5456 @item ^l^LAYOUT^
5457 @emph{Check layout.}
5458 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5459 layout of statement and declaration constructs must follow the
5460 recommendations in the Ada Reference Manual, as indicated by the
5461 form of the syntax rules. For example an @code{else} keyword must
5462 be lined up with the corresponding @code{if} keyword.
5463
5464 There are two respects in which the style rule enforced by this check
5465 option are more liberal than those in the Ada Reference Manual. First
5466 in the case of record declarations, it is permissible to put the
5467 @code{record} keyword on the same line as the @code{type} keyword, and
5468 then the @code{end} in @code{end record} must line up under @code{type}.
5469 For example, either of the following two layouts is acceptable:
5470
5471 @smallexample @c ada
5472 @cartouche
5473 type q is record
5474    a : integer;
5475    b : integer;
5476 end record;
5477
5478 type q is
5479    record
5480       a : integer;
5481       b : integer;
5482    end record;
5483 @end cartouche
5484 @end smallexample
5485
5486 @noindent
5487 Second, in the case of a block statement, a permitted alternative
5488 is to put the block label on the same line as the @code{declare} or
5489 @code{begin} keyword, and then line the @code{end} keyword up under
5490 the block label. For example both the following are permitted:
5491
5492 @smallexample @c ada
5493 @cartouche
5494 Block : declare
5495    A : Integer := 3;
5496 begin
5497    Proc (A, A);
5498 end Block;
5499
5500 Block :
5501    declare
5502       A : Integer := 3;
5503    begin
5504       Proc (A, A);
5505    end Block;
5506 @end cartouche
5507 @end smallexample
5508
5509 @noindent
5510 The same alternative format is allowed for loops. For example, both of
5511 the following are permitted:
5512
5513 @smallexample @c ada
5514 @cartouche
5515 Clear : while J < 10 loop
5516    A (J) := 0;
5517 end loop Clear;
5518
5519 Clear :
5520    while J < 10 loop
5521       A (J) := 0;
5522    end loop Clear;
5523 @end cartouche
5524 @end smallexample
5525
5526 @item ^Lnnn^MAX_NESTING=nnn^
5527 @emph{Set maximum nesting level}
5528 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5529 the range 0-999, appears in the string after @option{-gnaty} then the
5530 maximum level of nesting of constructs (including subprograms, loops,
5531 blocks, packages, and conditionals) may not exceed the given value. A
5532 value of zero disconnects this style check.
5533
5534 @item ^m^LINE_LENGTH^
5535 @emph{Check maximum line length.}
5536 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5537 then the length of source lines must not exceed 79 characters, including
5538 any trailing blanks. The value of 79 allows convenient display on an
5539 80 character wide device or window, allowing for possible special
5540 treatment of 80 character lines. Note that this count is of raw
5541 characters in the source text. This means that a tab character counts
5542 as one character in this count and a wide character sequence counts as
5543 several characters (however many are needed in the encoding).
5544
5545 @item ^Mnnn^MAX_LENGTH=nnn^
5546 @emph{Set maximum line length.}
5547 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5548 the string after @option{-gnaty} then the length of lines must not exceed the
5549 given value.
5550
5551 @item ^n^STANDARD_CASING^
5552 @emph{Check casing of entities in Standard.}
5553 If the ^letter n^word STANDARD_CASING^ appears in the string
5554 after @option{-gnaty} then any identifier from Standard must be cased
5555 to match the presentation in the Ada Reference Manual (for example,
5556 @code{Integer} and @code{ASCII.NUL}).
5557
5558 @item ^o^ORDERED_SUBPROGRAMS^
5559 @emph{Check order of subprogram bodies.}
5560 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5561 after @option{-gnaty} then all subprogram bodies in a given scope
5562 (e.g. a package body) must be in alphabetical order. The ordering
5563 rule uses normal Ada rules for comparing strings, ignoring casing
5564 of letters, except that if there is a trailing numeric suffix, then
5565 the value of this suffix is used in the ordering (e.g. Junk2 comes
5566 before Junk10).
5567
5568 @item ^p^PRAGMA^
5569 @emph{Check pragma casing.}
5570 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5571 pragma names must be written in mixed case, that is, the
5572 initial letter and any letter following an underscore must be uppercase.
5573 All other letters must be lowercase.
5574
5575 @item ^r^REFERENCES^
5576 @emph{Check references.}
5577 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5578 then all identifier references must be cased in the same way as the
5579 corresponding declaration. No specific casing style is imposed on
5580 identifiers. The only requirement is for consistency of references
5581 with declarations.
5582
5583 @item ^s^SPECS^
5584 @emph{Check separate specs.}
5585 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5586 separate declarations (``specs'') are required for subprograms (a
5587 body is not allowed to serve as its own declaration). The only
5588 exception is that parameterless library level procedures are
5589 not required to have a separate declaration. This exception covers
5590 the most frequent form of main program procedures.
5591
5592 @item ^t^TOKEN^
5593 @emph{Check token spacing.}
5594 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5595 the following token spacing rules are enforced:
5596
5597 @itemize @bullet
5598
5599 @item
5600 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5601
5602 @item
5603 The token @code{=>} must be surrounded by spaces.
5604
5605 @item
5606 The token @code{<>} must be preceded by a space or a left parenthesis.
5607
5608 @item
5609 Binary operators other than @code{**} must be surrounded by spaces.
5610 There is no restriction on the layout of the @code{**} binary operator.
5611
5612 @item
5613 Colon must be surrounded by spaces.
5614
5615 @item
5616 Colon-equal (assignment, initialization) must be surrounded by spaces.
5617
5618 @item
5619 Comma must be the first non-blank character on the line, or be
5620 immediately preceded by a non-blank character, and must be followed
5621 by a space.
5622
5623 @item
5624 If the token preceding a left parenthesis ends with a letter or digit, then
5625 a space must separate the two tokens.
5626
5627 @item
5628 A right parenthesis must either be the first non-blank character on
5629 a line, or it must be preceded by a non-blank character.
5630
5631 @item
5632 A semicolon must not be preceded by a space, and must not be followed by
5633 a non-blank character.
5634
5635 @item
5636 A unary plus or minus may not be followed by a space.
5637
5638 @item
5639 A vertical bar must be surrounded by spaces.
5640 @end itemize
5641
5642 @item ^u^UNNECESSARY_BLANK_LINES^
5643 @emph{Check unnecessary blank lines.}
5644 Check for unnecessary blank lines. A blank line is considered
5645 unnecessary if it appears at the end of the file, or if more than
5646 one blank line occurs in sequence.
5647
5648 @item ^x^XTRA_PARENS^
5649 @emph{Check extra parentheses.}
5650 Check for the use of an unnecessary extra level of parentheses (C-style)
5651 around conditions in @code{if} statements, @code{while} statements and
5652 @code{exit} statements.
5653
5654 @end table
5655
5656 @noindent
5657 In the above rules, appearing in column one is always permitted, that is,
5658 counts as meeting either a requirement for a required preceding space,
5659 or as meeting a requirement for no preceding space.
5660
5661 Appearing at the end of a line is also always permitted, that is, counts
5662 as meeting either a requirement for a following space, or as meeting
5663 a requirement for no following space.
5664
5665 @noindent
5666 If any of these style rules is violated, a message is generated giving
5667 details on the violation. The initial characters of such messages are
5668 always ``@code{(style)}''. Note that these messages are treated as warning
5669 messages, so they normally do not prevent the generation of an object
5670 file. The @option{-gnatwe} switch can be used to treat warning messages,
5671 including style messages, as fatal errors.
5672
5673 The switch
5674 @ifclear vms
5675 @option{-gnaty} on its own (that is not
5676 followed by any letters or digits),
5677 is equivalent to @code{gnaty3abcefhiklmnprst}, that is all checking
5678 options enabled with the exception of @option{-gnatyo},
5679 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
5680 @end ifclear
5681 @ifset vms
5682 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5683 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
5684 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
5685 @end ifset
5686 an indentation level of 3 is set. This is similar to the standard
5687 checking option that is used for the GNAT sources.
5688
5689 The switch
5690 @ifclear vms
5691 @option{-gnatyN}
5692 @end ifclear
5693 @ifset vms
5694 /STYLE_CHECKS=NONE
5695 @end ifset
5696 clears any previously set style checks.
5697
5698 @node Run-Time Checks
5699 @subsection Run-Time Checks
5700 @cindex Division by zero
5701 @cindex Access before elaboration
5702 @cindex Checks, division by zero
5703 @cindex Checks, access before elaboration
5704
5705 @noindent
5706 If you compile with the default options, GNAT will insert many run-time
5707 checks into the compiled code, including code that performs range
5708 checking against constraints, but not arithmetic overflow checking for
5709 integer operations (including division by zero) or checks for access
5710 before elaboration on subprogram calls. All other run-time checks, as
5711 required by the Ada 95 Reference Manual, are generated by default.
5712 The following @command{gcc} switches refine this default behavior:
5713
5714 @table @option
5715 @c !sort!
5716 @item -gnatp
5717 @cindex @option{-gnatp} (@command{gcc})
5718 @cindex Suppressing checks
5719 @cindex Checks, suppressing
5720 @findex Suppress
5721 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5722 had been present in the source. Validity checks are also suppressed (in
5723 other words @option{-gnatp} also implies @option{-gnatVn}.
5724 Use this switch to improve the performance
5725 of the code at the expense of safety in the presence of invalid data or
5726 program bugs.
5727
5728 @item -gnato
5729 @cindex @option{-gnato} (@command{gcc})
5730 @cindex Overflow checks
5731 @cindex Check, overflow
5732 Enables overflow checking for integer operations.
5733 This causes GNAT to generate slower and larger executable
5734 programs by adding code to check for overflow (resulting in raising
5735 @code{Constraint_Error} as required by standard Ada
5736 semantics). These overflow checks correspond to situations in which
5737 the true value of the result of an operation may be outside the base
5738 range of the result type. The following example shows the distinction:
5739
5740 @smallexample @c ada
5741 X1 : Integer := Integer'Last;
5742 X2 : Integer range 1 .. 5 := 5;
5743 X3 : Integer := Integer'Last;
5744 X4 : Integer range 1 .. 5 := 5;
5745 F  : Float := 2.0E+20;
5746 ...
5747 X1 := X1 + 1;
5748 X2 := X2 + 1;
5749 X3 := Integer (F);
5750 X4 := Integer (F);
5751 @end smallexample
5752
5753 @noindent
5754 Here the first addition results in a value that is outside the base range
5755 of Integer, and hence requires an overflow check for detection of the
5756 constraint error. Thus the first assignment to @code{X1} raises a
5757 @code{Constraint_Error} exception only if @option{-gnato} is set.
5758
5759 The second increment operation results in a violation
5760 of the explicit range constraint, and such range checks are always
5761 performed (unless specifically suppressed with a pragma @code{suppress}
5762 or the use of @option{-gnatp}).
5763
5764 The two conversions of @code{F} both result in values that are outside
5765 the base range of type @code{Integer} and thus will raise
5766 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5767 The fact that the result of the second conversion is assigned to
5768 variable @code{X4} with a restricted range is irrelevant, since the problem
5769 is in the conversion, not the assignment.
5770
5771 Basically the rule is that in the default mode (@option{-gnato} not
5772 used), the generated code assures that all integer variables stay
5773 within their declared ranges, or within the base range if there is
5774 no declared range. This prevents any serious problems like indexes
5775 out of range for array operations.
5776
5777 What is not checked in default mode is an overflow that results in
5778 an in-range, but incorrect value. In the above example, the assignments
5779 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5780 range of the target variable, but the result is wrong in the sense that
5781 it is too large to be represented correctly. Typically the assignment
5782 to @code{X1} will result in wrap around to the largest negative number.
5783 The conversions of @code{F} will result in some @code{Integer} value
5784 and if that integer value is out of the @code{X4} range then the
5785 subsequent assignment would generate an exception.
5786
5787 @findex Machine_Overflows
5788 Note that the @option{-gnato} switch does not affect the code generated
5789 for any floating-point operations; it applies only to integer
5790 semantics).
5791 For floating-point, GNAT has the @code{Machine_Overflows}
5792 attribute set to @code{False} and the normal mode of operation is to
5793 generate IEEE NaN and infinite values on overflow or invalid operations
5794 (such as dividing 0.0 by 0.0).
5795
5796 The reason that we distinguish overflow checking from other kinds of
5797 range constraint checking is that a failure of an overflow check can
5798 generate an incorrect value, but cannot cause erroneous behavior. This
5799 is unlike the situation with a constraint check on an array subscript,
5800 where failure to perform the check can result in random memory description,
5801 or the range check on a case statement, where failure to perform the check
5802 can cause a wild jump.
5803
5804 Note again that @option{-gnato} is off by default, so overflow checking is
5805 not performed in default mode. This means that out of the box, with the
5806 default settings, GNAT does not do all the checks expected from the
5807 language description in the Ada Reference Manual. If you want all constraint
5808 checks to be performed, as described in this Manual, then you must
5809 explicitly use the -gnato switch either on the @command{gnatmake} or
5810 @command{gcc} command.
5811
5812 @item -gnatE
5813 @cindex @option{-gnatE} (@command{gcc})
5814 @cindex Elaboration checks
5815 @cindex Check, elaboration
5816 Enables dynamic checks for access-before-elaboration
5817 on subprogram calls and generic instantiations.
5818 For full details of the effect and use of this switch,
5819 @xref{Compiling Using gcc}.
5820 @end table
5821
5822 @findex Unsuppress
5823 @noindent
5824 The setting of these switches only controls the default setting of the
5825 checks. You may modify them using either @code{Suppress} (to remove
5826 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5827 the program source.
5828
5829 @node Stack Overflow Checking
5830 @subsection Stack Overflow Checking
5831 @cindex Stack Overflow Checking
5832 @cindex -fstack-check
5833
5834 @noindent
5835 For most operating systems, @command{gcc} does not perform stack overflow
5836 checking by default. This means that if the main environment task or
5837 some other task exceeds the available stack space, then unpredictable
5838 behavior will occur.
5839
5840 To activate stack checking, compile all units with the gcc option
5841 @option{-fstack-check}. For example:
5842
5843 @smallexample
5844 gcc -c -fstack-check package1.adb
5845 @end smallexample
5846
5847 @noindent
5848 Units compiled with this option will generate extra instructions to check
5849 that any use of the stack (for procedure calls or for declaring local
5850 variables in declare blocks) do not exceed the available stack space.
5851 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5852
5853 For declared tasks, the stack size is always controlled by the size
5854 given in an applicable @code{Storage_Size} pragma (or is set to
5855 the default size if no pragma is used.
5856
5857 For the environment task, the stack size depends on
5858 system defaults and is unknown to the compiler. The stack
5859 may even dynamically grow on some systems, precluding the
5860 normal Ada semantics for stack overflow. In the worst case,
5861 unbounded stack usage, causes unbounded stack expansion
5862 resulting in the system running out of virtual memory.
5863
5864 The stack checking may still work correctly if a fixed
5865 size stack is allocated, but this cannot be guaranteed.
5866 To ensure that a clean exception is signalled for stack
5867 overflow, set the environment variable
5868 @code{GNAT_STACK_LIMIT} to indicate the maximum
5869 stack area that can be used, as in:
5870 @cindex GNAT_STACK_LIMIT
5871
5872 @smallexample
5873 SET GNAT_STACK_LIMIT 1600
5874 @end smallexample
5875
5876 @noindent
5877 The limit is given in kilobytes, so the above declaration would
5878 set the stack limit of the environment task to 1.6 megabytes.
5879 Note that the only purpose of this usage is to limit the amount
5880 of stack used by the environment task. If it is necessary to
5881 increase the amount of stack for the environment task, then this
5882 is an operating systems issue, and must be addressed with the
5883 appropriate operating systems commands.
5884
5885 @node Using gcc for Syntax Checking
5886 @subsection Using @command{gcc} for Syntax Checking
5887 @table @option
5888 @item -gnats
5889 @cindex @option{-gnats} (@command{gcc})
5890 @ifclear vms
5891
5892 @noindent
5893 The @code{s} stands for ``syntax''.
5894 @end ifclear
5895
5896 Run GNAT in syntax checking only mode. For
5897 example, the command
5898
5899 @smallexample
5900 $ gcc -c -gnats x.adb
5901 @end smallexample
5902
5903 @noindent
5904 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5905 series of files in a single command
5906 @ifclear vms
5907 , and can use wild cards to specify such a group of files.
5908 Note that you must specify the @option{-c} (compile
5909 only) flag in addition to the @option{-gnats} flag.
5910 @end ifclear
5911 .
5912 You may use other switches in conjunction with @option{-gnats}. In
5913 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5914 format of any generated error messages.
5915
5916 When the source file is empty or contains only empty lines and/or comments,
5917 the output is a warning:
5918
5919 @smallexample
5920 $ gcc -c -gnats -x ada toto.txt
5921 toto.txt:1:01: warning: empty file, contains no compilation units
5922 $
5923 @end smallexample
5924
5925 Otherwise, the output is simply the error messages, if any. No object file or
5926 ALI file is generated by a syntax-only compilation. Also, no units other
5927 than the one specified are accessed. For example, if a unit @code{X}
5928 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5929 check only mode does not access the source file containing unit
5930 @code{Y}.
5931
5932 @cindex Multiple units, syntax checking
5933 Normally, GNAT allows only a single unit in a source file. However, this
5934 restriction does not apply in syntax-check-only mode, and it is possible
5935 to check a file containing multiple compilation units concatenated
5936 together. This is primarily used by the @code{gnatchop} utility
5937 (@pxref{Renaming Files Using gnatchop}).
5938 @end table
5939
5940 @node Using gcc for Semantic Checking
5941 @subsection Using @command{gcc} for Semantic Checking
5942 @table @option
5943 @item -gnatc
5944 @cindex @option{-gnatc} (@command{gcc})
5945
5946 @ifclear vms
5947 @noindent
5948 The @code{c} stands for ``check''.
5949 @end ifclear
5950 Causes the compiler to operate in semantic check mode,
5951 with full checking for all illegalities specified in the
5952 Ada 95 Reference Manual, but without generation of any object code
5953 (no object file is generated).
5954
5955 Because dependent files must be accessed, you must follow the GNAT
5956 semantic restrictions on file structuring to operate in this mode:
5957
5958 @itemize @bullet
5959 @item
5960 The needed source files must be accessible
5961 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5962
5963 @item
5964 Each file must contain only one compilation unit.
5965
5966 @item
5967 The file name and unit name must match (@pxref{File Naming Rules}).
5968 @end itemize
5969
5970 The output consists of error messages as appropriate. No object file is
5971 generated. An @file{ALI} file is generated for use in the context of
5972 cross-reference tools, but this file is marked as not being suitable
5973 for binding (since no object file is generated).
5974 The checking corresponds exactly to the notion of
5975 legality in the Ada 95 Reference Manual.
5976
5977 Any unit can be compiled in semantics-checking-only mode, including
5978 units that would not normally be compiled (subunits,
5979 and specifications where a separate body is present).
5980 @end table
5981
5982 @node Compiling Different Versions of Ada
5983 @subsection Compiling Different Versions of Ada
5984 @table @option
5985 @cindex Compatibility with Ada 83
5986 @cindex Ada 83 mode
5987 @cindex Ada 95 mode
5988 @cindex Ada 2005 mode
5989
5990 GNAT is primarily an Ada 95 compiler, but the switches described in
5991 this section allow operation in Ada 83 compatibility mode, and also
5992 allow the use of a preliminary implementation of many of the expected
5993 new features in Ada 2005, the forthcoming new version of the standard.
5994
5995 @item -gnat83 (Ada 83 Compatibility Mode)
5996 @cindex @option{-gnat83} (@command{gcc})
5997 @cindex ACVC, Ada 83 tests
5998
5999 @noindent
6000 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
6001 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
6002 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
6003 where this can be done easily.
6004 It is not possible to guarantee this switch does a perfect
6005 job; for example, some subtle tests, such as are
6006 found in earlier ACVC tests (and that have been removed from the ACATS suite
6007 for Ada 95), might not compile correctly.
6008 Nevertheless, this switch may be useful in some circumstances, for example
6009 where, due to contractual reasons, legacy code needs to be maintained
6010 using only Ada 83 features.
6011
6012 With few exceptions (most notably the need to use @code{<>} on
6013 @cindex Generic formal parameters
6014 unconstrained generic formal parameters, the use of the new Ada 95
6015 reserved words, and the use of packages
6016 with optional bodies), it is not necessary to use the
6017 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6018 exceptions, Ada 95 is upwardly compatible with Ada 83. This
6019 means that a correct Ada 83 program is usually also a correct Ada 95
6020 program.
6021 For further information, please refer to @ref{Compatibility and Porting Guide}.
6022
6023 @item -gnat95 (Ada 95 mode)
6024 @cindex @option{-gnat95} (@command{gcc})
6025
6026 @noindent
6027 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
6028 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
6029 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
6030 this default Ada95 mode without problems (see section above describing the
6031 use of @option{-gnat83} to run in Ada 83 mode).
6032
6033 In Ada 95 mode, the use of Ada 2005 features will in general cause error
6034 messages or warnings. Some specialized releases of GNAT (notably the GAP
6035 academic version) operate in Ada 2005 mode by default (see section below
6036 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
6037 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
6038 This option also can be used to cancel the effect of a previous
6039 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6040
6041
6042 @item -gnat05 (Ada 2005 mode)
6043 @cindex @option{-gnat05} (@command{gcc})
6044
6045 @noindent
6046 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
6047 in Ada 2005 mode using this option. Although the new standard has not
6048 yet been issued (as of early 2005), many features have been discussed and
6049 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
6050 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
6051 releases is a file @file{features-ada0y} that describes the current set
6052 of implemented Ada 2005 features.
6053
6054 If these features are used in Ada 95 mode (which is the normal default),
6055 then error messages or warnings may be
6056 generated, reflecting the fact that these new features are otherwise
6057 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
6058 switch (or an equivalent pragma) causes these messages to be suppressed.
6059
6060 Note that some specialized releases of GNAT (notably the GAP academic
6061 version) have Ada 2005 mode on by default, and in such environments,
6062 the Ada 2005 features can be used freely without the use of switches.
6063
6064 @end table
6065
6066 @node Character Set Control
6067 @subsection Character Set Control
6068 @table @option
6069 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6070 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6071
6072 @noindent
6073 Normally GNAT recognizes the Latin-1 character set in source program
6074 identifiers, as described in the Ada 95 Reference Manual.
6075 This switch causes
6076 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6077 single character ^^or word^ indicating the character set, as follows:
6078
6079 @table @code
6080 @item 1
6081 ISO 8859-1 (Latin-1) identifiers
6082
6083 @item 2
6084 ISO 8859-2 (Latin-2) letters allowed in identifiers
6085
6086 @item 3
6087 ISO 8859-3 (Latin-3) letters allowed in identifiers
6088
6089 @item 4
6090 ISO 8859-4 (Latin-4) letters allowed in identifiers
6091
6092 @item 5
6093 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6094
6095 @item 9
6096 ISO 8859-15 (Latin-9) letters allowed in identifiers
6097
6098 @item ^p^PC^
6099 IBM PC letters (code page 437) allowed in identifiers
6100
6101 @item ^8^PC850^
6102 IBM PC letters (code page 850) allowed in identifiers
6103
6104 @item ^f^FULL_UPPER^
6105 Full upper-half codes allowed in identifiers
6106
6107 @item ^n^NO_UPPER^
6108 No upper-half codes allowed in identifiers
6109
6110 @item ^w^WIDE^
6111 Wide-character codes (that is, codes greater than 255)
6112 allowed in identifiers
6113 @end table
6114
6115 @xref{Foreign Language Representation}, for full details on the
6116 implementation of these character sets.
6117
6118 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6119 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6120 Specify the method of encoding for wide characters.
6121 @var{e} is one of the following:
6122
6123 @table @code
6124
6125 @item ^h^HEX^
6126 Hex encoding (brackets coding also recognized)
6127
6128 @item ^u^UPPER^
6129 Upper half encoding (brackets encoding also recognized)
6130
6131 @item ^s^SHIFT_JIS^
6132 Shift/JIS encoding (brackets encoding also recognized)
6133
6134 @item ^e^EUC^
6135 EUC encoding (brackets encoding also recognized)
6136
6137 @item ^8^UTF8^
6138 UTF-8 encoding (brackets encoding also recognized)
6139
6140 @item ^b^BRACKETS^
6141 Brackets encoding only (default value)
6142 @end table
6143 For full details on the these encoding
6144 methods see @ref{Wide Character Encodings}.
6145 Note that brackets coding is always accepted, even if one of the other
6146 options is specified, so for example @option{-gnatW8} specifies that both
6147 brackets and @code{UTF-8} encodings will be recognized. The units that are
6148 with'ed directly or indirectly will be scanned using the specified
6149 representation scheme, and so if one of the non-brackets scheme is
6150 used, it must be used consistently throughout the program. However,
6151 since brackets encoding is always recognized, it may be conveniently
6152 used in standard libraries, allowing these libraries to be used with
6153 any of the available coding schemes.
6154 scheme. If no @option{-gnatW?} parameter is present, then the default
6155 representation is Brackets encoding only.
6156
6157 Note that the wide character representation that is specified (explicitly
6158 or by default) for the main program also acts as the default encoding used
6159 for Wide_Text_IO files if not specifically overridden by a WCEM form
6160 parameter.
6161
6162 @end table
6163 @node File Naming Control
6164 @subsection File Naming Control
6165
6166 @table @option
6167 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6168 @cindex @option{-gnatk} (@command{gcc})
6169 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6170 1-999, indicates the maximum allowable length of a file name (not
6171 including the @file{.ads} or @file{.adb} extension). The default is not
6172 to enable file name krunching.
6173
6174 For the source file naming rules, @xref{File Naming Rules}.
6175 @end table
6176
6177 @node Subprogram Inlining Control
6178 @subsection Subprogram Inlining Control
6179
6180 @table @option
6181 @c !sort!
6182 @item -gnatn
6183 @cindex @option{-gnatn} (@command{gcc})
6184 @ifclear vms
6185 The @code{n} here is intended to suggest the first syllable of the
6186 word ``inline''.
6187 @end ifclear
6188 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6189 inlining to actually occur, optimization must be enabled. To enable
6190 inlining of subprograms specified by pragma @code{Inline},
6191 you must also specify this switch.
6192 In the absence of this switch, GNAT does not attempt
6193 inlining and does not need to access the bodies of
6194 subprograms for which @code{pragma Inline} is specified if they are not
6195 in the current unit.
6196
6197 If you specify this switch the compiler will access these bodies,
6198 creating an extra source dependency for the resulting object file, and
6199 where possible, the call will be inlined.
6200 For further details on when inlining is possible
6201 see @ref{Inlining of Subprograms}.
6202
6203 @item -gnatN
6204 @cindex @option{-gnatN} (@command{gcc})
6205 The front end inlining activated by this switch is generally more extensive,
6206 and quite often more effective than the standard @option{-gnatn} inlining mode.
6207 It will also generate additional dependencies.
6208 Note that
6209 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6210 to specify both options.
6211 @end table
6212
6213 @node Auxiliary Output Control
6214 @subsection Auxiliary Output Control
6215
6216 @table @option
6217 @item -gnatt
6218 @cindex @option{-gnatt} (@command{gcc})
6219 @cindex Writing internal trees
6220 @cindex Internal trees, writing to file
6221 Causes GNAT to write the internal tree for a unit to a file (with the
6222 extension @file{.adt}.
6223 This not normally required, but is used by separate analysis tools.
6224 Typically
6225 these tools do the necessary compilations automatically, so you should
6226 not have to specify this switch in normal operation.
6227
6228 @item -gnatu
6229 @cindex @option{-gnatu} (@command{gcc})
6230 Print a list of units required by this compilation on @file{stdout}.
6231 The listing includes all units on which the unit being compiled depends
6232 either directly or indirectly.
6233
6234 @ifclear vms
6235 @item -pass-exit-codes
6236 @cindex @option{-pass-exit-codes} (@command{gcc})
6237 If this switch is not used, the exit code returned by @command{gcc} when
6238 compiling multiple files indicates whether all source files have
6239 been successfully used to generate object files or not.
6240
6241 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6242 exit status and allows an integrated development environment to better
6243 react to a compilation failure. Those exit status are:
6244
6245 @table @asis
6246 @item 5
6247 There was an error in at least one source file.
6248 @item 3
6249 At least one source file did not generate an object file.
6250 @item 2
6251 The compiler died unexpectedly (internal error for example).
6252 @item 0
6253 An object file has been generated for every source file.
6254 @end table
6255 @end ifclear
6256 @end table
6257
6258 @node Debugging Control
6259 @subsection Debugging Control
6260
6261 @table @option
6262 @c !sort!
6263 @cindex Debugging options
6264 @ifclear vms
6265 @item -gnatd@var{x}
6266 @cindex @option{-gnatd} (@command{gcc})
6267 Activate internal debugging switches. @var{x} is a letter or digit, or
6268 string of letters or digits, which specifies the type of debugging
6269 outputs desired. Normally these are used only for internal development
6270 or system debugging purposes. You can find full documentation for these
6271 switches in the body of the @code{Debug} unit in the compiler source
6272 file @file{debug.adb}.
6273 @end ifclear
6274
6275 @item -gnatG
6276 @cindex @option{-gnatG} (@command{gcc})
6277 This switch causes the compiler to generate auxiliary output containing
6278 a pseudo-source listing of the generated expanded code. Like most Ada
6279 compilers, GNAT works by first transforming the high level Ada code into
6280 lower level constructs. For example, tasking operations are transformed
6281 into calls to the tasking run-time routines. A unique capability of GNAT
6282 is to list this expanded code in a form very close to normal Ada source.
6283 This is very useful in understanding the implications of various Ada
6284 usage on the efficiency of the generated code. There are many cases in
6285 Ada (e.g. the use of controlled types), where simple Ada statements can
6286 generate a lot of run-time code. By using @option{-gnatG} you can identify
6287 these cases, and consider whether it may be desirable to modify the coding
6288 approach to improve efficiency.
6289
6290 The format of the output is very similar to standard Ada source, and is
6291 easily understood by an Ada programmer. The following special syntactic
6292 additions correspond to low level features used in the generated code that
6293 do not have any exact analogies in pure Ada source form. The following
6294 is a partial list of these special constructions. See the specification
6295 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6296
6297 @table @code
6298 @item new @var{xxx} [storage_pool = @var{yyy}]
6299 Shows the storage pool being used for an allocator.
6300
6301 @item at end @var{procedure-name};
6302 Shows the finalization (cleanup) procedure for a scope.
6303
6304 @item (if @var{expr} then @var{expr} else @var{expr})
6305 Conditional expression equivalent to the @code{x?y:z} construction in C.
6306
6307 @item @var{target}^^^(@var{source})
6308 A conversion with floating-point truncation instead of rounding.
6309
6310 @item @var{target}?(@var{source})
6311 A conversion that bypasses normal Ada semantic checking. In particular
6312 enumeration types and fixed-point types are treated simply as integers.
6313
6314 @item @var{target}?^^^(@var{source})
6315 Combines the above two cases.
6316
6317 @item @var{x} #/ @var{y}
6318 @itemx @var{x} #mod @var{y}
6319 @itemx @var{x} #* @var{y}
6320 @itemx @var{x} #rem @var{y}
6321 A division or multiplication of fixed-point values which are treated as
6322 integers without any kind of scaling.
6323
6324 @item free @var{expr} [storage_pool = @var{xxx}]
6325 Shows the storage pool associated with a @code{free} statement.
6326
6327 @item freeze @var{typename} [@var{actions}]
6328 Shows the point at which @var{typename} is frozen, with possible
6329 associated actions to be performed at the freeze point.
6330
6331 @item reference @var{itype}
6332 Reference (and hence definition) to internal type @var{itype}.
6333
6334 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6335 Intrinsic function call.
6336
6337 @item @var{labelname} : label
6338 Declaration of label @var{labelname}.
6339
6340 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6341 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6342 @var{expr}, but handled more efficiently).
6343
6344 @item [constraint_error]
6345 Raise the @code{Constraint_Error} exception.
6346
6347 @item @var{expression}'reference
6348 A pointer to the result of evaluating @var{expression}.
6349
6350 @item @var{target-type}!(@var{source-expression})
6351 An unchecked conversion of @var{source-expression} to @var{target-type}.
6352
6353 @item [@var{numerator}/@var{denominator}]
6354 Used to represent internal real literals (that) have no exact
6355 representation in base 2-16 (for example, the result of compile time
6356 evaluation of the expression 1.0/27.0).
6357 @end table
6358
6359 @item -gnatD
6360 @cindex @option{-gnatD} (@command{gcc})
6361 When used in conjunction with @option{-gnatG}, this switch causes
6362 the expanded source, as described above for
6363 @option{-gnatG} to be written to files with names
6364 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6365 instead of to the standard ooutput file. For
6366 example, if the source file name is @file{hello.adb}, then a file
6367 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6368 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6369 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6370 you to do source level debugging using the generated code which is
6371 sometimes useful for complex code, for example to find out exactly
6372 which part of a complex construction raised an exception. This switch
6373 also suppress generation of cross-reference information (see
6374 @option{-gnatx}) since otherwise the cross-reference information
6375 would refer to the @file{^.dg^.DG^} file, which would cause
6376 confusion since this is not the original source file.
6377
6378 Note that @option{-gnatD} actually implies @option{-gnatG}
6379 automatically, so it is not necessary to give both options.
6380 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6381
6382 @ifclear vms
6383 @item -gnatR[0|1|2|3[s]]
6384 @cindex @option{-gnatR} (@command{gcc})
6385 This switch controls output from the compiler of a listing showing
6386 representation information for declared types and objects. For
6387 @option{-gnatR0}, no information is output (equivalent to omitting
6388 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6389 so @option{-gnatR} with no parameter has the same effect), size and alignment
6390 information is listed for declared array and record types. For
6391 @option{-gnatR2}, size and alignment information is listed for all
6392 expression information for values that are computed at run time for
6393 variant records. These symbolic expressions have a mostly obvious
6394 format with #n being used to represent the value of the n'th
6395 discriminant. See source files @file{repinfo.ads/adb} in the
6396 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6397 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6398 the output is to a file with the name @file{^file.rep^file_REP^} where
6399 file is the name of the corresponding source file.
6400 @end ifclear
6401 @ifset vms
6402 @item /REPRESENTATION_INFO
6403 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6404 This qualifier controls output from the compiler of a listing showing
6405 representation information for declared types and objects. For
6406 @option{/REPRESENTATION_INFO=NONE}, no information is output
6407 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6408 @option{/REPRESENTATION_INFO} without option is equivalent to
6409 @option{/REPRESENTATION_INFO=ARRAYS}.
6410 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6411 information is listed for declared array and record types. For
6412 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6413 is listed for all expression information for values that are computed
6414 at run time for variant records. These symbolic expressions have a mostly
6415 obvious format with #n being used to represent the value of the n'th
6416 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6417 @code{GNAT} sources for full details on the format of
6418 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6419 If _FILE is added at the end of an option
6420 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6421 then the output is to a file with the name @file{file_REP} where
6422 file is the name of the corresponding source file.
6423 @end ifset
6424
6425 @item -gnatS
6426 @cindex @option{-gnatS} (@command{gcc})
6427 The use of the switch @option{-gnatS} for an
6428 Ada compilation will cause the compiler to output a
6429 representation of package Standard in a form very
6430 close to standard Ada. It is not quite possible to
6431 do this entirely in standard Ada (since new
6432 numeric base types cannot be created in standard
6433 Ada), but the output is easily
6434 readable to any Ada programmer, and is useful to
6435 determine the characteristics of target dependent
6436 types in package Standard.
6437
6438 @item -gnatx
6439 @cindex @option{-gnatx} (@command{gcc})
6440 Normally the compiler generates full cross-referencing information in
6441 the @file{ALI} file. This information is used by a number of tools,
6442 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6443 suppresses this information. This saves some space and may slightly
6444 speed up compilation, but means that these tools cannot be used.
6445 @end table
6446
6447 @node Exception Handling Control
6448 @subsection Exception Handling Control
6449
6450 @noindent
6451 GNAT uses two methods for handling exceptions at run-time. The
6452 @code{setjmp/longjmp} method saves the context when entering
6453 a frame with an exception handler. Then when an exception is
6454 raised, the context can be restored immediately, without the
6455 need for tracing stack frames. This method provides very fast
6456 exception propagation, but introduces significant overhead for
6457 the use of exception handlers, even if no exception is raised.
6458
6459 The other approach is called ``zero cost'' exception handling.
6460 With this method, the compiler builds static tables to describe
6461 the exception ranges. No dynamic code is required when entering
6462 a frame containing an exception handler. When an exception is
6463 raised, the tables are used to control a back trace of the
6464 subprogram invocation stack to locate the required exception
6465 handler. This method has considerably poorer performance for
6466 the propagation of exceptions, but there is no overhead for
6467 exception handlers if no exception is raised. Note that in this
6468 mode and in the context of mixed Ada and C/C++ programming,
6469 to propagate an exception through a C/C++ code, the C/C++ code
6470 must be compiled with the @option{-funwind-tables} GCC's
6471 option.
6472
6473 The following switches can be used to control which of the
6474 two exception handling methods is used.
6475
6476 @table @option
6477 @c !sort!
6478
6479 @item --RTS=sjlj
6480 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6481 This switch causes the setjmp/longjmp run-time to be used
6482 for exception handling. If this is the default mechanism for the
6483 target (see below), then this has no effect. If the default
6484 mechanism for the target is zero cost exceptions, then
6485 this switch can be used to modify this default, and must be
6486 used for all units in the partition.
6487 This option is rarely used. One case in which it may be
6488 advantageous is if you have an application where exception
6489 raising is common and the overall performance of the
6490 application is improved by favoring exception propagation.
6491
6492 @item --RTS=zcx
6493 @cindex @option{--RTS=zcx} (@command{gnatmake})
6494 @cindex Zero Cost Exceptions
6495 This switch causes the zero cost approach to be used
6496 for exception handling. If this is the default mechanism for the
6497 target (see below), then this has no effect. If the default
6498 mechanism for the target is setjmp/longjmp exceptions, then
6499 this switch can be used to modify this default, and must be
6500 used for all units in the partition.
6501 This option can only be used if the zero cost approach
6502 is available for the target in use (see below).
6503 @end table
6504
6505 @noindent
6506 The @code{setjmp/longjmp} approach is available on all targets, while
6507 the @code{zero cost} approach is available on selected targets.
6508 To determine whether zero cost exceptions can be used for a
6509 particular target, look at the private part of the file system.ads.
6510 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6511 be True to use the zero cost approach. If both of these switches
6512 are set to False, this means that zero cost exception handling
6513 is not yet available for that target. The switch
6514 @code{ZCX_By_Default} indicates the default approach. If this
6515 switch is set to True, then the @code{zero cost} approach is
6516 used by default.
6517
6518 @node Units to Sources Mapping Files
6519 @subsection Units to Sources Mapping Files
6520
6521 @table @option
6522
6523 @item -gnatem^^=^@var{path}
6524 @cindex @option{-gnatem} (@command{gcc})
6525 A mapping file is a way to communicate to the compiler two mappings:
6526 from unit names to file names (without any directory information) and from
6527 file names to path names (with full directory information). These mappings
6528 are used by the compiler to short-circuit the path search.
6529
6530 The use of mapping files is not required for correct operation of the
6531 compiler, but mapping files can improve efficiency, particularly when
6532 sources are read over a slow network connection. In normal operation,
6533 you need not be concerned with the format or use of mapping files,
6534 and the @option{-gnatem} switch is not a switch that you would use
6535 explicitly. it is intended only for use by automatic tools such as
6536 @command{gnatmake} running under the project file facility. The
6537 description here of the format of mapping files is provided
6538 for completeness and for possible use by other tools.
6539
6540 A mapping file is a sequence of sets of three lines. In each set,
6541 the first line is the unit name, in lower case, with ``@code{%s}''
6542 appended for
6543 specifications and ``@code{%b}'' appended for bodies; the second line is the
6544 file name; and the third line is the path name.
6545
6546 Example:
6547 @smallexample
6548    main%b
6549    main.2.ada
6550    /gnat/project1/sources/main.2.ada
6551 @end smallexample
6552
6553 When the switch @option{-gnatem} is specified, the compiler will create
6554 in memory the two mappings from the specified file. If there is any problem
6555 (non existent file, truncated file or duplicate entries), no mapping
6556 will be created.
6557
6558 Several @option{-gnatem} switches may be specified; however, only the last
6559 one on the command line will be taken into account.
6560
6561 When using a project file, @command{gnatmake} create a temporary mapping file
6562 and communicates it to the compiler using this switch.
6563
6564 @end table
6565
6566 @node Integrated Preprocessing
6567 @subsection Integrated Preprocessing
6568
6569 @noindent
6570 GNAT sources may be preprocessed immediately before compilation; the actual
6571 text of the source is not the text of the source file, but is derived from it
6572 through a process called preprocessing. Integrated preprocessing is specified
6573 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6574 indicates, through a text file, the preprocessing data to be used.
6575 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6576
6577 @noindent
6578 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6579 used when Integrated Preprocessing is used. The reason is that preprocessing
6580 with another Preprocessing Data file without changing the sources will
6581 not trigger recompilation without this switch.
6582
6583 @noindent
6584 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6585 always trigger recompilation for sources that are preprocessed,
6586 because @command{gnatmake} cannot compute the checksum of the source after
6587 preprocessing.
6588
6589 @noindent
6590 The actual preprocessing function is described in details in section
6591 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6592 preprocessing is triggered and parameterized.
6593
6594 @table @code
6595
6596 @item -gnatep=@var{file}
6597 @cindex @option{-gnatep} (@command{gcc})
6598 This switch indicates to the compiler the file name (without directory
6599 information) of the preprocessor data file to use. The preprocessor data file
6600 should be found in the source directories.
6601
6602 @noindent
6603 A preprocessing data file is a text file with significant lines indicating
6604 how should be preprocessed either a specific source or all sources not
6605 mentioned in other lines. A significant line is a non empty, non comment line.
6606 Comments are similar to Ada comments.
6607
6608 @noindent
6609 Each significant line starts with either a literal string or the character '*'.
6610 A literal string is the file name (without directory information) of the source
6611 to preprocess. A character '*' indicates the preprocessing for all the sources
6612 that are not specified explicitly on other lines (order of the lines is not
6613 significant). It is an error to have two lines with the same file name or two
6614 lines starting with the character '*'.
6615
6616 @noindent
6617 After the file name or the character '*', another optional literal string
6618 indicating the file name of the definition file to be used for preprocessing
6619 (@pxref{Form of Definitions File}). The definition files are found by the
6620 compiler in one of the source directories. In some cases, when compiling
6621 a source in a directory other than the current directory, if the definition
6622 file is in the current directory, it may be necessary to add the current
6623 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6624 the compiler would not find the definition file.
6625
6626 @noindent
6627 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6628 be found. Those ^switches^switches^ are:
6629
6630 @table @code
6631
6632 @item -b
6633 Causes both preprocessor lines and the lines deleted by
6634 preprocessing to be replaced by blank lines, preserving the line number.
6635 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6636 it cancels the effect of @option{-c}.
6637
6638 @item -c
6639 Causes both preprocessor lines and the lines deleted
6640 by preprocessing to be retained as comments marked
6641 with the special string ``@code{--! }''.
6642
6643 @item -Dsymbol=value
6644 Define or redefine a symbol, associated with value. A symbol is an Ada
6645 identifier, or an Ada reserved word, with the exception of @code{if},
6646 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6647 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6648 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6649 same name defined in a definition file.
6650
6651 @item -s
6652 Causes a sorted list of symbol names and values to be
6653 listed on the standard output file.
6654
6655 @item -u
6656 Causes undefined symbols to be treated as having the value @code{FALSE}
6657 in the context
6658 of a preprocessor test. In the absence of this option, an undefined symbol in
6659 a @code{#if} or @code{#elsif} test will be treated as an error.
6660
6661 @end table
6662
6663 @noindent
6664 Examples of valid lines in a preprocessor data file:
6665
6666 @smallexample
6667   "toto.adb"  "prep.def" -u
6668   --  preprocess "toto.adb", using definition file "prep.def",
6669   --  undefined symbol are False.
6670
6671   * -c -DVERSION=V101
6672   --  preprocess all other sources without a definition file;
6673   --  suppressed lined are commented; symbol VERSION has the value V101.
6674
6675   "titi.adb" "prep2.def" -s
6676   --  preprocess "titi.adb", using definition file "prep2.def";
6677   --  list all symbols with their values.
6678 @end smallexample
6679
6680 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6681 @cindex @option{-gnateD} (@command{gcc})
6682 Define or redefine a preprocessing symbol, associated with value. If no value
6683 is given on the command line, then the value of the symbol is @code{True}.
6684 A symbol is an identifier, following normal Ada (case-insensitive)
6685 rules for its syntax, and value is any sequence (including an empty sequence)
6686 of characters from the set (letters, digits, period, underline).
6687 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6688 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6689
6690 @noindent
6691 A symbol declared with this ^switch^switch^ on the command line replaces a
6692 symbol with the same name either in a definition file or specified with a
6693 ^switch^switch^ -D in the preprocessor data file.
6694
6695 @noindent
6696 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6697
6698 @end table
6699
6700 @node Code Generation Control
6701 @subsection Code Generation Control
6702
6703 @noindent
6704
6705 The GCC technology provides a wide range of target dependent
6706 @option{-m} switches for controlling
6707 details of code generation with respect to different versions of
6708 architectures. This includes variations in instruction sets (e.g.
6709 different members of the power pc family), and different requirements
6710 for optimal arrangement of instructions (e.g. different members of
6711 the x86 family). The list of available @option{-m} switches may be
6712 found in the GCC documentation.
6713
6714 Use of the these @option{-m} switches may in some cases result in improved
6715 code performance.
6716
6717 The GNAT Pro technology is tested and qualified without any
6718 @option{-m} switches,
6719 so generally the most reliable approach is to avoid the use of these
6720 switches. However, we generally expect most of these switches to work
6721 successfully with GNAT Pro, and many customers have reported successful
6722 use of these options.
6723
6724 Our general advice is to avoid the use of @option{-m} switches unless
6725 special needs lead to requirements in this area. In particular,
6726 there is no point in using @option{-m} switches to improve performance
6727 unless you actually see a performance improvement.
6728
6729 @ifset vms
6730 @node Return Codes
6731 @subsection Return Codes
6732 @cindex Return Codes
6733 @cindex @option{/RETURN_CODES=VMS}
6734
6735 @noindent
6736 On VMS, GNAT compiled programs return POSIX-style codes by default,
6737 e.g. @option{/RETURN_CODES=POSIX}.
6738
6739 To enable VMS style return codes, use GNAT BIND and LINK with the option
6740 @option{/RETURN_CODES=VMS}. For example:
6741
6742 @smallexample
6743 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6744 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6745 @end smallexample
6746
6747 @noindent
6748 Programs built with /RETURN_CODES=VMS are suitable to be called in
6749 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6750 are suitable for spawning with appropriate GNAT RTL routines.
6751
6752 @end ifset
6753
6754 @node Search Paths and the Run-Time Library (RTL)
6755 @section Search Paths and the Run-Time Library (RTL)
6756
6757 @noindent
6758 With the GNAT source-based library system, the compiler must be able to
6759 find source files for units that are needed by the unit being compiled.
6760 Search paths are used to guide this process.
6761
6762 The compiler compiles one source file whose name must be given
6763 explicitly on the command line. In other words, no searching is done
6764 for this file. To find all other source files that are needed (the most
6765 common being the specs of units), the compiler examines the following
6766 directories, in the following order:
6767
6768 @enumerate
6769 @item
6770 The directory containing the source file of the main unit being compiled
6771 (the file name on the command line).
6772
6773 @item
6774 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6775 @command{gcc} command line, in the order given.
6776
6777 @item
6778 @findex ADA_PRJ_INCLUDE_FILE
6779 Each of the directories listed in the text file whose name is given
6780 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6781
6782 @noindent
6783 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6784 driver when project files are used. It should not normally be set
6785 by other means.
6786
6787 @item
6788 @findex ADA_INCLUDE_PATH
6789 Each of the directories listed in the value of the
6790 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6791 @ifclear vms
6792 Construct this value
6793 exactly as the @code{PATH} environment variable: a list of directory
6794 names separated by colons (semicolons when working with the NT version).
6795 @end ifclear
6796 @ifset vms
6797 Normally, define this value as a logical name containing a comma separated
6798 list of directory names.
6799
6800 This variable can also be defined by means of an environment string
6801 (an argument to the DEC C exec* set of functions).
6802
6803 Logical Name:
6804 @smallexample
6805 DEFINE ANOTHER_PATH FOO:[BAG]
6806 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6807 @end smallexample
6808
6809 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6810 first, followed by the standard Ada 95
6811 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6812 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6813 (Text_IO, Sequential_IO, etc)
6814 instead of the Ada95 packages. Thus, in order to get the Ada 95
6815 packages by default, ADA_INCLUDE_PATH must be redefined.
6816 @end ifset
6817
6818 @item
6819 The content of the @file{ada_source_path} file which is part of the GNAT
6820 installation tree and is used to store standard libraries such as the
6821 GNAT Run Time Library (RTL) source files.
6822 @ifclear vms
6823 @ref{Installing a library}
6824 @end ifclear
6825 @end enumerate
6826
6827 @noindent
6828 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6829 inhibits the use of the directory
6830 containing the source file named in the command line. You can still
6831 have this directory on your search path, but in this case it must be
6832 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6833
6834 Specifying the switch @option{-nostdinc}
6835 inhibits the search of the default location for the GNAT Run Time
6836 Library (RTL) source files.
6837
6838 The compiler outputs its object files and ALI files in the current
6839 working directory.
6840 @ifclear vms
6841 Caution: The object file can be redirected with the @option{-o} switch;
6842 however, @command{gcc} and @code{gnat1} have not been coordinated on this
6843 so the @file{ALI} file will not go to the right place. Therefore, you should
6844 avoid using the @option{-o} switch.
6845 @end ifclear
6846
6847 @findex System.IO
6848 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6849 children make up the GNAT RTL, together with the simple @code{System.IO}
6850 package used in the @code{"Hello World"} example. The sources for these units
6851 are needed by the compiler and are kept together in one directory. Not
6852 all of the bodies are needed, but all of the sources are kept together
6853 anyway. In a normal installation, you need not specify these directory
6854 names when compiling or binding. Either the environment variables or
6855 the built-in defaults cause these files to be found.
6856
6857 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6858 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6859 consisting of child units of @code{GNAT}. This is a collection of generally
6860 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6861 further details.
6862
6863 Besides simplifying access to the RTL, a major use of search paths is
6864 in compiling sources from multiple directories. This can make
6865 development environments much more flexible.
6866
6867 @node Order of Compilation Issues
6868 @section Order of Compilation Issues
6869
6870 @noindent
6871 If, in our earlier example, there was a spec for the @code{hello}
6872 procedure, it would be contained in the file @file{hello.ads}; yet this
6873 file would not have to be explicitly compiled. This is the result of the
6874 model we chose to implement library management. Some of the consequences
6875 of this model are as follows:
6876
6877 @itemize @bullet
6878 @item
6879 There is no point in compiling specs (except for package
6880 specs with no bodies) because these are compiled as needed by clients. If
6881 you attempt a useless compilation, you will receive an error message.
6882 It is also useless to compile subunits because they are compiled as needed
6883 by the parent.
6884
6885 @item
6886 There are no order of compilation requirements: performing a
6887 compilation never obsoletes anything. The only way you can obsolete
6888 something and require recompilations is to modify one of the
6889 source files on which it depends.
6890
6891 @item
6892 There is no library as such, apart from the ALI files
6893 (@pxref{The Ada Library Information Files}, for information on the format
6894 of these files). For now we find it convenient to create separate ALI files,
6895 but eventually the information therein may be incorporated into the object
6896 file directly.
6897
6898 @item
6899 When you compile a unit, the source files for the specs of all units
6900 that it @code{with}'s, all its subunits, and the bodies of any generics it
6901 instantiates must be available (reachable by the search-paths mechanism
6902 described above), or you will receive a fatal error message.
6903 @end itemize
6904
6905 @node Examples
6906 @section Examples
6907
6908 @noindent
6909 The following are some typical Ada compilation command line examples:
6910
6911 @table @code
6912 @item $ gcc -c xyz.adb
6913 Compile body in file @file{xyz.adb} with all default options.
6914
6915 @ifclear vms
6916 @item $ gcc -c -O2 -gnata xyz-def.adb
6917 @end ifclear
6918 @ifset vms
6919 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6920 @end ifset
6921
6922 Compile the child unit package in file @file{xyz-def.adb} with extensive
6923 optimizations, and pragma @code{Assert}/@code{Debug} statements
6924 enabled.
6925
6926 @item $ gcc -c -gnatc abc-def.adb
6927 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6928 mode.
6929 @end table
6930
6931 @node Binding Using gnatbind
6932 @chapter Binding Using @code{gnatbind}
6933 @findex gnatbind
6934
6935 @menu
6936 * Running gnatbind::
6937 * Switches for gnatbind::
6938 * Command-Line Access::
6939 * Search Paths for gnatbind::
6940 * Examples of gnatbind Usage::
6941 @end menu
6942
6943 @noindent
6944 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6945 to bind compiled GNAT objects. The @code{gnatbind} program performs
6946 four separate functions:
6947
6948 @enumerate
6949 @item
6950 Checks that a program is consistent, in accordance with the rules in
6951 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6952 messages are generated if a program uses inconsistent versions of a
6953 given unit.
6954
6955 @item
6956 Checks that an acceptable order of elaboration exists for the program
6957 and issues an error message if it cannot find an order of elaboration
6958 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6959
6960 @item
6961 Generates a main program incorporating the given elaboration order.
6962 This program is a small Ada package (body and spec) that
6963 must be subsequently compiled
6964 using the GNAT compiler. The necessary compilation step is usually
6965 performed automatically by @command{gnatlink}. The two most important
6966 functions of this program
6967 are to call the elaboration routines of units in an appropriate order
6968 and to call the main program.
6969
6970 @item
6971 Determines the set of object files required by the given main program.
6972 This information is output in the forms of comments in the generated program,
6973 to be read by the @command{gnatlink} utility used to link the Ada application.
6974 @end enumerate
6975
6976 @node Running gnatbind
6977 @section Running @code{gnatbind}
6978
6979 @noindent
6980 The form of the @code{gnatbind} command is
6981
6982 @smallexample
6983 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6984 @end smallexample
6985
6986 @noindent
6987 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6988 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6989 package in two files whose names are
6990 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6991 For example, if given the
6992 parameter @file{hello.ali}, for a main program contained in file
6993 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6994 and @file{b~hello.adb}.
6995
6996 When doing consistency checking, the binder takes into consideration
6997 any source files it can locate. For example, if the binder determines
6998 that the given main program requires the package @code{Pack}, whose
6999 @file{.ALI}
7000 file is @file{pack.ali} and whose corresponding source spec file is
7001 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7002 (using the same search path conventions as previously described for the
7003 @command{gcc} command). If it can locate this source file, it checks that
7004 the time stamps
7005 or source checksums of the source and its references to in @file{ALI} files
7006 match. In other words, any @file{ALI} files that mentions this spec must have
7007 resulted from compiling this version of the source file (or in the case
7008 where the source checksums match, a version close enough that the
7009 difference does not matter).
7010
7011 @cindex Source files, use by binder
7012 The effect of this consistency checking, which includes source files, is
7013 that the binder ensures that the program is consistent with the latest
7014 version of the source files that can be located at bind time. Editing a
7015 source file without compiling files that depend on the source file cause
7016 error messages to be generated by the binder.
7017
7018 For example, suppose you have a main program @file{hello.adb} and a
7019 package @code{P}, from file @file{p.ads} and you perform the following
7020 steps:
7021
7022 @enumerate
7023 @item
7024 Enter @code{gcc -c hello.adb} to compile the main program.
7025
7026 @item
7027 Enter @code{gcc -c p.ads} to compile package @code{P}.
7028
7029 @item
7030 Edit file @file{p.ads}.
7031
7032 @item
7033 Enter @code{gnatbind hello}.
7034 @end enumerate
7035
7036 @noindent
7037 At this point, the file @file{p.ali} contains an out-of-date time stamp
7038 because the file @file{p.ads} has been edited. The attempt at binding
7039 fails, and the binder generates the following error messages:
7040
7041 @smallexample
7042 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7043 error: "p.ads" has been modified and must be recompiled
7044 @end smallexample
7045
7046 @noindent
7047 Now both files must be recompiled as indicated, and then the bind can
7048 succeed, generating a main program. You need not normally be concerned
7049 with the contents of this file, but for reference purposes a sample
7050 binder output file is given in @ref{Example of Binder Output File}.
7051
7052 In most normal usage, the default mode of @command{gnatbind} which is to
7053 generate the main package in Ada, as described in the previous section.
7054 In particular, this means that any Ada programmer can read and understand
7055 the generated main program. It can also be debugged just like any other
7056 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7057 @command{gnatbind} and @command{gnatlink}.
7058
7059 However for some purposes it may be convenient to generate the main
7060 program in C rather than Ada. This may for example be helpful when you
7061 are generating a mixed language program with the main program in C. The
7062 GNAT compiler itself is an example.
7063 The use of the @option{^-C^/BIND_FILE=C^} switch
7064 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7065 be generated in C (and compiled using the gnu C compiler).
7066
7067 @node Switches for gnatbind
7068 @section Switches for @command{gnatbind}
7069
7070 @noindent
7071 The following switches are available with @code{gnatbind}; details will
7072 be presented in subsequent sections.
7073
7074 @menu
7075 * Consistency-Checking Modes::
7076 * Binder Error Message Control::
7077 * Elaboration Control::
7078 * Output Control::
7079 * Binding with Non-Ada Main Programs::
7080 * Binding Programs with No Main Subprogram::
7081 @end menu
7082
7083 @table @option
7084 @c !sort!
7085 @item ^-aO^/OBJECT_SEARCH^
7086 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7087 Specify directory to be searched for ALI files.
7088
7089 @item ^-aI^/SOURCE_SEARCH^
7090 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7091 Specify directory to be searched for source file.
7092
7093 @item ^-A^/BIND_FILE=ADA^
7094 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7095 Generate binder program in Ada (default)
7096
7097 @item ^-b^/REPORT_ERRORS=BRIEF^
7098 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7099 Generate brief messages to @file{stderr} even if verbose mode set.
7100
7101 @item ^-c^/NOOUTPUT^
7102 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7103 Check only, no generation of binder output file.
7104
7105 @item ^-C^/BIND_FILE=C^
7106 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7107 Generate binder program in C
7108
7109 @item ^-e^/ELABORATION_DEPENDENCIES^
7110 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7111 Output complete list of elaboration-order dependencies.
7112
7113 @item ^-E^/STORE_TRACEBACKS^
7114 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7115 Store tracebacks in exception occurrences when the target supports it.
7116 This is the default with the zero cost exception mechanism.
7117 @ignore
7118 @c The following may get moved to an appendix
7119 This option is currently supported on the following targets:
7120 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7121 @end ignore
7122 See also the packages @code{GNAT.Traceback} and
7123 @code{GNAT.Traceback.Symbolic} for more information.
7124 @ifclear vms
7125 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7126 @command{gcc} option.
7127 @end ifclear
7128
7129 @item ^-F^/FORCE_ELABS_FLAGS^
7130 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7131 Force the checks of elaboration flags. @command{gnatbind} does not normally
7132 generate checks of elaboration flags for the main executable, except when
7133 a Stand-Alone Library is used. However, there are cases when this cannot be
7134 detected by gnatbind. An example is importing an interface of a Stand-Alone
7135 Library through a pragma Import and only specifying through a linker switch
7136 this Stand-Alone Library. This switch is used to guarantee that elaboration
7137 flag checks are generated.
7138
7139 @item ^-h^/HELP^
7140 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7141 Output usage (help) information
7142
7143 @item ^-I^/SEARCH^
7144 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7145 Specify directory to be searched for source and ALI files.
7146
7147 @item ^-I-^/NOCURRENT_DIRECTORY^
7148 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7149 Do not look for sources in the current directory where @code{gnatbind} was
7150 invoked, and do not look for ALI files in the directory containing the
7151 ALI file named in the @code{gnatbind} command line.
7152
7153 @item ^-l^/ORDER_OF_ELABORATION^
7154 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7155 Output chosen elaboration order.
7156
7157 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7158 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7159 Bind the units for library building. In this case the adainit and
7160 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7161 are renamed to ^xxxinit^XXXINIT^ and
7162 ^xxxfinal^XXXFINAL^.
7163 Implies ^-n^/NOCOMPILE^.
7164 @ifclear vms
7165 (@xref{GNAT and Libraries}, for more details.)
7166 @end ifclear
7167 @ifset vms
7168 On OpenVMS, these init and final procedures are exported in uppercase
7169 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7170 the init procedure will be "TOTOINIT" and the exported name of the final
7171 procedure will be "TOTOFINAL".
7172 @end ifset
7173
7174 @item ^-Mxyz^/RENAME_MAIN=xyz^
7175 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7176 Rename generated main program from main to xyz
7177
7178 @item ^-m^/ERROR_LIMIT=^@var{n}
7179 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7180 Limit number of detected errors to @var{n}, where @var{n} is
7181 in the range 1..999_999. The default value if no switch is
7182 given is 9999. Binding is terminated if the limit is exceeded.
7183 @ifset unw
7184 Furthermore, under Windows, the sources pointed to by the libraries path
7185 set in the registry are not searched for.
7186 @end ifset
7187
7188 @item ^-n^/NOMAIN^
7189 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7190 No main program.
7191
7192 @item -nostdinc
7193 @cindex @option{-nostdinc} (@command{gnatbind})
7194 Do not look for sources in the system default directory.
7195
7196 @item -nostdlib
7197 @cindex @option{-nostdlib} (@command{gnatbind})
7198 Do not look for library files in the system default directory.
7199
7200 @item --RTS=@var{rts-path}
7201 @cindex @option{--RTS} (@code{gnatbind})
7202 Specifies the default location of the runtime library. Same meaning as the
7203 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7204
7205 @item ^-o ^/OUTPUT=^@var{file}
7206 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7207 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7208 Note that if this option is used, then linking must be done manually,
7209 gnatlink cannot be used.
7210
7211 @item ^-O^/OBJECT_LIST^
7212 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7213 Output object list.
7214
7215 @item ^-p^/PESSIMISTIC_ELABORATION^
7216 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7217 Pessimistic (worst-case) elaboration order
7218
7219 @item ^-s^/READ_SOURCES=ALL^
7220 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7221 Require all source files to be present.
7222
7223 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7224 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7225 Specifies the value to be used when detecting uninitialized scalar
7226 objects with pragma Initialize_Scalars.
7227 The @var{xxx} ^string specified with the switch^option^ may be either
7228 @itemize @bullet
7229 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7230 @item ``@option{^lo^LOW^}'' for the lowest possible value
7231 @item ``@option{^hi^HIGH^}'' for the highest possible value
7232 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7233 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7234 @end itemize
7235
7236 In addition, you can specify @option{-Sev} to indicate that the value is
7237 to be set at run time. In this case, the program will look for an environment
7238 @cindex GNAT_INIT_SCALARS
7239 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7240 of @option{in/lo/hi/xx} with the same meanings as above.
7241 If no environment variable is found, or if it does not have a valid value,
7242 then the default is @option{in} (invalid values).
7243
7244 @ifclear vms
7245 @item -static
7246 @cindex @option{-static} (@code{gnatbind})
7247 Link against a static GNAT run time.
7248
7249 @item -shared
7250 @cindex @option{-shared} (@code{gnatbind})
7251 Link against a shared GNAT run time when available.
7252 @end ifclear
7253
7254 @item ^-t^/NOTIME_STAMP_CHECK^
7255 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7256 Tolerate time stamp and other consistency errors
7257
7258 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7259 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7260 Set the time slice value to @var{n} milliseconds. If the system supports
7261 the specification of a specific time slice value, then the indicated value
7262 is used. If the system does not support specific time slice values, but
7263 does support some general notion of round-robin scheduling, then any
7264 non-zero value will activate round-robin scheduling.
7265
7266 A value of zero is treated specially. It turns off time
7267 slicing, and in addition, indicates to the tasking run time that the
7268 semantics should match as closely as possible the Annex D
7269 requirements of the Ada RM, and in particular sets the default
7270 scheduling policy to @code{FIFO_Within_Priorities}.
7271
7272 @item ^-v^/REPORT_ERRORS=VERBOSE^
7273 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7274 Verbose mode. Write error messages, header, summary output to
7275 @file{stdout}.
7276
7277 @ifclear vms
7278 @item -w@var{x}
7279 @cindex @option{-w} (@code{gnatbind})
7280 Warning mode (@var{x}=s/e for suppress/treat as error)
7281 @end ifclear
7282
7283 @ifset vms
7284 @item /WARNINGS=NORMAL
7285 @cindex @option{/WARNINGS} (@code{gnatbind})
7286 Normal warnings mode. Warnings are issued but ignored
7287
7288 @item /WARNINGS=SUPPRESS
7289 @cindex @option{/WARNINGS} (@code{gnatbind})
7290 All warning messages are suppressed
7291
7292 @item /WARNINGS=ERROR
7293 @cindex @option{/WARNINGS} (@code{gnatbind})
7294 Warning messages are treated as fatal errors
7295 @end ifset
7296
7297 @item ^-x^/READ_SOURCES=NONE^
7298 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7299 Exclude source files (check object consistency only).
7300
7301 @ifset vms
7302 @item /READ_SOURCES=AVAILABLE
7303 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7304 Default mode, in which sources are checked for consistency only if
7305 they are available.
7306 @end ifset
7307
7308 @item ^-z^/ZERO_MAIN^
7309 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7310 No main subprogram.
7311 @end table
7312
7313 @ifclear vms
7314 @noindent
7315 You may obtain this listing of switches by running @code{gnatbind} with
7316 no arguments.
7317 @end ifclear
7318
7319 @node Consistency-Checking Modes
7320 @subsection Consistency-Checking Modes
7321
7322 @noindent
7323 As described earlier, by default @code{gnatbind} checks
7324 that object files are consistent with one another and are consistent
7325 with any source files it can locate. The following switches control binder
7326 access to sources.
7327
7328 @table @option
7329 @c !sort!
7330 @item ^-s^/READ_SOURCES=ALL^
7331 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7332 Require source files to be present. In this mode, the binder must be
7333 able to locate all source files that are referenced, in order to check
7334 their consistency. In normal mode, if a source file cannot be located it
7335 is simply ignored. If you specify this switch, a missing source
7336 file is an error.
7337
7338 @item ^-x^/READ_SOURCES=NONE^
7339 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7340 Exclude source files. In this mode, the binder only checks that ALI
7341 files are consistent with one another. Source files are not accessed.
7342 The binder runs faster in this mode, and there is still a guarantee that
7343 the resulting program is self-consistent.
7344 If a source file has been edited since it was last compiled, and you
7345 specify this switch, the binder will not detect that the object
7346 file is out of date with respect to the source file. Note that this is the
7347 mode that is automatically used by @command{gnatmake} because in this
7348 case the checking against sources has already been performed by
7349 @command{gnatmake} in the course of compilation (i.e. before binding).
7350
7351 @ifset vms
7352 @item /READ_SOURCES=AVAILABLE
7353 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7354 This is the default mode in which source files are checked if they are
7355 available, and ignored if they are not available.
7356 @end ifset
7357 @end table
7358
7359 @node Binder Error Message Control
7360 @subsection Binder Error Message Control
7361
7362 @noindent
7363 The following switches provide control over the generation of error
7364 messages from the binder:
7365
7366 @table @option
7367 @c !sort!
7368 @item ^-v^/REPORT_ERRORS=VERBOSE^
7369 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7370 Verbose mode. In the normal mode, brief error messages are generated to
7371 @file{stderr}. If this switch is present, a header is written
7372 to @file{stdout} and any error messages are directed to @file{stdout}.
7373 All that is written to @file{stderr} is a brief summary message.
7374
7375 @item ^-b^/REPORT_ERRORS=BRIEF^
7376 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7377 Generate brief error messages to @file{stderr} even if verbose mode is
7378 specified. This is relevant only when used with the
7379 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7380
7381 @ifclear vms
7382 @item -m@var{n}
7383 @cindex @option{-m} (@code{gnatbind})
7384 Limits the number of error messages to @var{n}, a decimal integer in the
7385 range 1-999. The binder terminates immediately if this limit is reached.
7386
7387 @item -M@var{xxx}
7388 @cindex @option{-M} (@code{gnatbind})
7389 Renames the generated main program from @code{main} to @code{xxx}.
7390 This is useful in the case of some cross-building environments, where
7391 the actual main program is separate from the one generated
7392 by @code{gnatbind}.
7393 @end ifclear
7394
7395 @item ^-ws^/WARNINGS=SUPPRESS^
7396 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7397 @cindex Warnings
7398 Suppress all warning messages.
7399
7400 @item ^-we^/WARNINGS=ERROR^
7401 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7402 Treat any warning messages as fatal errors.
7403
7404 @ifset vms
7405 @item /WARNINGS=NORMAL
7406 Standard mode with warnings generated, but warnings do not get treated
7407 as errors.
7408 @end ifset
7409
7410 @item ^-t^/NOTIME_STAMP_CHECK^
7411 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7412 @cindex Time stamp checks, in binder
7413 @cindex Binder consistency checks
7414 @cindex Consistency checks, in binder
7415 The binder performs a number of consistency checks including:
7416
7417 @itemize @bullet
7418 @item
7419 Check that time stamps of a given source unit are consistent
7420 @item
7421 Check that checksums of a given source unit are consistent
7422 @item
7423 Check that consistent versions of @code{GNAT} were used for compilation
7424 @item
7425 Check consistency of configuration pragmas as required
7426 @end itemize
7427
7428 @noindent
7429 Normally failure of such checks, in accordance with the consistency
7430 requirements of the Ada Reference Manual, causes error messages to be
7431 generated which abort the binder and prevent the output of a binder
7432 file and subsequent link to obtain an executable.
7433
7434 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7435 into warnings, so that
7436 binding and linking can continue to completion even in the presence of such
7437 errors. The result may be a failed link (due to missing symbols), or a
7438 non-functional executable which has undefined semantics.
7439 @emph{This means that
7440 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7441 with extreme care.}
7442 @end table
7443
7444 @node Elaboration Control
7445 @subsection Elaboration Control
7446
7447 @noindent
7448 The following switches provide additional control over the elaboration
7449 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7450
7451 @table @option
7452 @item ^-p^/PESSIMISTIC_ELABORATION^
7453 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7454 Normally the binder attempts to choose an elaboration order that is
7455 likely to minimize the likelihood of an elaboration order error resulting
7456 in raising a @code{Program_Error} exception. This switch reverses the
7457 action of the binder, and requests that it deliberately choose an order
7458 that is likely to maximize the likelihood of an elaboration error.
7459 This is useful in ensuring portability and avoiding dependence on
7460 accidental fortuitous elaboration ordering.
7461
7462 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7463 switch if dynamic
7464 elaboration checking is used (@option{-gnatE} switch used for compilation).
7465 This is because in the default static elaboration mode, all necessary
7466 @code{Elaborate_All} pragmas are implicitly inserted.
7467 These implicit pragmas are still respected by the binder in
7468 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7469 safe elaboration order is assured.
7470 @end table
7471
7472 @node Output Control
7473 @subsection Output Control
7474
7475 @noindent
7476 The following switches allow additional control over the output
7477 generated by the binder.
7478
7479 @table @option
7480 @c !sort!
7481
7482 @item ^-A^/BIND_FILE=ADA^
7483 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7484 Generate binder program in Ada (default). The binder program is named
7485 @file{b~@var{mainprog}.adb} by default. This can be changed with
7486 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7487
7488 @item ^-c^/NOOUTPUT^
7489 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7490 Check only. Do not generate the binder output file. In this mode the
7491 binder performs all error checks but does not generate an output file.
7492
7493 @item ^-C^/BIND_FILE=C^
7494 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7495 Generate binder program in C. The binder program is named
7496 @file{b_@var{mainprog}.c}.
7497 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7498 option.
7499
7500 @item ^-e^/ELABORATION_DEPENDENCIES^
7501 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7502 Output complete list of elaboration-order dependencies, showing the
7503 reason for each dependency. This output can be rather extensive but may
7504 be useful in diagnosing problems with elaboration order. The output is
7505 written to @file{stdout}.
7506
7507 @item ^-h^/HELP^
7508 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7509 Output usage information. The output is written to @file{stdout}.
7510
7511 @item ^-K^/LINKER_OPTION_LIST^
7512 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7513 Output linker options to @file{stdout}. Includes library search paths,
7514 contents of pragmas Ident and Linker_Options, and libraries added
7515 by @code{gnatbind}.
7516
7517 @item ^-l^/ORDER_OF_ELABORATION^
7518 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7519 Output chosen elaboration order. The output is written to @file{stdout}.
7520
7521 @item ^-O^/OBJECT_LIST^
7522 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7523 Output full names of all the object files that must be linked to provide
7524 the Ada component of the program. The output is written to @file{stdout}.
7525 This list includes the files explicitly supplied and referenced by the user
7526 as well as implicitly referenced run-time unit files. The latter are
7527 omitted if the corresponding units reside in shared libraries. The
7528 directory names for the run-time units depend on the system configuration.
7529
7530 @item ^-o ^/OUTPUT=^@var{file}
7531 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7532 Set name of output file to @var{file} instead of the normal
7533 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7534 binder generated body filename. In C mode you would normally give
7535 @var{file} an extension of @file{.c} because it will be a C source program.
7536 Note that if this option is used, then linking must be done manually.
7537 It is not possible to use gnatlink in this case, since it cannot locate
7538 the binder file.
7539
7540 @item ^-r^/RESTRICTION_LIST^
7541 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7542 Generate list of @code{pragma Restrictions} that could be applied to
7543 the current unit. This is useful for code audit purposes, and also may
7544 be used to improve code generation in some cases.
7545
7546 @end table
7547
7548 @node Binding with Non-Ada Main Programs
7549 @subsection Binding with Non-Ada Main Programs
7550
7551 @noindent
7552 In our description so far we have assumed that the main
7553 program is in Ada, and that the task of the binder is to generate a
7554 corresponding function @code{main} that invokes this Ada main
7555 program. GNAT also supports the building of executable programs where
7556 the main program is not in Ada, but some of the called routines are
7557 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7558 The following switch is used in this situation:
7559
7560 @table @option
7561 @item ^-n^/NOMAIN^
7562 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7563 No main program. The main program is not in Ada.
7564 @end table
7565
7566 @noindent
7567 In this case, most of the functions of the binder are still required,
7568 but instead of generating a main program, the binder generates a file
7569 containing the following callable routines:
7570
7571 @table @code
7572 @item adainit
7573 @findex adainit
7574 You must call this routine to initialize the Ada part of the program by
7575 calling the necessary elaboration routines. A call to @code{adainit} is
7576 required before the first call to an Ada subprogram.
7577
7578 Note that it is assumed that the basic execution environment must be setup
7579 to be appropriate for Ada execution at the point where the first Ada
7580 subprogram is called. In particular, if the Ada code will do any
7581 floating-point operations, then the FPU must be setup in an appropriate
7582 manner. For the case of the x86, for example, full precision mode is
7583 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7584 that the FPU is in the right state.
7585
7586 @item adafinal
7587 @findex adafinal
7588 You must call this routine to perform any library-level finalization
7589 required by the Ada subprograms. A call to @code{adafinal} is required
7590 after the last call to an Ada subprogram, and before the program
7591 terminates.
7592 @end table
7593
7594 @noindent
7595 If the @option{^-n^/NOMAIN^} switch
7596 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7597 @cindex Binder, multiple input files
7598 is given, more than one ALI file may appear on
7599 the command line for @code{gnatbind}. The normal @dfn{closure}
7600 calculation is performed for each of the specified units. Calculating
7601 the closure means finding out the set of units involved by tracing
7602 @code{with} references. The reason it is necessary to be able to
7603 specify more than one ALI file is that a given program may invoke two or
7604 more quite separate groups of Ada units.
7605
7606 The binder takes the name of its output file from the last specified ALI
7607 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7608 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7609 The output is an Ada unit in source form that can
7610 be compiled with GNAT unless the -C switch is used in which case the
7611 output is a C source file, which must be compiled using the C compiler.
7612 This compilation occurs automatically as part of the @command{gnatlink}
7613 processing.
7614
7615 Currently the GNAT run time requires a FPU using 80 bits mode
7616 precision. Under targets where this is not the default it is required to
7617 call GNAT.Float_Control.Reset before using floating point numbers (this
7618 include float computation, float input and output) in the Ada code. A
7619 side effect is that this could be the wrong mode for the foreign code
7620 where floating point computation could be broken after this call.
7621
7622 @node Binding Programs with No Main Subprogram
7623 @subsection Binding Programs with No Main Subprogram
7624
7625 @noindent
7626 It is possible to have an Ada program which does not have a main
7627 subprogram. This program will call the elaboration routines of all the
7628 packages, then the finalization routines.
7629
7630 The following switch is used to bind programs organized in this manner:
7631
7632 @table @option
7633 @item ^-z^/ZERO_MAIN^
7634 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7635 Normally the binder checks that the unit name given on the command line
7636 corresponds to a suitable main subprogram. When this switch is used,
7637 a list of ALI files can be given, and the execution of the program
7638 consists of elaboration of these units in an appropriate order.
7639 @end table
7640
7641 @node Command-Line Access
7642 @section Command-Line Access
7643
7644 @noindent
7645 The package @code{Ada.Command_Line} provides access to the command-line
7646 arguments and program name. In order for this interface to operate
7647 correctly, the two variables
7648
7649 @smallexample
7650 @group
7651 int gnat_argc;
7652 char **gnat_argv;
7653 @end group
7654 @end smallexample
7655
7656 @noindent
7657 @findex gnat_argv
7658 @findex gnat_argc
7659 are declared in one of the GNAT library routines. These variables must
7660 be set from the actual @code{argc} and @code{argv} values passed to the
7661 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7662 generates the C main program to automatically set these variables.
7663 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7664 set these variables. If they are not set, the procedures in
7665 @code{Ada.Command_Line} will not be available, and any attempt to use
7666 them will raise @code{Constraint_Error}. If command line access is
7667 required, your main program must set @code{gnat_argc} and
7668 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7669 it.
7670
7671 @node Search Paths for gnatbind
7672 @section Search Paths for @code{gnatbind}
7673
7674 @noindent
7675 The binder takes the name of an ALI file as its argument and needs to
7676 locate source files as well as other ALI files to verify object consistency.
7677
7678 For source files, it follows exactly the same search rules as @command{gcc}
7679 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7680 directories searched are:
7681
7682 @enumerate
7683 @item
7684 The directory containing the ALI file named in the command line, unless
7685 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7686
7687 @item
7688 All directories specified by @option{^-I^/SEARCH^}
7689 switches on the @code{gnatbind}
7690 command line, in the order given.
7691
7692 @item
7693 @findex ADA_PRJ_OBJECTS_FILE
7694 Each of the directories listed in the text file whose name is given
7695 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7696
7697 @noindent
7698 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7699 driver when project files are used. It should not normally be set
7700 by other means.
7701
7702 @item
7703 @findex ADA_OBJECTS_PATH
7704 Each of the directories listed in the value of the
7705 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7706 @ifset unw
7707 Construct this value
7708 exactly as the @code{PATH} environment variable: a list of directory
7709 names separated by colons (semicolons when working with the NT version
7710 of GNAT).
7711 @end ifset
7712 @ifset vms
7713 Normally, define this value as a logical name containing a comma separated
7714 list of directory names.
7715
7716 This variable can also be defined by means of an environment string
7717 (an argument to the DEC C exec* set of functions).
7718
7719 Logical Name:
7720 @smallexample
7721 DEFINE ANOTHER_PATH FOO:[BAG]
7722 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7723 @end smallexample
7724
7725 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7726 first, followed by the standard Ada 95
7727 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7728 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7729 (Text_IO, Sequential_IO, etc)
7730 instead of the Ada95 packages. Thus, in order to get the Ada 95
7731 packages by default, ADA_OBJECTS_PATH must be redefined.
7732 @end ifset
7733
7734 @item
7735 The content of the @file{ada_object_path} file which is part of the GNAT
7736 installation tree and is used to store standard libraries such as the
7737 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7738 specified.
7739 @ifclear vms
7740 @ref{Installing a library}
7741 @end ifclear
7742 @end enumerate
7743
7744 @noindent
7745 In the binder the switch @option{^-I^/SEARCH^}
7746 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7747 is used to specify both source and
7748 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7749 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7750 instead if you want to specify
7751 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7752 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7753 if you want to specify library paths
7754 only. This means that for the binder
7755 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7756 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7757 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7758 The binder generates the bind file (a C language source file) in the
7759 current working directory.
7760
7761 @findex Ada
7762 @findex System
7763 @findex Interfaces
7764 @findex GNAT
7765 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7766 children make up the GNAT Run-Time Library, together with the package
7767 GNAT and its children, which contain a set of useful additional
7768 library functions provided by GNAT. The sources for these units are
7769 needed by the compiler and are kept together in one directory. The ALI
7770 files and object files generated by compiling the RTL are needed by the
7771 binder and the linker and are kept together in one directory, typically
7772 different from the directory containing the sources. In a normal
7773 installation, you need not specify these directory names when compiling
7774 or binding. Either the environment variables or the built-in defaults
7775 cause these files to be found.
7776
7777 Besides simplifying access to the RTL, a major use of search paths is
7778 in compiling sources from multiple directories. This can make
7779 development environments much more flexible.
7780
7781 @node Examples of gnatbind Usage
7782 @section Examples of @code{gnatbind} Usage
7783
7784 @noindent
7785 This section contains a number of examples of using the GNAT binding
7786 utility @code{gnatbind}.
7787
7788 @table @code
7789 @item gnatbind hello
7790 The main program @code{Hello} (source program in @file{hello.adb}) is
7791 bound using the standard switch settings. The generated main program is
7792 @file{b~hello.adb}. This is the normal, default use of the binder.
7793
7794 @ifclear vms
7795 @item gnatbind hello -o mainprog.adb
7796 @end ifclear
7797 @ifset vms
7798 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7799 @end ifset
7800 The main program @code{Hello} (source program in @file{hello.adb}) is
7801 bound using the standard switch settings. The generated main program is
7802 @file{mainprog.adb} with the associated spec in
7803 @file{mainprog.ads}. Note that you must specify the body here not the
7804 spec, in the case where the output is in Ada. Note that if this option
7805 is used, then linking must be done manually, since gnatlink will not
7806 be able to find the generated file.
7807
7808 @ifclear vms
7809 @item gnatbind main -C -o mainprog.c -x
7810 @end ifclear
7811 @ifset vms
7812 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7813 @end ifset
7814 The main program @code{Main} (source program in
7815 @file{main.adb}) is bound, excluding source files from the
7816 consistency checking, generating
7817 the file @file{mainprog.c}.
7818
7819 @ifclear vms
7820 @item gnatbind -x main_program -C -o mainprog.c
7821 This command is exactly the same as the previous example. Switches may
7822 appear anywhere in the command line, and single letter switches may be
7823 combined into a single switch.
7824 @end ifclear
7825
7826 @ifclear vms
7827 @item gnatbind -n math dbase -C -o ada-control.c
7828 @end ifclear
7829 @ifset vms
7830 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7831 @end ifset
7832 The main program is in a language other than Ada, but calls to
7833 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7834 to @code{gnatbind} generates the file @file{ada-control.c} containing
7835 the @code{adainit} and @code{adafinal} routines to be called before and
7836 after accessing the Ada units.
7837 @end table
7838
7839 @c ------------------------------------
7840 @node Linking Using gnatlink
7841 @chapter Linking Using @command{gnatlink}
7842 @c ------------------------------------
7843 @findex gnatlink
7844
7845 @noindent
7846 This chapter discusses @command{gnatlink}, a tool that links
7847 an Ada program and builds an executable file. This utility
7848 invokes the system linker ^(via the @command{gcc} command)^^
7849 with a correct list of object files and library references.
7850 @command{gnatlink} automatically determines the list of files and
7851 references for the Ada part of a program. It uses the binder file
7852 generated by the @command{gnatbind} to determine this list.
7853
7854 @menu
7855 * Running gnatlink::
7856 * Switches for gnatlink::
7857 * Setting Stack Size from gnatlink::
7858 * Setting Heap Size from gnatlink::
7859 @end menu
7860
7861 @node Running gnatlink
7862 @section Running @command{gnatlink}
7863
7864 @noindent
7865 The form of the @command{gnatlink} command is
7866
7867 @smallexample
7868 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7869            [@var{non-Ada objects}] [@var{linker options}]
7870 @end smallexample
7871
7872 @noindent
7873 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
7874 non-Ada objects
7875 or linker options) may be in any order, provided that no non-Ada object may
7876 be mistaken for a main @file{ALI} file.
7877 Any file name @file{F} without the @file{.ali}
7878 extension will be taken as the main @file{ALI} file if a file exists
7879 whose name is the concatenation of @file{F} and @file{.ali}.
7880
7881 @noindent
7882 @file{@var{mainprog}.ali} references the ALI file of the main program.
7883 The @file{.ali} extension of this file can be omitted. From this
7884 reference, @command{gnatlink} locates the corresponding binder file
7885 @file{b~@var{mainprog}.adb} and, using the information in this file along
7886 with the list of non-Ada objects and linker options, constructs a
7887 linker command file to create the executable.
7888
7889 The arguments other than the @command{gnatlink} switches and the main
7890 @file{ALI} file are passed to the linker uninterpreted.
7891 They typically include the names of
7892 object files for units written in other languages than Ada and any library
7893 references required to resolve references in any of these foreign language
7894 units, or in @code{Import} pragmas in any Ada units.
7895
7896 @var{linker options} is an optional list of linker specific
7897 switches.
7898 The default linker called by gnatlink is @var{gcc} which in
7899 turn calls the appropriate system linker.
7900 Standard options for the linker such as @option{-lmy_lib} or
7901 @option{-Ldir} can be added as is.
7902 For options that are not recognized by
7903 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7904 @option{-Wl,}.
7905 Refer to the GCC documentation for
7906 details. Here is an example showing how to generate a linker map:
7907
7908 @ifclear vms
7909 @smallexample
7910 $ gnatlink my_prog -Wl,-Map,MAPFILE
7911 @end smallexample
7912 @end ifclear
7913
7914 @ifset vms
7915 <<Need example for VMS>>
7916 @end ifset
7917
7918 Using @var{linker options} it is possible to set the program stack and
7919 heap size. See @ref{Setting Stack Size from gnatlink} and
7920 @ref{Setting Heap Size from gnatlink}.
7921
7922 @command{gnatlink} determines the list of objects required by the Ada
7923 program and prepends them to the list of objects passed to the linker.
7924 @command{gnatlink} also gathers any arguments set by the use of
7925 @code{pragma Linker_Options} and adds them to the list of arguments
7926 presented to the linker.
7927
7928 @ifset vms
7929 @command{gnatlink} accepts the following types of extra files on the command
7930 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7931 options files (.OPT). These are recognized and handled according to their
7932 extension.
7933 @end ifset
7934
7935 @node Switches for gnatlink
7936 @section Switches for @command{gnatlink}
7937
7938 @noindent
7939 The following switches are available with the @command{gnatlink} utility:
7940
7941 @table @option
7942 @c !sort!
7943
7944 @item ^-A^/BIND_FILE=ADA^
7945 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
7946 The binder has generated code in Ada. This is the default.
7947
7948 @item ^-C^/BIND_FILE=C^
7949 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
7950 If instead of generating a file in Ada, the binder has generated one in
7951 C, then the linker needs to know about it. Use this switch to signal
7952 to @command{gnatlink} that the binder has generated C code rather than
7953 Ada code.
7954
7955 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7956 @cindex Command line length
7957 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
7958 On some targets, the command line length is limited, and @command{gnatlink}
7959 will generate a separate file for the linker if the list of object files
7960 is too long.
7961 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7962 to be generated even if
7963 the limit is not exceeded. This is useful in some cases to deal with
7964 special situations where the command line length is exceeded.
7965
7966 @item ^-g^/DEBUG^
7967 @cindex Debugging information, including
7968 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
7969 The option to include debugging information causes the Ada bind file (in
7970 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7971 @option{^-g^/DEBUG^}.
7972 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7973 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7974 Without @option{^-g^/DEBUG^}, the binder removes these files by
7975 default. The same procedure apply if a C bind file was generated using
7976 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7977 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7978
7979 @item ^-n^/NOCOMPILE^
7980 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
7981 Do not compile the file generated by the binder. This may be used when
7982 a link is rerun with different options, but there is no need to recompile
7983 the binder file.
7984
7985 @item ^-v^/VERBOSE^
7986 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
7987 Causes additional information to be output, including a full list of the
7988 included object files. This switch option is most useful when you want
7989 to see what set of object files are being used in the link step.
7990
7991 @item ^-v -v^/VERBOSE/VERBOSE^
7992 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
7993 Very verbose mode. Requests that the compiler operate in verbose mode when
7994 it compiles the binder file, and that the system linker run in verbose mode.
7995
7996 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7997 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
7998 @var{exec-name} specifies an alternate name for the generated
7999 executable program. If this switch is omitted, the executable has the same
8000 name as the main unit. For example, @code{gnatlink try.ali} creates
8001 an executable called @file{^try^TRY.EXE^}.
8002
8003 @ifclear vms
8004 @item -b @var{target}
8005 @cindex @option{-b} (@command{gnatlink})
8006 Compile your program to run on @var{target}, which is the name of a
8007 system configuration. You must have a GNAT cross-compiler built if
8008 @var{target} is not the same as your host system.
8009
8010 @item -B@var{dir}
8011 @cindex @option{-B} (@command{gnatlink})
8012 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8013 from @var{dir} instead of the default location. Only use this switch
8014 when multiple versions of the GNAT compiler are available. See the
8015 @command{gcc} manual page for further details. You would normally use the
8016 @option{-b} or @option{-V} switch instead.
8017
8018 @item --GCC=@var{compiler_name}
8019 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8020 Program used for compiling the binder file. The default is
8021 @command{gcc}. You need to use quotes around @var{compiler_name} if
8022 @code{compiler_name} contains spaces or other separator characters. As
8023 an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to use
8024 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8025 inserted after your command name. Thus in the above example the compiler
8026 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8027 If several @option{--GCC=compiler_name} are used, only the last
8028 @var{compiler_name} is taken into account. However, all the additional
8029 switches are also taken into account. Thus,
8030 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8031 @option{--GCC="bar -x -y -z -t"}.
8032
8033 @item --LINK=@var{name}
8034 @cindex @option{--LINK=} (@command{gnatlink})
8035 @var{name} is the name of the linker to be invoked. This is especially
8036 useful in mixed language programs since languages such as C++ require
8037 their own linker to be used. When this switch is omitted, the default
8038 name for the linker is @command{gcc}. When this switch is used, the
8039 specified linker is called instead of @command{gcc} with exactly the same
8040 parameters that would have been passed to @command{gcc} so if the desired
8041 linker requires different parameters it is necessary to use a wrapper
8042 script that massages the parameters before invoking the real linker. It
8043 may be useful to control the exact invocation by using the verbose
8044 switch.
8045
8046 @end ifclear
8047
8048 @ifset vms
8049 @item /DEBUG=TRACEBACK
8050 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8051 This qualifier causes sufficient information to be included in the
8052 executable file to allow a traceback, but does not include the full
8053 symbol information needed by the debugger.
8054
8055 @item /IDENTIFICATION="<string>"
8056 @code{"<string>"} specifies the string to be stored in the image file
8057 identification field in the image header.
8058 It overrides any pragma @code{Ident} specified string.
8059
8060 @item /NOINHIBIT-EXEC
8061 Generate the executable file even if there are linker warnings.
8062
8063 @item /NOSTART_FILES
8064 Don't link in the object file containing the ``main'' transfer address.
8065 Used when linking with a foreign language main program compiled with a
8066 Digital compiler.
8067
8068 @item /STATIC
8069 Prefer linking with object libraries over sharable images, even without
8070 /DEBUG.
8071 @end ifset
8072
8073 @end table
8074
8075 @node Setting Stack Size from gnatlink
8076 @section Setting Stack Size from @command{gnatlink}
8077
8078 @noindent
8079 Under Windows systems, it is possible to specify the program stack size from
8080 @command{gnatlink} using either:
8081
8082 @itemize @bullet
8083
8084 @item using @option{-Xlinker} linker option
8085
8086 @smallexample
8087 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
8088 @end smallexample
8089
8090 This sets the stack reserve size to 0x10000 bytes and the stack commit
8091 size to 0x1000 bytes.
8092
8093 @item using @option{-Wl} linker option
8094
8095 @smallexample
8096 $ gnatlink hello -Wl,--stack=0x1000000
8097 @end smallexample
8098
8099 This sets the stack reserve size to 0x1000000 bytes. Note that with
8100 @option{-Wl} option it is not possible to set the stack commit size
8101 because the coma is a separator for this option.
8102
8103 @end itemize
8104
8105 @node Setting Heap Size from gnatlink
8106 @section Setting Heap Size from @command{gnatlink}
8107
8108 @noindent
8109 Under Windows systems, it is possible to specify the program heap size from
8110 @command{gnatlink} using either:
8111
8112 @itemize @bullet
8113
8114 @item using @option{-Xlinker} linker option
8115
8116 @smallexample
8117 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
8118 @end smallexample
8119
8120 This sets the heap reserve size to 0x10000 bytes and the heap commit
8121 size to 0x1000 bytes.
8122
8123 @item using @option{-Wl} linker option
8124
8125 @smallexample
8126 $ gnatlink hello -Wl,--heap=0x1000000
8127 @end smallexample
8128
8129 This sets the heap reserve size to 0x1000000 bytes. Note that with
8130 @option{-Wl} option it is not possible to set the heap commit size
8131 because the coma is a separator for this option.
8132
8133 @end itemize
8134
8135 @node The GNAT Make Program gnatmake
8136 @chapter The GNAT Make Program @command{gnatmake}
8137 @findex gnatmake
8138
8139 @menu
8140 * Running gnatmake::
8141 * Switches for gnatmake::
8142 * Mode Switches for gnatmake::
8143 * Notes on the Command Line::
8144 * How gnatmake Works::
8145 * Examples of gnatmake Usage::
8146 @end menu
8147 @noindent
8148 A typical development cycle when working on an Ada program consists of
8149 the following steps:
8150
8151 @enumerate
8152 @item
8153 Edit some sources to fix bugs.
8154
8155 @item
8156 Add enhancements.
8157
8158 @item
8159 Compile all sources affected.
8160
8161 @item
8162 Rebind and relink.
8163
8164 @item
8165 Test.
8166 @end enumerate
8167
8168 @noindent
8169 The third step can be tricky, because not only do the modified files
8170 @cindex Dependency rules
8171 have to be compiled, but any files depending on these files must also be
8172 recompiled. The dependency rules in Ada can be quite complex, especially
8173 in the presence of overloading, @code{use} clauses, generics and inlined
8174 subprograms.
8175
8176 @command{gnatmake} automatically takes care of the third and fourth steps
8177 of this process. It determines which sources need to be compiled,
8178 compiles them, and binds and links the resulting object files.
8179
8180 Unlike some other Ada make programs, the dependencies are always
8181 accurately recomputed from the new sources. The source based approach of
8182 the GNAT compilation model makes this possible. This means that if
8183 changes to the source program cause corresponding changes in
8184 dependencies, they will always be tracked exactly correctly by
8185 @command{gnatmake}.
8186
8187 @node Running gnatmake
8188 @section Running @command{gnatmake}
8189
8190 @noindent
8191 The usual form of the @command{gnatmake} command is
8192
8193 @smallexample
8194 $ gnatmake [@var{switches}] @var{file_name}
8195       [@var{file_names}] [@var{mode_switches}]
8196 @end smallexample
8197
8198 @noindent
8199 The only required argument is one @var{file_name}, which specifies
8200 a compilation unit that is a main program. Several @var{file_names} can be
8201 specified: this will result in several executables being built.
8202 If @code{switches} are present, they can be placed before the first
8203 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8204 If @var{mode_switches} are present, they must always be placed after
8205 the last @var{file_name} and all @code{switches}.
8206
8207 If you are using standard file extensions (.adb and .ads), then the
8208 extension may be omitted from the @var{file_name} arguments. However, if
8209 you are using non-standard extensions, then it is required that the
8210 extension be given. A relative or absolute directory path can be
8211 specified in a @var{file_name}, in which case, the input source file will
8212 be searched for in the specified directory only. Otherwise, the input
8213 source file will first be searched in the directory where
8214 @command{gnatmake} was invoked and if it is not found, it will be search on
8215 the source path of the compiler as described in
8216 @ref{Search Paths and the Run-Time Library (RTL)}.
8217
8218 All @command{gnatmake} output (except when you specify
8219 @option{^-M^/DEPENDENCIES_LIST^}) is to
8220 @file{stderr}. The output produced by the
8221 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8222 @file{stdout}.
8223
8224 @node Switches for gnatmake
8225 @section Switches for @command{gnatmake}
8226
8227 @noindent
8228 You may specify any of the following switches to @command{gnatmake}:
8229
8230 @table @option
8231 @c !sort!
8232 @ifclear vms
8233 @item --GCC=@var{compiler_name}
8234 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8235 Program used for compiling. The default is `@command{gcc}'. You need to use
8236 quotes around @var{compiler_name} if @code{compiler_name} contains
8237 spaces or other separator characters. As an example @option{--GCC="foo -x
8238 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8239 compiler. Note that switch @option{-c} is always inserted after your
8240 command name. Thus in the above example the compiler command that will
8241 be used by @command{gnatmake} will be @code{foo -c -x -y}.
8242 If several @option{--GCC=compiler_name} are used, only the last
8243 @var{compiler_name} is taken into account. However, all the additional
8244 switches are also taken into account. Thus,
8245 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8246 @option{--GCC="bar -x -y -z -t"}.
8247
8248 @item --GNATBIND=@var{binder_name}
8249 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8250 Program used for binding. The default is `@code{gnatbind}'. You need to
8251 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8252 or other separator characters. As an example @option{--GNATBIND="bar -x
8253 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8254 binder. Binder switches that are normally appended by @command{gnatmake} to
8255 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8256
8257 @item --GNATLINK=@var{linker_name}
8258 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8259 Program used for linking. The default is `@command{gnatlink}'. You need to
8260 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8261 or other separator characters. As an example @option{--GNATLINK="lan -x
8262 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8263 linker. Linker switches that are normally appended by @command{gnatmake} to
8264 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8265
8266 @end ifclear
8267
8268 @item ^-a^/ALL_FILES^
8269 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8270 Consider all files in the make process, even the GNAT internal system
8271 files (for example, the predefined Ada library files), as well as any
8272 locked files. Locked files are files whose ALI file is write-protected.
8273 By default,
8274 @command{gnatmake} does not check these files,
8275 because the assumption is that the GNAT internal files are properly up
8276 to date, and also that any write protected ALI files have been properly
8277 installed. Note that if there is an installation problem, such that one
8278 of these files is not up to date, it will be properly caught by the
8279 binder.
8280 You may have to specify this switch if you are working on GNAT
8281 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8282 in conjunction with @option{^-f^/FORCE_COMPILE^}
8283 if you need to recompile an entire application,
8284 including run-time files, using special configuration pragmas,
8285 such as a @code{Normalize_Scalars} pragma.
8286
8287 By default
8288 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8289 internal files with
8290 @ifclear vms
8291 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8292 @end ifclear
8293 @ifset vms
8294 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8295 @end ifset
8296
8297 @item ^-b^/ACTIONS=BIND^
8298 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8299 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8300 compilation and binding, but no link.
8301 Can be combined with @option{^-l^/ACTIONS=LINK^}
8302 to do binding and linking. When not combined with
8303 @option{^-c^/ACTIONS=COMPILE^}
8304 all the units in the closure of the main program must have been previously
8305 compiled and must be up to date. The root unit specified by @var{file_name}
8306 may be given without extension, with the source extension or, if no GNAT
8307 Project File is specified, with the ALI file extension.
8308
8309 @item ^-c^/ACTIONS=COMPILE^
8310 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8311 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8312 is also specified. Do not perform linking, except if both
8313 @option{^-b^/ACTIONS=BIND^} and
8314  @option{^-l^/ACTIONS=LINK^} are also specified.
8315 If the root unit specified by @var{file_name} is not a main unit, this is the
8316 default. Otherwise @command{gnatmake} will attempt binding and linking
8317 unless all objects are up to date and the executable is more recent than
8318 the objects.
8319
8320 @item ^-C^/MAPPING^
8321 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8322 Use a temporary mapping file. A mapping file is a way to communicate to the
8323 compiler two mappings: from unit names to file names (without any directory
8324 information) and from file names to path names (with full directory
8325 information). These mappings are used by the compiler to short-circuit the path
8326 search. When @command{gnatmake} is invoked with this switch, it will create
8327 a temporary mapping file, initially populated by the project manager,
8328 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8329 Each invocation of the compiler will add the newly accessed sources to the
8330 mapping file. This will improve the source search during the next invocation
8331 of the compiler.
8332
8333 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8334 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8335 Use a specific mapping file. The file, specified as a path name (absolute or
8336 relative) by this switch, should already exist, otherwise the switch is
8337 ineffective. The specified mapping file will be communicated to the compiler.
8338 This switch is not compatible with a project file
8339 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8340 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8341
8342 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8343 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8344 Put all object files and ALI file in directory @var{dir}.
8345 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8346 and ALI files go in the current working directory.
8347
8348 This switch cannot be used when using a project file.
8349
8350 @ifclear vms
8351 @item -eL
8352 @cindex @option{-eL} (@command{gnatmake})
8353 Follow all symbolic links when processing project files.
8354 @end ifclear
8355
8356 @item ^-f^/FORCE_COMPILE^
8357 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8358 Force recompilations. Recompile all sources, even though some object
8359 files may be up to date, but don't recompile predefined or GNAT internal
8360 files or locked files (files with a write-protected ALI file),
8361 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8362
8363 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8364 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8365 When using project files, if some errors or warnings are detected during
8366 parsing and verbose mode is not in effect (no use of switch
8367 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8368 file, rather than its simple file name.
8369
8370 @item ^-i^/IN_PLACE^
8371 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8372 In normal mode, @command{gnatmake} compiles all object files and ALI files
8373 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8374 then instead object files and ALI files that already exist are overwritten
8375 in place. This means that once a large project is organized into separate
8376 directories in the desired manner, then @command{gnatmake} will automatically
8377 maintain and update this organization. If no ALI files are found on the
8378 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8379 the new object and ALI files are created in the
8380 directory containing the source being compiled. If another organization
8381 is desired, where objects and sources are kept in different directories,
8382 a useful technique is to create dummy ALI files in the desired directories.
8383 When detecting such a dummy file, @command{gnatmake} will be forced to
8384 recompile the corresponding source file, and it will be put the resulting
8385 object and ALI files in the directory where it found the dummy file.
8386
8387 @item ^-j^/PROCESSES=^@var{n}
8388 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8389 @cindex Parallel make
8390 Use @var{n} processes to carry out the (re)compilations. On a
8391 multiprocessor machine compilations will occur in parallel. In the
8392 event of compilation errors, messages from various compilations might
8393 get interspersed (but @command{gnatmake} will give you the full ordered
8394 list of failing compiles at the end). If this is problematic, rerun
8395 the make process with n set to 1 to get a clean list of messages.
8396
8397 @item ^-k^/CONTINUE_ON_ERROR^
8398 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8399 Keep going. Continue as much as possible after a compilation error. To
8400 ease the programmer's task in case of compilation errors, the list of
8401 sources for which the compile fails is given when @command{gnatmake}
8402 terminates.
8403
8404 If @command{gnatmake} is invoked with several @file{file_names} and with this
8405 switch, if there are compilation errors when building an executable,
8406 @command{gnatmake} will not attempt to build the following executables.
8407
8408 @item ^-l^/ACTIONS=LINK^
8409 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8410 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8411 and linking. Linking will not be performed if combined with
8412 @option{^-c^/ACTIONS=COMPILE^}
8413 but not with @option{^-b^/ACTIONS=BIND^}.
8414 When not combined with @option{^-b^/ACTIONS=BIND^}
8415 all the units in the closure of the main program must have been previously
8416 compiled and must be up to date, and the main program needs to have been bound.
8417 The root unit specified by @var{file_name}
8418 may be given without extension, with the source extension or, if no GNAT
8419 Project File is specified, with the ALI file extension.
8420
8421 @item ^-m^/MINIMAL_RECOMPILATION^
8422 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8423 Specify that the minimum necessary amount of recompilations
8424 be performed. In this mode @command{gnatmake} ignores time
8425 stamp differences when the only
8426 modifications to a source file consist in adding/removing comments,
8427 empty lines, spaces or tabs. This means that if you have changed the
8428 comments in a source file or have simply reformatted it, using this
8429 switch will tell gnatmake not to recompile files that depend on it
8430 (provided other sources on which these files depend have undergone no
8431 semantic modifications). Note that the debugging information may be
8432 out of date with respect to the sources if the @option{-m} switch causes
8433 a compilation to be switched, so the use of this switch represents a
8434 trade-off between compilation time and accurate debugging information.
8435
8436 @item ^-M^/DEPENDENCIES_LIST^
8437 @cindex Dependencies, producing list
8438 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8439 Check if all objects are up to date. If they are, output the object
8440 dependences to @file{stdout} in a form that can be directly exploited in
8441 a @file{Makefile}. By default, each source file is prefixed with its
8442 (relative or absolute) directory name. This name is whatever you
8443 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8444 and @option{^-I^/SEARCH^} switches. If you use
8445 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8446 @option{^-q^/QUIET^}
8447 (see below), only the source file names,
8448 without relative paths, are output. If you just specify the
8449 @option{^-M^/DEPENDENCIES_LIST^}
8450 switch, dependencies of the GNAT internal system files are omitted. This
8451 is typically what you want. If you also specify
8452 the @option{^-a^/ALL_FILES^} switch,
8453 dependencies of the GNAT internal files are also listed. Note that
8454 dependencies of the objects in external Ada libraries (see switch
8455 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8456 are never reported.
8457
8458 @item ^-n^/DO_OBJECT_CHECK^
8459 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8460 Don't compile, bind, or link. Checks if all objects are up to date.
8461 If they are not, the full name of the first file that needs to be
8462 recompiled is printed.
8463 Repeated use of this option, followed by compiling the indicated source
8464 file, will eventually result in recompiling all required units.
8465
8466 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8467 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8468 Output executable name. The name of the final executable program will be
8469 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8470 name for the executable will be the name of the input file in appropriate form
8471 for an executable file on the host system.
8472
8473 This switch cannot be used when invoking @command{gnatmake} with several
8474 @file{file_names}.
8475
8476 @item ^-P^/PROJECT_FILE=^@var{project}
8477 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8478 Use project file @var{project}. Only one such switch can be used.
8479 @xref{gnatmake and Project Files}.
8480
8481 @item ^-q^/QUIET^
8482 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8483 Quiet. When this flag is not set, the commands carried out by
8484 @command{gnatmake} are displayed.
8485
8486 @item ^-s^/SWITCH_CHECK/^
8487 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8488 Recompile if compiler switches have changed since last compilation.
8489 All compiler switches but -I and -o are taken into account in the
8490 following way:
8491 orders between different ``first letter'' switches are ignored, but
8492 orders between same switches are taken into account. For example,
8493 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8494 is equivalent to @option{-O -g}.
8495
8496 This switch is recommended when Integrated Preprocessing is used.
8497
8498 @item ^-u^/UNIQUE^
8499 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8500 Unique. Recompile at most the main files. It implies -c. Combined with
8501 -f, it is equivalent to calling the compiler directly. Note that using
8502 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8503 (@pxref{Project Files and Main Subprograms}).
8504
8505 @item ^-U^/ALL_PROJECTS^
8506 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8507 When used without a project file or with one or several mains on the command
8508 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8509 on the command line, all sources of all project files are checked and compiled
8510 if not up to date, and libraries are rebuilt, if necessary.
8511
8512 @item ^-v^/REASONS^
8513 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8514 Verbose. Display the reason for all recompilations @command{gnatmake}
8515 decides are necessary.
8516
8517 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8518 Indicate the verbosity of the parsing of GNAT project files.
8519 @xref{Switches Related to Project Files}.
8520
8521 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8522 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8523 Indicate that sources that are not part of any Project File may be compiled.
8524 Normally, when using Project Files, only sources that are part of a Project
8525 File may be compile. When this switch is used, a source outside of all Project
8526 Files may be compiled. The ALI file and the object file will be put in the
8527 object directory of the main Project. The compilation switches used will only
8528 be those specified on the command line.
8529
8530 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8531 Indicate that external variable @var{name} has the value @var{value}.
8532 The Project Manager will use this value for occurrences of
8533 @code{external(name)} when parsing the project file.
8534 @xref{Switches Related to Project Files}.
8535
8536 @item ^-z^/NOMAIN^
8537 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8538 No main subprogram. Bind and link the program even if the unit name
8539 given on the command line is a package name. The resulting executable
8540 will execute the elaboration routines of the package and its closure,
8541 then the finalization routines.
8542
8543 @item ^-g^/DEBUG^
8544 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8545 Enable debugging. This switch is simply passed to the compiler and to the
8546 linker.
8547
8548 @end table
8549
8550 @table @asis
8551 @item @command{gcc} @asis{switches}
8552 @ifclear vms
8553 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8554 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8555 @end ifclear
8556 @ifset vms
8557 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8558 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8559 automatically treated as a compiler switch, and passed on to all
8560 compilations that are carried out.
8561 @end ifset
8562 @end table
8563
8564 @noindent
8565 Source and library search path switches:
8566
8567 @table @option
8568 @c !sort!
8569 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8570 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8571 When looking for source files also look in directory @var{dir}.
8572 The order in which source files search is undertaken is
8573 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8574
8575 @item ^-aL^/SKIP_MISSING=^@var{dir}
8576 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8577 Consider @var{dir} as being an externally provided Ada library.
8578 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8579 files have been located in directory @var{dir}. This allows you to have
8580 missing bodies for the units in @var{dir} and to ignore out of date bodies
8581 for the same units. You still need to specify
8582 the location of the specs for these units by using the switches
8583 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8584 or @option{^-I^/SEARCH=^@var{dir}}.
8585 Note: this switch is provided for compatibility with previous versions
8586 of @command{gnatmake}. The easier method of causing standard libraries
8587 to be excluded from consideration is to write-protect the corresponding
8588 ALI files.
8589
8590 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8591 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8592 When searching for library and object files, look in directory
8593 @var{dir}. The order in which library files are searched is described in
8594 @ref{Search Paths for gnatbind}.
8595
8596 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8597 @cindex Search paths, for @command{gnatmake}
8598 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8599 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8600 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8601
8602 @item ^-I^/SEARCH=^@var{dir}
8603 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8604 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8605 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8606
8607 @item ^-I-^/NOCURRENT_DIRECTORY^
8608 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8609 @cindex Source files, suppressing search
8610 Do not look for source files in the directory containing the source
8611 file named in the command line.
8612 Do not look for ALI or object files in the directory
8613 where @command{gnatmake} was invoked.
8614
8615 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8616 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8617 @cindex Linker libraries
8618 Add directory @var{dir} to the list of directories in which the linker
8619 will search for libraries. This is equivalent to
8620 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8621 @ifclear vms
8622 Furthermore, under Windows, the sources pointed to by the libraries path
8623 set in the registry are not searched for.
8624 @end ifclear
8625
8626 @item -nostdinc
8627 @cindex @option{-nostdinc} (@command{gnatmake})
8628 Do not look for source files in the system default directory.
8629
8630 @item -nostdlib
8631 @cindex @option{-nostdlib} (@command{gnatmake})
8632 Do not look for library files in the system default directory.
8633
8634 @item --RTS=@var{rts-path}
8635 @cindex @option{--RTS} (@command{gnatmake})
8636 Specifies the default location of the runtime library. GNAT looks for the
8637 runtime
8638 in the following directories, and stops as soon as a valid runtime is found
8639 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8640 @file{ada_object_path} present):
8641
8642 @itemize @bullet
8643 @item <current directory>/$rts_path
8644
8645 @item <default-search-dir>/$rts_path
8646
8647 @item <default-search-dir>/rts-$rts_path
8648 @end itemize
8649
8650 @noindent
8651 The selected path is handled like a normal RTS path.
8652
8653 @end table
8654
8655 @node Mode Switches for gnatmake
8656 @section Mode Switches for @command{gnatmake}
8657
8658 @noindent
8659 The mode switches (referred to as @code{mode_switches}) allow the
8660 inclusion of switches that are to be passed to the compiler itself, the
8661 binder or the linker. The effect of a mode switch is to cause all
8662 subsequent switches up to the end of the switch list, or up to the next
8663 mode switch, to be interpreted as switches to be passed on to the
8664 designated component of GNAT.
8665
8666 @table @option
8667 @c !sort!
8668 @item -cargs @var{switches}
8669 @cindex @option{-cargs} (@command{gnatmake})
8670 Compiler switches. Here @var{switches} is a list of switches
8671 that are valid switches for @command{gcc}. They will be passed on to
8672 all compile steps performed by @command{gnatmake}.
8673
8674 @item -bargs @var{switches}
8675 @cindex @option{-bargs} (@command{gnatmake})
8676 Binder switches. Here @var{switches} is a list of switches
8677 that are valid switches for @code{gnatbind}. They will be passed on to
8678 all bind steps performed by @command{gnatmake}.
8679
8680 @item -largs @var{switches}
8681 @cindex @option{-largs} (@command{gnatmake})
8682 Linker switches. Here @var{switches} is a list of switches
8683 that are valid switches for @command{gnatlink}. They will be passed on to
8684 all link steps performed by @command{gnatmake}.
8685
8686 @item -margs @var{switches}
8687 @cindex @option{-margs} (@command{gnatmake})
8688 Make switches. The switches are directly interpreted by @command{gnatmake},
8689 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8690 or @option{-largs}.
8691 @end table
8692
8693 @node Notes on the Command Line
8694 @section Notes on the Command Line
8695
8696 @noindent
8697 This section contains some additional useful notes on the operation
8698 of the @command{gnatmake} command.
8699
8700 @itemize @bullet
8701 @item
8702 @cindex Recompilation, by @command{gnatmake}
8703 If @command{gnatmake} finds no ALI files, it recompiles the main program
8704 and all other units required by the main program.
8705 This means that @command{gnatmake}
8706 can be used for the initial compile, as well as during subsequent steps of
8707 the development cycle.
8708
8709 @item
8710 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8711 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8712 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8713 warning.
8714
8715 @item
8716 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8717 is used to specify both source and
8718 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8719 instead if you just want to specify
8720 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8721 if you want to specify library paths
8722 only.
8723
8724 @item
8725 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8726 This may conveniently be used to exclude standard libraries from
8727 consideration and in particular it means that the use of the
8728 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8729 unless @option{^-a^/ALL_FILES^} is also specified.
8730
8731 @item
8732 @command{gnatmake} has been designed to make the use of Ada libraries
8733 particularly convenient. Assume you have an Ada library organized
8734 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8735 of your Ada compilation units,
8736 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8737 specs of these units, but no bodies. Then to compile a unit
8738 stored in @code{main.adb}, which uses this Ada library you would just type
8739
8740 @smallexample
8741 @ifclear vms
8742 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8743 @end ifclear
8744 @ifset vms
8745 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8746            /SKIP_MISSING=@i{[OBJ_DIR]} main
8747 @end ifset
8748 @end smallexample
8749
8750 @item
8751 Using @command{gnatmake} along with the
8752 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8753 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8754 this switch,
8755 you can update the comments/format of your
8756 source files without having to recompile everything. Note, however, that
8757 adding or deleting lines in a source files may render its debugging
8758 info obsolete. If the file in question is a spec, the impact is rather
8759 limited, as that debugging info will only be useful during the
8760 elaboration phase of your program. For bodies the impact can be more
8761 significant. In all events, your debugger will warn you if a source file
8762 is more recent than the corresponding object, and alert you to the fact
8763 that the debugging information may be out of date.
8764 @end itemize
8765
8766 @node How gnatmake Works
8767 @section How @command{gnatmake} Works
8768
8769 @noindent
8770 Generally @command{gnatmake} automatically performs all necessary
8771 recompilations and you don't need to worry about how it works. However,
8772 it may be useful to have some basic understanding of the @command{gnatmake}
8773 approach and in particular to understand how it uses the results of
8774 previous compilations without incorrectly depending on them.
8775
8776 First a definition: an object file is considered @dfn{up to date} if the
8777 corresponding ALI file exists and if all the source files listed in the
8778 dependency section of this ALI file have time stamps matching those in
8779 the ALI file. This means that neither the source file itself nor any
8780 files that it depends on have been modified, and hence there is no need
8781 to recompile this file.
8782
8783 @command{gnatmake} works by first checking if the specified main unit is up
8784 to date. If so, no compilations are required for the main unit. If not,
8785 @command{gnatmake} compiles the main program to build a new ALI file that
8786 reflects the latest sources. Then the ALI file of the main unit is
8787 examined to find all the source files on which the main program depends,
8788 and @command{gnatmake} recursively applies the above procedure on all these
8789 files.
8790
8791 This process ensures that @command{gnatmake} only trusts the dependencies
8792 in an existing ALI file if they are known to be correct. Otherwise it
8793 always recompiles to determine a new, guaranteed accurate set of
8794 dependencies. As a result the program is compiled ``upside down'' from what may
8795 be more familiar as the required order of compilation in some other Ada
8796 systems. In particular, clients are compiled before the units on which
8797 they depend. The ability of GNAT to compile in any order is critical in
8798 allowing an order of compilation to be chosen that guarantees that
8799 @command{gnatmake} will recompute a correct set of new dependencies if
8800 necessary.
8801
8802 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8803 imported by several of the executables, it will be recompiled at most once.
8804
8805 Note: when using non-standard naming conventions
8806 (@pxref{Using Other File Names}), changing through a configuration pragmas
8807 file the version of a source and invoking @command{gnatmake} to recompile may
8808 have no effect, if the previous version of the source is still accessible
8809 by @command{gnatmake}. It may be necessary to use the switch
8810 ^-f^/FORCE_COMPILE^.
8811
8812 @node Examples of gnatmake Usage
8813 @section Examples of @command{gnatmake} Usage
8814
8815 @table @code
8816 @item gnatmake hello.adb
8817 Compile all files necessary to bind and link the main program
8818 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8819 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8820
8821 @item gnatmake main1 main2 main3
8822 Compile all files necessary to bind and link the main programs
8823 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8824 (containing unit @code{Main2}) and @file{main3.adb}
8825 (containing unit @code{Main3}) and bind and link the resulting object files
8826 to generate three executable files @file{^main1^MAIN1.EXE^},
8827 @file{^main2^MAIN2.EXE^}
8828 and @file{^main3^MAIN3.EXE^}.
8829
8830 @ifclear vms
8831 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8832 @end ifclear
8833
8834 @ifset vms
8835 @item gnatmake Main_Unit /QUIET
8836    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8837    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8838 @end ifset
8839 Compile all files necessary to bind and link the main program unit
8840 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8841 be done with optimization level 2 and the order of elaboration will be
8842 listed by the binder. @command{gnatmake} will operate in quiet mode, not
8843 displaying commands it is executing.
8844 @end table
8845
8846 @c *************************
8847 @node Improving Performance
8848 @chapter Improving Performance
8849 @cindex Improving performance
8850
8851 @noindent
8852 This chapter presents several topics related to program performance.
8853 It first describes some of the tradeoffs that need to be considered
8854 and some of the techniques for making your program run faster.
8855 It then documents the @command{gnatelim} tool, which can reduce
8856 the size of program executables.
8857
8858 @ifnottex
8859 @menu
8860 * Performance Considerations::
8861 * Reducing the Size of Ada Executables with gnatelim::
8862 @end menu
8863 @end ifnottex
8864
8865 @c *****************************
8866 @node Performance Considerations
8867 @section Performance Considerations
8868
8869 @noindent
8870 The GNAT system provides a number of options that allow a trade-off
8871 between
8872
8873 @itemize @bullet
8874 @item
8875 performance of the generated code
8876
8877 @item
8878 speed of compilation
8879
8880 @item
8881 minimization of dependences and recompilation
8882
8883 @item
8884 the degree of run-time checking.
8885 @end itemize
8886
8887 @noindent
8888 The defaults (if no options are selected) aim at improving the speed
8889 of compilation and minimizing dependences, at the expense of performance
8890 of the generated code:
8891
8892 @itemize @bullet
8893 @item
8894 no optimization
8895
8896 @item
8897 no inlining of subprogram calls
8898
8899 @item
8900 all run-time checks enabled except overflow and elaboration checks
8901 @end itemize
8902
8903 @noindent
8904 These options are suitable for most program development purposes. This
8905 chapter describes how you can modify these choices, and also provides
8906 some guidelines on debugging optimized code.
8907
8908 @menu
8909 * Controlling Run-Time Checks::
8910 * Use of Restrictions::
8911 * Optimization Levels::
8912 * Debugging Optimized Code::
8913 * Inlining of Subprograms::
8914 * Optimization and Strict Aliasing::
8915 @ifset vms
8916 * Coverage Analysis::
8917 @end ifset
8918 @end menu
8919
8920 @node Controlling Run-Time Checks
8921 @subsection Controlling Run-Time Checks
8922
8923 @noindent
8924 By default, GNAT generates all run-time checks, except arithmetic overflow
8925 checking for integer operations and checks for access before elaboration on
8926 subprogram calls. The latter are not required in default mode, because all
8927 necessary checking is done at compile time.
8928 @cindex @option{-gnatp} (@command{gcc})
8929 @cindex @option{-gnato} (@command{gcc})
8930 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8931 be modified. @xref{Run-Time Checks}.
8932
8933 Our experience is that the default is suitable for most development
8934 purposes.
8935
8936 We treat integer overflow specially because these
8937 are quite expensive and in our experience are not as important as other
8938 run-time checks in the development process. Note that division by zero
8939 is not considered an overflow check, and divide by zero checks are
8940 generated where required by default.
8941
8942 Elaboration checks are off by default, and also not needed by default, since
8943 GNAT uses a static elaboration analysis approach that avoids the need for
8944 run-time checking. This manual contains a full chapter discussing the issue
8945 of elaboration checks, and if the default is not satisfactory for your use,
8946 you should read this chapter.
8947
8948 For validity checks, the minimal checks required by the Ada Reference
8949 Manual (for case statements and assignments to array elements) are on
8950 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8951 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8952 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8953 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8954 are also suppressed entirely if @option{-gnatp} is used.
8955
8956 @cindex Overflow checks
8957 @cindex Checks, overflow
8958 @findex Suppress
8959 @findex Unsuppress
8960 @cindex pragma Suppress
8961 @cindex pragma Unsuppress
8962 Note that the setting of the switches controls the default setting of
8963 the checks. They may be modified using either @code{pragma Suppress} (to
8964 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8965 checks) in the program source.
8966
8967 @node Use of Restrictions
8968 @subsection Use of Restrictions
8969
8970 @noindent
8971 The use of pragma Restrictions allows you to control which features are
8972 permitted in your program. Apart from the obvious point that if you avoid
8973 relatively expensive features like finalization (enforceable by the use
8974 of pragma Restrictions (No_Finalization), the use of this pragma does not
8975 affect the generated code in most cases.
8976
8977 One notable exception to this rule is that the possibility of task abort
8978 results in some distributed overhead, particularly if finalization or
8979 exception handlers are used. The reason is that certain sections of code
8980 have to be marked as non-abortable.
8981
8982 If you use neither the @code{abort} statement, nor asynchronous transfer
8983 of control (@code{select .. then abort}), then this distributed overhead
8984 is removed, which may have a general positive effect in improving
8985 overall performance.  Especially code involving frequent use of tasking
8986 constructs and controlled types will show much improved performance.
8987 The relevant restrictions pragmas are
8988
8989 @smallexample
8990    pragma Restrictions (No_Abort_Statements);
8991    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8992 @end smallexample
8993
8994 @noindent
8995 It is recommended that these restriction pragmas be used if possible. Note
8996 that this also means that you can write code without worrying about the
8997 possibility of an immediate abort at any point.
8998
8999 @node Optimization Levels
9000 @subsection Optimization Levels
9001 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9002
9003 @noindent
9004 The default is optimization off. This results in the fastest compile
9005 times, but GNAT makes absolutely no attempt to optimize, and the
9006 generated programs are considerably larger and slower than when
9007 optimization is enabled. You can use the
9008 @ifclear vms
9009 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
9010 @end ifclear
9011 @ifset vms
9012 @code{OPTIMIZE} qualifier
9013 @end ifset
9014 to @command{gcc} to control the optimization level:
9015
9016 @table @option
9017 @item ^-O0^/OPTIMIZE=NONE^
9018 No optimization (the default);
9019 generates unoptimized code but has
9020 the fastest compilation time.
9021
9022 @item ^-O1^/OPTIMIZE=SOME^
9023 Medium level optimization;
9024 optimizes reasonably well but does not
9025 degrade compilation time significantly.
9026
9027 @item ^-O2^/OPTIMIZE=ALL^
9028 @ifset vms
9029 @itemx /OPTIMIZE=DEVELOPMENT
9030 @end ifset
9031 Full optimization;
9032 generates highly optimized code and has
9033 the slowest compilation time.
9034
9035 @item ^-O3^/OPTIMIZE=INLINING^
9036 Full optimization as in @option{-O2},
9037 and also attempts automatic inlining of small
9038 subprograms within a unit (@pxref{Inlining of Subprograms}).
9039 @end table
9040
9041 @noindent
9042 Higher optimization levels perform more global transformations on the
9043 program and apply more expensive analysis algorithms in order to generate
9044 faster and more compact code. The price in compilation time, and the
9045 resulting improvement in execution time,
9046 both depend on the particular application and the hardware environment.
9047 You should experiment to find the best level for your application.
9048
9049 Since the precise set of optimizations done at each level will vary from
9050 release to release (and sometime from target to target), it is best to think
9051 of the optimization settings in general terms.
9052 The @cite{Using GNU GCC} manual contains details about
9053 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9054 individually enable or disable specific optimizations.
9055
9056 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9057 been tested extensively at all optimization levels. There are some bugs
9058 which appear only with optimization turned on, but there have also been
9059 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9060 level of optimization does not improve the reliability of the code
9061 generator, which in practice is highly reliable at all optimization
9062 levels.
9063
9064 Note regarding the use of @option{-O3}: The use of this optimization level
9065 is generally discouraged with GNAT, since it often results in larger
9066 executables which run more slowly. See further discussion of this point
9067 in @ref{Inlining of Subprograms}.
9068
9069 @node Debugging Optimized Code
9070 @subsection Debugging Optimized Code
9071 @cindex Debugging optimized code
9072 @cindex Optimization and debugging
9073
9074 @noindent
9075 Although it is possible to do a reasonable amount of debugging at
9076 @ifclear vms
9077 non-zero optimization levels,
9078 the higher the level the more likely that
9079 @end ifclear
9080 @ifset vms
9081 @option{/OPTIMIZE} settings other than @code{NONE},
9082 such settings will make it more likely that
9083 @end ifset
9084 source-level constructs will have been eliminated by optimization.
9085 For example, if a loop is strength-reduced, the loop
9086 control variable may be completely eliminated and thus cannot be
9087 displayed in the debugger.
9088 This can only happen at @option{-O2} or @option{-O3}.
9089 Explicit temporary variables that you code might be eliminated at
9090 ^level^setting^ @option{-O1} or higher.
9091
9092 The use of the @option{^-g^/DEBUG^} switch,
9093 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9094 which is needed for source-level debugging,
9095 affects the size of the program executable on disk,
9096 and indeed the debugging information can be quite large.
9097 However, it has no effect on the generated code (and thus does not
9098 degrade performance)
9099
9100 Since the compiler generates debugging tables for a compilation unit before
9101 it performs optimizations, the optimizing transformations may invalidate some
9102 of the debugging data.  You therefore need to anticipate certain
9103 anomalous situations that may arise while debugging optimized code.
9104 These are the most common cases:
9105
9106 @enumerate
9107 @item
9108 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9109 commands show
9110 the PC bouncing back and forth in the code.  This may result from any of
9111 the following optimizations:
9112
9113 @itemize @bullet
9114 @item
9115 @i{Common subexpression elimination:} using a single instance of code for a
9116 quantity that the source computes several times.  As a result you
9117 may not be able to stop on what looks like a statement.
9118
9119 @item
9120 @i{Invariant code motion:} moving an expression that does not change within a
9121 loop, to the beginning of the loop.
9122
9123 @item
9124 @i{Instruction scheduling:} moving instructions so as to
9125 overlap loads and stores (typically) with other code, or in
9126 general to move computations of values closer to their uses. Often
9127 this causes you to pass an assignment statement without the assignment
9128 happening and then later bounce back to the statement when the
9129 value is actually needed.  Placing a breakpoint on a line of code
9130 and then stepping over it may, therefore, not always cause all the
9131 expected side-effects.
9132 @end itemize
9133
9134 @item
9135 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9136 two identical pieces of code are merged and the program counter suddenly
9137 jumps to a statement that is not supposed to be executed, simply because
9138 it (and the code following) translates to the same thing as the code
9139 that @emph{was} supposed to be executed.  This effect is typically seen in
9140 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9141 a @code{break} in a C @code{^switch^switch^} statement.
9142
9143 @item
9144 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9145 There are various reasons for this effect:
9146
9147 @itemize @bullet
9148 @item
9149 In a subprogram prologue, a parameter may not yet have been moved to its
9150 ``home''.
9151
9152 @item
9153 A variable may be dead, and its register re-used.  This is
9154 probably the most common cause.
9155
9156 @item
9157 As mentioned above, the assignment of a value to a variable may
9158 have been moved.
9159
9160 @item
9161 A variable may be eliminated entirely by value propagation or
9162 other means.  In this case, GCC may incorrectly generate debugging
9163 information for the variable
9164 @end itemize
9165
9166 @noindent
9167 In general, when an unexpected value appears for a local variable or parameter
9168 you should first ascertain if that value was actually computed by
9169 your program, as opposed to being incorrectly reported by the debugger.
9170 Record fields or
9171 array elements in an object designated by an access value
9172 are generally less of a problem, once you have ascertained that the access
9173 value is sensible.
9174 Typically, this means checking variables in the preceding code and in the
9175 calling subprogram to verify that the value observed is explainable from other
9176 values (one must apply the procedure recursively to those
9177 other values); or re-running the code and stopping a little earlier
9178 (perhaps before the call) and stepping to better see how the variable obtained
9179 the value in question; or continuing to step @emph{from} the point of the
9180 strange value to see if code motion had simply moved the variable's
9181 assignments later.
9182 @end enumerate
9183
9184 @noindent
9185 In light of such anomalies, a recommended technique is to use @option{-O0}
9186 early in the software development cycle, when extensive debugging capabilities
9187 are most needed, and then move to @option{-O1} and later @option{-O2} as
9188 the debugger becomes less critical.
9189 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9190 a release management issue.
9191 @ifclear vms
9192 Note that if you use @option{-g} you can then use the @command{strip} program
9193 on the resulting executable,
9194 which removes both debugging information and global symbols.
9195 @end ifclear
9196
9197 @node Inlining of Subprograms
9198 @subsection Inlining of Subprograms
9199
9200 @noindent
9201 A call to a subprogram in the current unit is inlined if all the
9202 following conditions are met:
9203
9204 @itemize @bullet
9205 @item
9206 The optimization level is at least @option{-O1}.
9207
9208 @item
9209 The called subprogram is suitable for inlining: It must be small enough
9210 and not contain nested subprograms or anything else that @command{gcc}
9211 cannot support in inlined subprograms.
9212
9213 @item
9214 The call occurs after the definition of the body of the subprogram.
9215
9216 @item
9217 @cindex pragma Inline
9218 @findex Inline
9219 Either @code{pragma Inline} applies to the subprogram or it is
9220 small and automatic inlining (optimization level @option{-O3}) is
9221 specified.
9222 @end itemize
9223
9224 @noindent
9225 Calls to subprograms in @code{with}'ed units are normally not inlined.
9226 To achieve this level of inlining, the following conditions must all be
9227 true:
9228
9229 @itemize @bullet
9230 @item
9231 The optimization level is at least @option{-O1}.
9232
9233 @item
9234 The called subprogram is suitable for inlining: It must be small enough
9235 and not contain nested subprograms or anything else @command{gcc} cannot
9236 support in inlined subprograms.
9237
9238 @item
9239 The call appears in a body (not in a package spec).
9240
9241 @item
9242 There is a @code{pragma Inline} for the subprogram.
9243
9244 @item
9245 @cindex @option{-gnatn} (@command{gcc})
9246 The @option{^-gnatn^/INLINE^} switch
9247 is used in the @command{gcc} command line
9248 @end itemize
9249
9250 Note that specifying the @option{-gnatn} switch causes additional
9251 compilation dependencies. Consider the following:
9252
9253 @smallexample @c ada
9254 @cartouche
9255 package R is
9256    procedure Q;
9257    pragma Inline (Q);
9258 end R;
9259 package body R is
9260    ...
9261 end R;
9262
9263 with R;
9264 procedure Main is
9265 begin
9266    ...
9267    R.Q;
9268 end Main;
9269 @end cartouche
9270 @end smallexample
9271
9272 @noindent
9273 With the default behavior (no @option{-gnatn} switch specified), the
9274 compilation of the @code{Main} procedure depends only on its own source,
9275 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9276 means that editing the body of @code{R} does not require recompiling
9277 @code{Main}.
9278
9279 On the other hand, the call @code{R.Q} is not inlined under these
9280 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9281 is compiled, the call will be inlined if the body of @code{Q} is small
9282 enough, but now @code{Main} depends on the body of @code{R} in
9283 @file{r.adb} as well as on the spec. This means that if this body is edited,
9284 the main program must be recompiled. Note that this extra dependency
9285 occurs whether or not the call is in fact inlined by @command{gcc}.
9286
9287 The use of front end inlining with @option{-gnatN} generates similar
9288 additional dependencies.
9289
9290 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9291 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9292 can be used to prevent
9293 all inlining. This switch overrides all other conditions and ensures
9294 that no inlining occurs. The extra dependences resulting from
9295 @option{-gnatn} will still be active, even if
9296 this switch is used to suppress the resulting inlining actions.
9297
9298 Note regarding the use of @option{-O3}: There is no difference in inlining
9299 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9300 pragma @code{Inline} assuming the use of @option{-gnatn}
9301 or @option{-gnatN} (the switches that activate inlining). If you have used
9302 pragma @code{Inline} in appropriate cases, then it is usually much better
9303 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9304 in this case only has the effect of inlining subprograms you did not
9305 think should be inlined. We often find that the use of @option{-O3} slows
9306 down code by performing excessive inlining, leading to increased instruction
9307 cache pressure from the increased code size. So the bottom line here is
9308 that you should not automatically assume that @option{-O3} is better than
9309 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9310 it actually improves performance.
9311
9312 @node Optimization and Strict Aliasing
9313 @subsection Optimization and Strict Aliasing
9314 @cindex Aliasing
9315 @cindex Strict Aliasing
9316 @cindex No_Strict_Aliasing
9317
9318 @noindent
9319 The strong typing capabilities of Ada allow an optimizer to generate
9320 efficient code in situations where other languages would be forced to
9321 make worst case assumptions preventing such optimizations. Consider
9322 the following example:
9323
9324 @smallexample @c ada
9325 @cartouche
9326 procedure R is
9327    type Int1 is new Integer;
9328    type Int2 is new Integer;
9329    type Int1A is access Int1;
9330    type Int2A is access Int2;
9331    Int1V : Int1A;
9332    Int2V : Int2A;
9333    ...
9334
9335 begin
9336    ...
9337    for J in Data'Range loop
9338       if Data (J) = Int1V.all then
9339          Int2V.all := Int2V.all + 1;
9340       end if;
9341    end loop;
9342    ...
9343 end R;
9344 @end cartouche
9345 @end smallexample
9346
9347 @noindent
9348 In this example, since the variable @code{Int1V} can only access objects
9349 of type @code{Int1}, and @code{Int2V} can only access objects of type
9350 @code{Int2}, there is no possibility that the assignment to
9351 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9352 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9353 for all iterations of the loop and avoid the extra memory reference
9354 required to dereference it each time through the loop.
9355
9356 This kind of optimization, called strict aliasing analysis, is
9357 triggered by specifying an optimization level of @option{-O2} or
9358 higher and allows @code{GNAT} to generate more efficient code
9359 when access values are involved.
9360
9361 However, although this optimization is always correct in terms of
9362 the formal semantics of the Ada Reference Manual, difficulties can
9363 arise if features like @code{Unchecked_Conversion} are used to break
9364 the typing system. Consider the following complete program example:
9365
9366 @smallexample @c ada
9367 @cartouche
9368 package p1 is
9369    type int1 is new integer;
9370    type int2 is new integer;
9371    type a1 is access int1;
9372    type a2 is access int2;
9373 end p1;
9374
9375 with p1; use p1;
9376 package p2 is
9377    function to_a2 (Input : a1) return a2;
9378 end p2;
9379
9380 with Unchecked_Conversion;
9381 package body p2 is
9382    function to_a2 (Input : a1) return a2 is
9383       function to_a2u is
9384         new Unchecked_Conversion (a1, a2);
9385    begin
9386       return to_a2u (Input);
9387    end to_a2;
9388 end p2;
9389
9390 with p2; use p2;
9391 with p1; use p1;
9392 with Text_IO; use Text_IO;
9393 procedure m is
9394    v1 : a1 := new int1;
9395    v2 : a2 := to_a2 (v1);
9396 begin
9397    v1.all := 1;
9398    v2.all := 0;
9399    put_line (int1'image (v1.all));
9400 end;
9401 @end cartouche
9402 @end smallexample
9403
9404 @noindent
9405 This program prints out 0 in @code{-O0} or @code{-O1}
9406 mode, but it prints out 1 in @code{-O2} mode. That's
9407 because in strict aliasing mode, the compiler can and
9408 does assume that the assignment to @code{v2.all} could not
9409 affect the value of @code{v1.all}, since different types
9410 are involved.
9411
9412 This behavior is not a case of non-conformance with the standard, since
9413 the Ada RM specifies that an unchecked conversion where the resulting
9414 bit pattern is not a correct value of the target type can result in an
9415 abnormal value and attempting to reference an abnormal value makes the
9416 execution of a program erroneous.  That's the case here since the result
9417 does not point to an object of type @code{int2}.  This means that the
9418 effect is entirely unpredictable.
9419
9420 However, although that explanation may satisfy a language
9421 lawyer, in practice an applications programmer expects an
9422 unchecked conversion involving pointers to create true
9423 aliases and the behavior of printing 1 seems plain wrong.
9424 In this case, the strict aliasing optimization is unwelcome.
9425
9426 Indeed the compiler recognizes this possibility, and the
9427 unchecked conversion generates a warning:
9428
9429 @smallexample
9430 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9431 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9432 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9433 @end smallexample
9434
9435 @noindent
9436 Unfortunately the problem is recognized when compiling the body of
9437 package @code{p2}, but the actual "bad" code is generated while
9438 compiling the body of @code{m} and this latter compilation does not see
9439 the suspicious @code{Unchecked_Conversion}.
9440
9441 As implied by the warning message, there are approaches you can use to
9442 avoid the unwanted strict aliasing optimization in a case like this.
9443
9444 One possibility is to simply avoid the use of @code{-O2}, but
9445 that is a bit drastic, since it throws away a number of useful
9446 optimizations that do not involve strict aliasing assumptions.
9447
9448 A less drastic approach is to compile the program using the
9449 option @code{-fno-strict-aliasing}. Actually it is only the
9450 unit containing the dereferencing of the suspicious pointer
9451 that needs to be compiled. So in this case, if we compile
9452 unit @code{m} with this switch, then we get the expected
9453 value of zero printed. Analyzing which units might need
9454 the switch can be painful, so a more reasonable approach
9455 is to compile the entire program with options @code{-O2}
9456 and @code{-fno-strict-aliasing}. If the performance is
9457 satisfactory with this combination of options, then the
9458 advantage is that the entire issue of possible "wrong"
9459 optimization due to strict aliasing is avoided.
9460
9461 To avoid the use of compiler switches, the configuration
9462 pragma @code{No_Strict_Aliasing} with no parameters may be
9463 used to specify that for all access types, the strict
9464 aliasing optimization should be suppressed.
9465
9466 However, these approaches are still overkill, in that they causes
9467 all manipulations of all access values to be deoptimized. A more
9468 refined approach is to concentrate attention on the specific
9469 access type identified as problematic.
9470
9471 First, if a careful analysis of uses of the pointer shows
9472 that there are no possible problematic references, then
9473 the warning can be suppressed by bracketing the
9474 instantiation of @code{Unchecked_Conversion} to turn
9475 the warning off:
9476
9477 @smallexample @c ada
9478    pragma Warnings (Off);
9479    function to_a2u is
9480      new Unchecked_Conversion (a1, a2);
9481    pragma Warnings (On);
9482 @end smallexample
9483
9484 @noindent
9485 Of course that approach is not appropriate for this particular
9486 example, since indeed there is a problematic reference. In this
9487 case we can take one of two other approaches.
9488
9489 The first possibility is to move the instantiation of unchecked
9490 conversion to the unit in which the type is declared. In
9491 this example, we would move the instantiation of
9492 @code{Unchecked_Conversion} from the body of package
9493 @code{p2} to the spec of package @code{p1}. Now the
9494 warning disappears. That's because any use of the
9495 access type knows there is a suspicious unchecked
9496 conversion, and the strict aliasing optimization
9497 is automatically suppressed for the type.
9498
9499 If it is not practical to move the unchecked conversion to the same unit
9500 in which the destination access type is declared (perhaps because the
9501 source type is not visible in that unit), you may use pragma
9502 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9503 same declarative sequence as the declaration of the access type:
9504
9505 @smallexample @c ada
9506    type a2 is access int2;
9507    pragma No_Strict_Aliasing (a2);
9508 @end smallexample
9509
9510 @noindent
9511 Here again, the compiler now knows that the strict aliasing optimization
9512 should be suppressed for any reference to type @code{a2} and the
9513 expected behavior is obtained.
9514
9515 Finally, note that although the compiler can generate warnings for
9516 simple cases of unchecked conversions, there are tricker and more
9517 indirect ways of creating type incorrect aliases which the compiler
9518 cannot detect. Examples are the use of address overlays and unchecked
9519 conversions involving composite types containing access types as
9520 components. In such cases, no warnings are generated, but there can
9521 still be aliasing problems. One safe coding practice is to forbid the
9522 use of address clauses for type overlaying, and to allow unchecked
9523 conversion only for primitive types. This is not really a significant
9524 restriction since any possible desired effect can be achieved by
9525 unchecked conversion of access values.
9526
9527 @ifset vms
9528 @node Coverage Analysis
9529 @subsection Coverage Analysis
9530
9531 @noindent
9532 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9533 the user to determine the distribution of execution time across a program,
9534 @pxref{Profiling} for details of usage.
9535 @end ifset
9536
9537 @node Reducing the Size of Ada Executables with gnatelim
9538 @section Reducing the Size of Ada Executables with @code{gnatelim}
9539 @findex gnatelim
9540
9541 @noindent
9542 This section describes @command{gnatelim}, a tool which detects unused
9543 subprograms and helps the compiler to create a smaller executable for your
9544 program.
9545
9546 @menu
9547 * About gnatelim::
9548 * Running gnatelim::
9549 * Correcting the List of Eliminate Pragmas::
9550 * Making Your Executables Smaller::
9551 * Summary of the gnatelim Usage Cycle::
9552 @end menu
9553
9554 @node About gnatelim
9555 @subsection About @code{gnatelim}
9556
9557 @noindent
9558 When a program shares a set of Ada
9559 packages with other programs, it may happen that this program uses
9560 only a fraction of the subprograms defined in these packages. The code
9561 created for these unused subprograms increases the size of the executable.
9562
9563 @code{gnatelim} tracks unused subprograms in an Ada program and
9564 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9565 subprograms that are declared but never called. By placing the list of
9566 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9567 recompiling your program, you may decrease the size of its executable,
9568 because the compiler will not generate the code for 'eliminated' subprograms.
9569 See GNAT Reference Manual for more information about this pragma.
9570
9571 @code{gnatelim} needs as its input data the name of the main subprogram
9572 and a bind file for a main subprogram.
9573
9574 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9575 the main subprogram. @code{gnatelim} can work with both Ada and C
9576 bind files; when both are present, it uses the Ada bind file.
9577 The following commands will build the program and create the bind file:
9578
9579 @smallexample
9580 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9581 $ gnatbind main_prog
9582 @end smallexample
9583
9584 Note that @code{gnatelim} needs neither object nor ALI files.
9585
9586 @node Running gnatelim
9587 @subsection Running @code{gnatelim}
9588
9589 @noindent
9590 @code{gnatelim} has the following command-line interface:
9591
9592 @smallexample
9593 $ gnatelim [options] name
9594 @end smallexample
9595
9596 @noindent
9597 @code{name} should be a name of a source file that contains the main subprogram
9598 of a program (partition).
9599
9600 @code{gnatelim} has the following switches:
9601
9602 @table @option
9603 @c !sort!
9604 @item ^-q^/QUIET^
9605 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9606 Quiet mode: by default @code{gnatelim} outputs to the standard error
9607 stream the number of program units left to be processed. This option turns
9608 this trace off.
9609
9610 @item ^-v^/VERBOSE^
9611 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9612 Verbose mode: @code{gnatelim} version information is printed as Ada
9613 comments to the standard output stream. Also, in addition to the number of
9614 program units left @code{gnatelim} will output the name of the current unit
9615 being processed.
9616
9617 @item ^-a^/ALL^
9618 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9619 Also look for subprograms from the GNAT run time that can be eliminated. Note
9620 that when @file{gnat.adc} is produced using this switch, the entire program
9621 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9622
9623 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9624 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9625 When looking for source files also look in directory @var{dir}. Specifying
9626 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9627 sources in the current directory.
9628
9629 @item ^-b^/BIND_FILE=^@var{bind_file}
9630 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9631 Specifies @var{bind_file} as the bind file to process. If not set, the name
9632 of the bind file is computed from the full expanded Ada name
9633 of a main subprogram.
9634
9635 @item ^-C^/CONFIG_FILE=^@var{config_file}
9636 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9637 Specifies a file @var{config_file} that contains configuration pragmas. The
9638 file must be specified with full path.
9639
9640 @item ^--GCC^/COMPILER^=@var{compiler_name}
9641 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9642 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9643 available on the path.
9644
9645 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9646 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9647 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9648 available on the path.
9649 @end table
9650
9651 @noindent
9652 @code{gnatelim} sends its output to the standard output stream, and all the
9653 tracing and debug information is sent to the standard error stream.
9654 In order to produce a proper GNAT configuration file
9655 @file{gnat.adc}, redirection must be used:
9656
9657 @smallexample
9658 @ifset vms
9659 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9660 @end ifset
9661 @ifclear vms
9662 $ gnatelim main_prog.adb > gnat.adc
9663 @end ifclear
9664 @end smallexample
9665
9666 @ifclear vms
9667 @noindent
9668 or
9669
9670 @smallexample
9671 $ gnatelim main_prog.adb >> gnat.adc
9672 @end smallexample
9673
9674 @noindent
9675 in order to append the @code{gnatelim} output to the existing contents of
9676 @file{gnat.adc}.
9677 @end ifclear
9678
9679 @node Correcting the List of Eliminate Pragmas
9680 @subsection Correcting the List of Eliminate Pragmas
9681
9682 @noindent
9683 In some rare cases @code{gnatelim} may try to eliminate
9684 subprograms that are actually called in the program. In this case, the
9685 compiler will generate an error message of the form:
9686
9687 @smallexample
9688 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9689 @end smallexample
9690
9691 @noindent
9692 You will need to manually remove the wrong @code{Eliminate} pragmas from
9693 the @file{gnat.adc} file. You should recompile your program
9694 from scratch after that, because you need a consistent @file{gnat.adc} file
9695 during the entire compilation.
9696
9697 @node Making Your Executables Smaller
9698 @subsection Making Your Executables Smaller
9699
9700 @noindent
9701 In order to get a smaller executable for your program you now have to
9702 recompile the program completely with the new @file{gnat.adc} file
9703 created by @code{gnatelim} in your current directory:
9704
9705 @smallexample
9706 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9707 @end smallexample
9708
9709 @noindent
9710 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9711 recompile everything
9712 with the set of pragmas @code{Eliminate} that you have obtained with
9713 @command{gnatelim}).
9714
9715 Be aware that the set of @code{Eliminate} pragmas is specific to each
9716 program. It is not recommended to merge sets of @code{Eliminate}
9717 pragmas created for different programs in one @file{gnat.adc} file.
9718
9719 @node Summary of the gnatelim Usage Cycle
9720 @subsection Summary of the gnatelim Usage Cycle
9721
9722 @noindent
9723 Here is a quick summary of the steps to be taken in order to reduce
9724 the size of your executables with @code{gnatelim}. You may use
9725 other GNAT options to control the optimization level,
9726 to produce the debugging information, to set search path, etc.
9727
9728 @enumerate
9729 @item
9730 Produce a bind file
9731
9732 @smallexample
9733 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9734 $ gnatbind main_prog
9735 @end smallexample
9736
9737 @item
9738 Generate a list of @code{Eliminate} pragmas
9739 @smallexample
9740 @ifset vms
9741 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9742 @end ifset
9743 @ifclear vms
9744 $ gnatelim main_prog >[>] gnat.adc
9745 @end ifclear
9746 @end smallexample
9747
9748 @item
9749 Recompile the application
9750
9751 @smallexample
9752 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9753 @end smallexample
9754
9755 @end enumerate
9756
9757 @c ********************************
9758 @node Renaming Files Using gnatchop
9759 @chapter Renaming Files Using @code{gnatchop}
9760 @findex gnatchop
9761
9762 @noindent
9763 This chapter discusses how to handle files with multiple units by using
9764 the @code{gnatchop} utility. This utility is also useful in renaming
9765 files to meet the standard GNAT default file naming conventions.
9766
9767 @menu
9768 * Handling Files with Multiple Units::
9769 * Operating gnatchop in Compilation Mode::
9770 * Command Line for gnatchop::
9771 * Switches for gnatchop::
9772 * Examples of gnatchop Usage::
9773 @end menu
9774
9775 @node Handling Files with Multiple Units
9776 @section Handling Files with Multiple Units
9777
9778 @noindent
9779 The basic compilation model of GNAT requires that a file submitted to the
9780 compiler have only one unit and there be a strict correspondence
9781 between the file name and the unit name.
9782
9783 The @code{gnatchop} utility allows both of these rules to be relaxed,
9784 allowing GNAT to process files which contain multiple compilation units
9785 and files with arbitrary file names. @code{gnatchop}
9786 reads the specified file and generates one or more output files,
9787 containing one unit per file. The unit and the file name correspond,
9788 as required by GNAT.
9789
9790 If you want to permanently restructure a set of ``foreign'' files so that
9791 they match the GNAT rules, and do the remaining development using the
9792 GNAT structure, you can simply use @command{gnatchop} once, generate the
9793 new set of files and work with them from that point on.
9794
9795 Alternatively, if you want to keep your files in the ``foreign'' format,
9796 perhaps to maintain compatibility with some other Ada compilation
9797 system, you can set up a procedure where you use @command{gnatchop} each
9798 time you compile, regarding the source files that it writes as temporary
9799 files that you throw away.
9800
9801 @node Operating gnatchop in Compilation Mode
9802 @section Operating gnatchop in Compilation Mode
9803
9804 @noindent
9805 The basic function of @code{gnatchop} is to take a file with multiple units
9806 and split it into separate files. The boundary between files is reasonably
9807 clear, except for the issue of comments and pragmas. In default mode, the
9808 rule is that any pragmas between units belong to the previous unit, except
9809 that configuration pragmas always belong to the following unit. Any comments
9810 belong to the following unit. These rules
9811 almost always result in the right choice of
9812 the split point without needing to mark it explicitly and most users will
9813 find this default to be what they want. In this default mode it is incorrect to
9814 submit a file containing only configuration pragmas, or one that ends in
9815 configuration pragmas, to @code{gnatchop}.
9816
9817 However, using a special option to activate ``compilation mode'',
9818 @code{gnatchop}
9819 can perform another function, which is to provide exactly the semantics
9820 required by the RM for handling of configuration pragmas in a compilation.
9821 In the absence of configuration pragmas (at the main file level), this
9822 option has no effect, but it causes such configuration pragmas to be handled
9823 in a quite different manner.
9824
9825 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9826 only configuration pragmas, then this file is appended to the
9827 @file{gnat.adc} file in the current directory. This behavior provides
9828 the required behavior described in the RM for the actions to be taken
9829 on submitting such a file to the compiler, namely that these pragmas
9830 should apply to all subsequent compilations in the same compilation
9831 environment. Using GNAT, the current directory, possibly containing a
9832 @file{gnat.adc} file is the representation
9833 of a compilation environment. For more information on the
9834 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
9835
9836 Second, in compilation mode, if @code{gnatchop}
9837 is given a file that starts with
9838 configuration pragmas, and contains one or more units, then these
9839 configuration pragmas are prepended to each of the chopped files. This
9840 behavior provides the required behavior described in the RM for the
9841 actions to be taken on compiling such a file, namely that the pragmas
9842 apply to all units in the compilation, but not to subsequently compiled
9843 units.
9844
9845 Finally, if configuration pragmas appear between units, they are appended
9846 to the previous unit. This results in the previous unit being illegal,
9847 since the compiler does not accept configuration pragmas that follow
9848 a unit. This provides the required RM behavior that forbids configuration
9849 pragmas other than those preceding the first compilation unit of a
9850 compilation.
9851
9852 For most purposes, @code{gnatchop} will be used in default mode. The
9853 compilation mode described above is used only if you need exactly
9854 accurate behavior with respect to compilations, and you have files
9855 that contain multiple units and configuration pragmas. In this
9856 circumstance the use of @code{gnatchop} with the compilation mode
9857 switch provides the required behavior, and is for example the mode
9858 in which GNAT processes the ACVC tests.
9859
9860 @node Command Line for gnatchop
9861 @section Command Line for @code{gnatchop}
9862
9863 @noindent
9864 The @code{gnatchop} command has the form:
9865
9866 @smallexample
9867 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9868       [@var{directory}]
9869 @end smallexample
9870
9871 @noindent
9872 The only required argument is the file name of the file to be chopped.
9873 There are no restrictions on the form of this file name. The file itself
9874 contains one or more Ada units, in normal GNAT format, concatenated
9875 together. As shown, more than one file may be presented to be chopped.
9876
9877 When run in default mode, @code{gnatchop} generates one output file in
9878 the current directory for each unit in each of the files.
9879
9880 @var{directory}, if specified, gives the name of the directory to which
9881 the output files will be written. If it is not specified, all files are
9882 written to the current directory.
9883
9884 For example, given a
9885 file called @file{hellofiles} containing
9886
9887 @smallexample @c ada
9888 @group
9889 @cartouche
9890 procedure hello;
9891
9892 with Text_IO; use Text_IO;
9893 procedure hello is
9894 begin
9895    Put_Line ("Hello");
9896 end hello;
9897 @end cartouche
9898 @end group
9899 @end smallexample
9900
9901 @noindent
9902 the command
9903
9904 @smallexample
9905 $ gnatchop ^hellofiles^HELLOFILES.^
9906 @end smallexample
9907
9908 @noindent
9909 generates two files in the current directory, one called
9910 @file{hello.ads} containing the single line that is the procedure spec,
9911 and the other called @file{hello.adb} containing the remaining text. The
9912 original file is not affected. The generated files can be compiled in
9913 the normal manner.
9914
9915 @noindent
9916 When gnatchop is invoked on a file that is empty or that contains only empty
9917 lines and/or comments, gnatchop will not fail, but will not produce any
9918 new sources.
9919
9920 For example, given a
9921 file called @file{toto.txt} containing
9922
9923 @smallexample @c ada
9924 @group
9925 @cartouche
9926 --  Just a comment
9927 @end cartouche
9928 @end group
9929 @end smallexample
9930
9931 @noindent
9932 the command
9933
9934 @smallexample
9935 $ gnatchop ^toto.txt^TOT.TXT^
9936 @end smallexample
9937
9938 @noindent
9939 will not produce any new file and will result in the following warnings:
9940
9941 @smallexample
9942 toto.txt:1:01: warning: empty file, contains no compilation units
9943 no compilation units found
9944 no source files written
9945 @end smallexample
9946
9947 @node Switches for gnatchop
9948 @section Switches for @code{gnatchop}
9949
9950 @noindent
9951 @command{gnatchop} recognizes the following switches:
9952
9953 @table @option
9954 @c !sort!
9955
9956 @item ^-c^/COMPILATION^
9957 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9958 Causes @code{gnatchop} to operate in compilation mode, in which
9959 configuration pragmas are handled according to strict RM rules. See
9960 previous section for a full description of this mode.
9961
9962 @ifclear vms
9963 @item -gnatxxx
9964 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9965 used to parse the given file. Not all @code{xxx} options make sense,
9966 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9967 process a source file that uses Latin-2 coding for identifiers.
9968 @end ifclear
9969
9970 @item ^-h^/HELP^
9971 Causes @code{gnatchop} to generate a brief help summary to the standard
9972 output file showing usage information.
9973
9974 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9975 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9976 Limit generated file names to the specified number @code{mm}
9977 of characters.
9978 This is useful if the
9979 resulting set of files is required to be interoperable with systems
9980 which limit the length of file names.
9981 @ifset vms
9982 If no value is given, or
9983 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9984 a default of 39, suitable for OpenVMS Alpha
9985 Systems, is assumed
9986 @end ifset
9987 @ifclear vms
9988 No space is allowed between the @option{-k} and the numeric value. The numeric
9989 value may be omitted in which case a default of @option{-k8},
9990 suitable for use
9991 with DOS-like file systems, is used. If no @option{-k} switch
9992 is present then
9993 there is no limit on the length of file names.
9994 @end ifclear
9995
9996 @item ^-p^/PRESERVE^
9997 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9998 Causes the file ^modification^creation^ time stamp of the input file to be
9999 preserved and used for the time stamp of the output file(s). This may be
10000 useful for preserving coherency of time stamps in an environment where
10001 @code{gnatchop} is used as part of a standard build process.
10002
10003 @item ^-q^/QUIET^
10004 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10005 Causes output of informational messages indicating the set of generated
10006 files to be suppressed. Warnings and error messages are unaffected.
10007
10008 @item ^-r^/REFERENCE^
10009 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10010 @findex Source_Reference
10011 Generate @code{Source_Reference} pragmas. Use this switch if the output
10012 files are regarded as temporary and development is to be done in terms
10013 of the original unchopped file. This switch causes
10014 @code{Source_Reference} pragmas to be inserted into each of the
10015 generated files to refers back to the original file name and line number.
10016 The result is that all error messages refer back to the original
10017 unchopped file.
10018 In addition, the debugging information placed into the object file (when
10019 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10020 specified)
10021 also refers back to this original file so that tools like profilers and
10022 debuggers will give information in terms of the original unchopped file.
10023
10024 If the original file to be chopped itself contains
10025 a @code{Source_Reference}
10026 pragma referencing a third file, then gnatchop respects
10027 this pragma, and the generated @code{Source_Reference} pragmas
10028 in the chopped file refer to the original file, with appropriate
10029 line numbers. This is particularly useful when @code{gnatchop}
10030 is used in conjunction with @code{gnatprep} to compile files that
10031 contain preprocessing statements and multiple units.
10032
10033 @item ^-v^/VERBOSE^
10034 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10035 Causes @code{gnatchop} to operate in verbose mode. The version
10036 number and copyright notice are output, as well as exact copies of
10037 the gnat1 commands spawned to obtain the chop control information.
10038
10039 @item ^-w^/OVERWRITE^
10040 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10041 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10042 fatal error if there is already a file with the same name as a
10043 file it would otherwise output, in other words if the files to be
10044 chopped contain duplicated units. This switch bypasses this
10045 check, and causes all but the last instance of such duplicated
10046 units to be skipped.
10047
10048 @ifclear vms
10049 @item --GCC=xxxx
10050 @cindex @option{--GCC=} (@code{gnatchop})
10051 Specify the path of the GNAT parser to be used. When this switch is used,
10052 no attempt is made to add the prefix to the GNAT parser executable.
10053 @end ifclear
10054 @end table
10055
10056 @node Examples of gnatchop Usage
10057 @section Examples of @code{gnatchop} Usage
10058
10059 @table @code
10060 @ifset vms
10061 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10062 @end ifset
10063 @ifclear vms
10064 @item gnatchop -w hello_s.ada prerelease/files
10065 @end ifclear
10066
10067 Chops the source file @file{hello_s.ada}. The output files will be
10068 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10069 overwriting any
10070 files with matching names in that directory (no files in the current
10071 directory are modified).
10072
10073 @item gnatchop ^archive^ARCHIVE.^
10074 Chops the source file @file{^archive^ARCHIVE.^}
10075 into the current directory. One
10076 useful application of @code{gnatchop} is in sending sets of sources
10077 around, for example in email messages. The required sources are simply
10078 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10079 command), and then
10080 @code{gnatchop} is used at the other end to reconstitute the original
10081 file names.
10082
10083 @item gnatchop file1 file2 file3 direc
10084 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10085 the resulting files in the directory @file{direc}. Note that if any units
10086 occur more than once anywhere within this set of files, an error message
10087 is generated, and no files are written. To override this check, use the
10088 @option{^-w^/OVERWRITE^} switch,
10089 in which case the last occurrence in the last file will
10090 be the one that is output, and earlier duplicate occurrences for a given
10091 unit will be skipped.
10092 @end table
10093
10094 @node Configuration Pragmas
10095 @chapter Configuration Pragmas
10096 @cindex Configuration pragmas
10097 @cindex Pragmas, configuration
10098
10099 @noindent
10100 In Ada 95, configuration pragmas include those pragmas described as
10101 such in the Ada 95 Reference Manual, as well as
10102 implementation-dependent pragmas that are configuration pragmas. See the
10103 individual descriptions of pragmas in the GNAT Reference Manual for
10104 details on these additional GNAT-specific configuration pragmas. Most
10105 notably, the pragma @code{Source_File_Name}, which allows
10106 specifying non-default names for source files, is a configuration
10107 pragma. The following is a complete list of configuration pragmas
10108 recognized by @code{GNAT}:
10109
10110 @smallexample
10111    Ada_83
10112    Ada_95
10113    Ada_05
10114    C_Pass_By_Copy
10115    Component_Alignment
10116    Detect_Blocking
10117    Discard_Names
10118    Elaboration_Checks
10119    Eliminate
10120    Extend_System
10121    External_Name_Casing
10122    Float_Representation
10123    Initialize_Scalars
10124    License
10125    Locking_Policy
10126    Long_Float
10127    Normalize_Scalars
10128    Polling
10129    Profile
10130    Profile_Warnings
10131    Propagate_Exceptions
10132    Queuing_Policy
10133    Ravenscar
10134    Restricted_Run_Time
10135    Restrictions
10136    Restrictions_Warnings
10137    Reviewable
10138    Source_File_Name
10139    Style_Checks
10140    Suppress
10141    Task_Dispatching_Policy
10142    Universal_Data
10143    Unsuppress
10144    Use_VADS_Size
10145    Warnings
10146    Validity_Checks
10147 @end smallexample
10148
10149 @menu
10150 * Handling of Configuration Pragmas::
10151 * The Configuration Pragmas Files::
10152 @end menu
10153
10154 @node Handling of Configuration Pragmas
10155 @section Handling of Configuration Pragmas
10156
10157 Configuration pragmas may either appear at the start of a compilation
10158 unit, in which case they apply only to that unit, or they may apply to
10159 all compilations performed in a given compilation environment.
10160
10161 GNAT also provides the @code{gnatchop} utility to provide an automatic
10162 way to handle configuration pragmas following the semantics for
10163 compilations (that is, files with multiple units), described in the RM.
10164 See @ref{Operating gnatchop in Compilation Mode} for details.
10165 However, for most purposes, it will be more convenient to edit the
10166 @file{gnat.adc} file that contains configuration pragmas directly,
10167 as described in the following section.
10168
10169 @node The Configuration Pragmas Files
10170 @section The Configuration Pragmas Files
10171 @cindex @file{gnat.adc}
10172
10173 @noindent
10174 In GNAT a compilation environment is defined by the current
10175 directory at the time that a compile command is given. This current
10176 directory is searched for a file whose name is @file{gnat.adc}. If
10177 this file is present, it is expected to contain one or more
10178 configuration pragmas that will be applied to the current compilation.
10179 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10180 considered.
10181
10182 Configuration pragmas may be entered into the @file{gnat.adc} file
10183 either by running @code{gnatchop} on a source file that consists only of
10184 configuration pragmas, or more conveniently  by
10185 direct editing of the @file{gnat.adc} file, which is a standard format
10186 source file.
10187
10188 In addition to @file{gnat.adc}, one additional file containing configuration
10189 pragmas may be applied to the current compilation using the switch
10190 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10191 contains only configuration pragmas. These configuration pragmas are
10192 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10193 is present and switch @option{-gnatA} is not used).
10194
10195 It is allowed to specify several switches @option{-gnatec}, however only
10196 the last one on the command line will be taken into account.
10197
10198 If you are using project file, a separate mechanism is provided using
10199 project attributes, see @ref{Specifying Configuration Pragmas} for more
10200 details.
10201
10202 @ifset vms
10203 Of special interest to GNAT OpenVMS Alpha is the following
10204 configuration pragma:
10205
10206 @smallexample @c ada
10207 @cartouche
10208 pragma Extend_System (Aux_DEC);
10209 @end cartouche
10210 @end smallexample
10211
10212 @noindent
10213 In the presence of this pragma, GNAT adds to the definition of the
10214 predefined package SYSTEM all the additional types and subprograms that are
10215 defined in DEC Ada. See @ref{Compatibility with DEC Ada} for details.
10216 @end ifset
10217
10218 @node Handling Arbitrary File Naming Conventions Using gnatname
10219 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10220 @cindex Arbitrary File Naming Conventions
10221
10222 @menu
10223 * Arbitrary File Naming Conventions::
10224 * Running gnatname::
10225 * Switches for gnatname::
10226 * Examples of gnatname Usage::
10227 @end menu
10228
10229 @node Arbitrary File Naming Conventions
10230 @section Arbitrary File Naming Conventions
10231
10232 @noindent
10233 The GNAT compiler must be able to know the source file name of a compilation
10234 unit.  When using the standard GNAT default file naming conventions
10235 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10236 does not need additional information.
10237
10238 @noindent
10239 When the source file names do not follow the standard GNAT default file naming
10240 conventions, the GNAT compiler must be given additional information through
10241 a configuration pragmas file (@pxref{Configuration Pragmas})
10242 or a project file.
10243 When the non standard file naming conventions are well-defined,
10244 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10245 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10246 if the file naming conventions are irregular or arbitrary, a number
10247 of pragma @code{Source_File_Name} for individual compilation units
10248 must be defined.
10249 To help maintain the correspondence between compilation unit names and
10250 source file names within the compiler,
10251 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10252 set of files.
10253
10254 @node Running gnatname
10255 @section Running @code{gnatname}
10256
10257 @noindent
10258 The usual form of the @code{gnatname} command is
10259
10260 @smallexample
10261 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10262 @end smallexample
10263
10264 @noindent
10265 All of the arguments are optional. If invoked without any argument,
10266 @code{gnatname} will display its usage.
10267
10268 @noindent
10269 When used with at least one naming pattern, @code{gnatname} will attempt to
10270 find all the compilation units in files that follow at least one of the
10271 naming patterns. To find these compilation units,
10272 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10273 regular files.
10274
10275 @noindent
10276 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10277 Each Naming Pattern is enclosed between double quotes.
10278 A Naming Pattern is a regular expression similar to the wildcard patterns
10279 used in file names by the Unix shells or the DOS prompt.
10280
10281 @noindent
10282 Examples of Naming Patterns are
10283
10284 @smallexample
10285    "*.[12].ada"
10286    "*.ad[sb]*"
10287    "body_*"    "spec_*"
10288 @end smallexample
10289
10290 @noindent
10291 For a more complete description of the syntax of Naming Patterns,
10292 see the second kind of regular expressions described in @file{g-regexp.ads}
10293 (the ``Glob'' regular expressions).
10294
10295 @noindent
10296 When invoked with no switches, @code{gnatname} will create a configuration
10297 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10298 @code{Source_File_Name} for each file that contains a valid Ada unit.
10299
10300 @node Switches for gnatname
10301 @section Switches for @code{gnatname}
10302
10303 @noindent
10304 Switches for @code{gnatname} must precede any specified Naming Pattern.
10305
10306 @noindent
10307 You may specify any of the following switches to @code{gnatname}:
10308
10309 @table @option
10310 @c !sort!
10311
10312 @item ^-c^/CONFIG_FILE=^@file{file}
10313 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10314 Create a configuration pragmas file @file{file} (instead of the default
10315 @file{gnat.adc}).
10316 @ifclear vms
10317 There may be zero, one or more space between @option{-c} and
10318 @file{file}.
10319 @end ifclear
10320 @file{file} may include directory information. @file{file} must be
10321 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10322 When a switch @option{^-c^/CONFIG_FILE^} is
10323 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10324
10325 @item ^-d^/SOURCE_DIRS=^@file{dir}
10326 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10327 Look for source files in directory @file{dir}. There may be zero, one or more
10328 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10329 When a switch @option{^-d^/SOURCE_DIRS^}
10330 is specified, the current working directory will not be searched for source
10331 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10332 or @option{^-D^/DIR_FILES^} switch.
10333 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10334 If @file{dir} is a relative path, it is relative to the directory of
10335 the configuration pragmas file specified with switch
10336 @option{^-c^/CONFIG_FILE^},
10337 or to the directory of the project file specified with switch
10338 @option{^-P^/PROJECT_FILE^} or,
10339 if neither switch @option{^-c^/CONFIG_FILE^}
10340 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10341 current working directory. The directory
10342 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10343
10344 @item ^-D^/DIRS_FILE=^@file{file}
10345 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10346 Look for source files in all directories listed in text file @file{file}.
10347 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10348 and @file{file}.
10349 @file{file} must be an existing, readable text file.
10350 Each non empty line in @file{file} must be a directory.
10351 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10352 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10353 @file{file}.
10354
10355 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10356 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10357 Foreign patterns. Using this switch, it is possible to add sources of languages
10358 other than Ada to the list of sources of a project file.
10359 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10360 For example,
10361 @smallexample
10362 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10363 @end smallexample
10364 @noindent
10365 will look for Ada units in all files with the @file{.ada} extension,
10366 and will add to the list of file for project @file{prj.gpr} the C files
10367 with extension ".^c^C^".
10368
10369 @item ^-h^/HELP^
10370 @cindex @option{^-h^/HELP^} (@code{gnatname})
10371 Output usage (help) information. The output is written to @file{stdout}.
10372
10373 @item ^-P^/PROJECT_FILE=^@file{proj}
10374 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10375 Create or update project file @file{proj}. There may be zero, one or more space
10376 between @option{-P} and @file{proj}. @file{proj} may include directory
10377 information. @file{proj} must be writable.
10378 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10379 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10380 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10381
10382 @item ^-v^/VERBOSE^
10383 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10384 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10385 This includes name of the file written, the name of the directories to search
10386 and, for each file in those directories whose name matches at least one of
10387 the Naming Patterns, an indication of whether the file contains a unit,
10388 and if so the name of the unit.
10389
10390 @item ^-v -v^/VERBOSE /VERBOSE^
10391 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10392 Very Verbose mode. In addition to the output produced in verbose mode,
10393 for each file in the searched directories whose name matches none of
10394 the Naming Patterns, an indication is given that there is no match.
10395
10396 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10397 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10398 Excluded patterns. Using this switch, it is possible to exclude some files
10399 that would match the name patterns. For example,
10400 @smallexample
10401 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10402 @end smallexample
10403 @noindent
10404 will look for Ada units in all files with the @file{.ada} extension,
10405 except those whose names end with @file{_nt.ada}.
10406
10407 @end table
10408
10409 @node Examples of gnatname Usage
10410 @section Examples of @code{gnatname} Usage
10411
10412 @ifset vms
10413 @smallexample
10414 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10415 @end smallexample
10416 @end ifset
10417
10418 @ifclear vms
10419 @smallexample
10420 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10421 @end smallexample
10422 @end ifclear
10423
10424 @noindent
10425 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10426 and be writable. In addition, the directory
10427 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10428 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10429
10430 @ifclear vms
10431 Note the optional spaces after @option{-c} and @option{-d}.
10432 @end ifclear
10433
10434 @smallexample
10435 @ifclear vms
10436 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10437   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10438 @end ifclear
10439 @ifset vms
10440 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10441   /EXCLUDED_PATTERN=*_nt_body.ada
10442   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10443   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10444 @end ifset
10445 @end smallexample
10446
10447 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10448 even in conjunction with one or several switches
10449 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10450 are used in this example.
10451
10452 @c *****************************************
10453 @c * G N A T  P r o j e c t  M a n a g e r *
10454 @c *****************************************
10455 @node GNAT Project Manager
10456 @chapter GNAT Project Manager
10457
10458 @menu
10459 * Introduction::
10460 * Examples of Project Files::
10461 * Project File Syntax::
10462 * Objects and Sources in Project Files::
10463 * Importing Projects::
10464 * Project Extension::
10465 * Project Hierarchy Extension::
10466 * External References in Project Files::
10467 * Packages in Project Files::
10468 * Variables from Imported Projects::
10469 * Naming Schemes::
10470 * Library Projects::
10471 * Stand-alone Library Projects::
10472 * Switches Related to Project Files::
10473 * Tools Supporting Project Files::
10474 * An Extended Example::
10475 * Project File Complete Syntax::
10476 @end menu
10477
10478 @c ****************
10479 @c * Introduction *
10480 @c ****************
10481
10482 @node Introduction
10483 @section Introduction
10484
10485 @noindent
10486 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10487 you to manage complex builds involving a number of source files, directories,
10488 and compilation options for different system configurations. In particular,
10489 project files allow you to specify:
10490 @itemize @bullet
10491 @item
10492 The directory or set of directories containing the source files, and/or the
10493 names of the specific source files themselves
10494 @item
10495 The directory in which the compiler's output
10496 (@file{ALI} files, object files, tree files) is to be placed
10497 @item
10498 The directory in which the executable programs is to be placed
10499 @item
10500 ^Switch^Switch^ settings for any of the project-enabled tools
10501 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10502 @code{gnatfind}); you can apply these settings either globally or to individual
10503 compilation units.
10504 @item
10505 The source files containing the main subprogram(s) to be built
10506 @item
10507 The source programming language(s) (currently Ada and/or C)
10508 @item
10509 Source file naming conventions; you can specify these either globally or for
10510 individual compilation units
10511 @end itemize
10512
10513 @menu
10514 * Project Files::
10515 @end menu
10516
10517 @node Project Files
10518 @subsection Project Files
10519
10520 @noindent
10521 Project files are written in a syntax close to that of Ada, using  familiar
10522 notions such as packages, context clauses, declarations, default values,
10523 assignments, and inheritance. Finally, project files can be built
10524 hierarchically from other project files, simplifying complex system
10525 integration and project reuse.
10526
10527 A @dfn{project} is a specific set of values for various compilation properties.
10528 The settings for a given project are described by means of
10529 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10530 Property values in project files are either strings or lists of strings.
10531 Properties that are not explicitly set receive default values.  A project
10532 file may interrogate the values of @dfn{external variables} (user-defined
10533 command-line switches or environment variables), and it may specify property
10534 settings conditionally, based on the value of such variables.
10535
10536 In simple cases, a project's source files depend only on other source files
10537 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10538 used in
10539 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10540 the Project Manager also allows more sophisticated arrangements,
10541 where the source files in one project depend on source files in other
10542 projects:
10543 @itemize @bullet
10544 @item
10545 One project can @emph{import} other projects containing needed source files.
10546 @item
10547 You can organize GNAT projects in a hierarchy: a @emph{child} project
10548 can extend a @emph{parent} project, inheriting the parent's source files and
10549 optionally overriding any of them with alternative versions
10550 @end itemize
10551
10552 @noindent
10553 More generally, the Project Manager lets you structure large development
10554 efforts into hierarchical subsystems, where build decisions are delegated
10555 to the subsystem level, and thus different compilation environments
10556 (^switch^switch^ settings) used for different subsystems.
10557
10558 The Project Manager is invoked through the
10559 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10560 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10561 @ifclear vms
10562 There may be zero, one or more spaces between @option{-P} and
10563 @option{@emph{projectfile}}.
10564 @end ifclear
10565 If you want to define (on the command line) an external variable that is
10566 queried by the project file, you must use the
10567 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10568 The Project Manager parses and interprets the project file, and drives the
10569 invoked tool based on the project settings.
10570
10571 The Project Manager supports a wide range of development strategies,
10572 for systems of all sizes.  Here are some typical practices that are
10573 easily handled:
10574 @itemize @bullet
10575 @item
10576 Using a common set of source files, but generating object files in different
10577 directories via different ^switch^switch^ settings
10578 @item
10579 Using a mostly-shared set of source files, but with different versions of
10580 some unit or units
10581 @end itemize
10582
10583 @noindent
10584 The destination of an executable can be controlled inside a project file
10585 using the @option{^-o^-o^}
10586 ^switch^switch^.
10587 In the absence of such a ^switch^switch^ either inside
10588 the project file or on the command line, any executable files generated by
10589 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10590 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10591 in the object directory of the project.
10592
10593 You can use project files to achieve some of the effects of a source
10594 versioning system (for example, defining separate projects for
10595 the different sets of sources that comprise different releases) but the
10596 Project Manager is independent of any source configuration management tools
10597 that might be used by the developers.
10598
10599 The next section introduces the main features of GNAT's project facility
10600 through a sequence of examples; subsequent sections will present the syntax
10601 and semantics in more detail. A more formal description of the project
10602 facility appears in the GNAT Reference Manual.
10603
10604 @c *****************************
10605 @c * Examples of Project Files *
10606 @c *****************************
10607
10608 @node Examples of Project Files
10609 @section Examples of Project Files
10610 @noindent
10611 This section illustrates some of the typical uses of project files and
10612 explains their basic structure and behavior.
10613
10614 @menu
10615 * Common Sources with Different ^Switches^Switches^ and Directories::
10616 * Using External Variables::
10617 * Importing Other Projects::
10618 * Extending a Project::
10619 @end menu
10620
10621 @node Common Sources with Different ^Switches^Switches^ and Directories
10622 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10623
10624 @menu
10625 * Source Files::
10626 * Specifying the Object Directory::
10627 * Specifying the Exec Directory::
10628 * Project File Packages::
10629 * Specifying ^Switch^Switch^ Settings::
10630 * Main Subprograms::
10631 * Executable File Names::
10632 * Source File Naming Conventions::
10633 * Source Language(s)::
10634 @end menu
10635
10636 @noindent
10637 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10638 @file{proc.adb} are in the @file{/common} directory.  The file
10639 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10640 package @code{Pack}.  We want to compile these source files under two sets
10641 of ^switches^switches^:
10642 @itemize @bullet
10643 @item
10644 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10645 and the @option{^-gnata^-gnata^},
10646 @option{^-gnato^-gnato^},
10647 and @option{^-gnatE^-gnatE^} switches to the
10648 compiler; the compiler's output is to appear in @file{/common/debug}
10649 @item
10650 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10651 to the compiler; the compiler's output is to appear in @file{/common/release}
10652 @end itemize
10653
10654 @noindent
10655 The GNAT project files shown below, respectively @file{debug.gpr} and
10656 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10657
10658 Schematically:
10659 @smallexample
10660 @group
10661 ^/common^[COMMON]^
10662   debug.gpr
10663   release.gpr
10664   pack.ads
10665   pack.adb
10666   proc.adb
10667 @end group
10668 @group
10669 ^/common/debug^[COMMON.DEBUG]^
10670   proc.ali, proc.o
10671   pack.ali, pack.o
10672 @end group
10673 @group
10674 ^/common/release^[COMMON.RELEASE]^
10675   proc.ali, proc.o
10676   pack.ali, pack.o
10677 @end group
10678 @end smallexample
10679 Here are the corresponding project files:
10680
10681 @smallexample @c projectfile
10682 @group
10683 project Debug is
10684   for Object_Dir use "debug";
10685   for Main use ("proc");
10686
10687   package Builder is
10688     for ^Default_Switches^Default_Switches^ ("Ada")
10689         use ("^-g^-g^");
10690     for Executable ("proc.adb") use "proc1";
10691   end Builder;
10692 @end group
10693
10694 @group
10695   package Compiler is
10696     for ^Default_Switches^Default_Switches^ ("Ada")
10697        use ("-fstack-check",
10698             "^-gnata^-gnata^",
10699             "^-gnato^-gnato^",
10700             "^-gnatE^-gnatE^");
10701   end Compiler;
10702 end Debug;
10703 @end group
10704 @end smallexample
10705
10706 @smallexample @c projectfile
10707 @group
10708 project Release is
10709   for Object_Dir use "release";
10710   for Exec_Dir use ".";
10711   for Main use ("proc");
10712
10713   package Compiler is
10714     for ^Default_Switches^Default_Switches^ ("Ada")
10715         use ("^-O2^-O2^");
10716   end Compiler;
10717 end Release;
10718 @end group
10719 @end smallexample
10720
10721 @noindent
10722 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10723 insensitive), and analogously the project defined by @file{release.gpr} is
10724 @code{"Release"}.  For consistency the file should have the same name as the
10725 project, and the project file's extension should be @code{"gpr"}. These
10726 conventions are not required, but a warning is issued if they are not followed.
10727
10728 If the current directory is @file{^/temp^[TEMP]^}, then the command
10729 @smallexample
10730 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10731 @end smallexample
10732
10733 @noindent
10734 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10735 as well as the @code{^proc1^PROC1.EXE^} executable,
10736 using the ^switch^switch^ settings defined in the project file.
10737
10738 Likewise, the command
10739 @smallexample
10740 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10741 @end smallexample
10742
10743 @noindent
10744 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10745 and the @code{^proc^PROC.EXE^}
10746 executable in @file{^/common^[COMMON]^},
10747 using the ^switch^switch^ settings from the project file.
10748
10749 @node Source Files
10750 @unnumberedsubsubsec Source Files
10751
10752 @noindent
10753 If a project file does not explicitly specify a set of source directories or
10754 a set of source files, then by default the project's source files are the
10755 Ada source files in the project file directory.  Thus @file{pack.ads},
10756 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10757
10758 @node Specifying the Object Directory
10759 @unnumberedsubsubsec Specifying the Object Directory
10760
10761 @noindent
10762 Several project properties are modeled by Ada-style @emph{attributes};
10763 a property is defined by supplying the equivalent of an Ada attribute
10764 definition clause in the project file.
10765 A project's object directory is another such a property; the corresponding
10766 attribute is @code{Object_Dir}, and its value is also a string expression,
10767 specified either as absolute or relative. In the later case,
10768 it is relative to the project file directory. Thus the compiler's
10769 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10770 (for the @code{Debug} project)
10771 and to @file{^/common/release^[COMMON.RELEASE]^}
10772 (for the @code{Release} project).
10773 If @code{Object_Dir} is not specified, then the default is the project file
10774 directory itself.
10775
10776 @node Specifying the Exec Directory
10777 @unnumberedsubsubsec Specifying the Exec Directory
10778
10779 @noindent
10780 A project's exec directory is another property; the corresponding
10781 attribute is @code{Exec_Dir}, and its value is also a string expression,
10782 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10783 then the default is the object directory (which may also be the project file
10784 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10785 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10786 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10787 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10788
10789 @node Project File Packages
10790 @unnumberedsubsubsec Project File Packages
10791
10792 @noindent
10793 A GNAT tool that is integrated with the Project Manager is modeled by a
10794 corresponding package in the project file. In the example above,
10795 The @code{Debug} project defines the packages @code{Builder}
10796 (for @command{gnatmake}) and @code{Compiler};
10797 the @code{Release} project defines only the @code{Compiler} package.
10798
10799 The Ada-like package syntax is not to be taken literally.  Although packages in
10800 project files bear a surface resemblance to packages in Ada source code, the
10801 notation is simply a way to convey a grouping of properties for a named
10802 entity.  Indeed, the package names permitted in project files are restricted
10803 to a predefined set, corresponding to the project-aware tools, and the contents
10804 of packages are limited to a small set of constructs.
10805 The packages in the example above contain attribute definitions.
10806
10807 @node Specifying ^Switch^Switch^ Settings
10808 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10809
10810 @noindent
10811 ^Switch^Switch^ settings for a project-aware tool can be specified through
10812 attributes in the package that corresponds to the tool.
10813 The example above illustrates one of the relevant attributes,
10814 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10815 in both project files.
10816 Unlike simple attributes like @code{Source_Dirs},
10817 @code{^Default_Switches^Default_Switches^} is
10818 known as an @emph{associative array}.  When you define this attribute, you must
10819 supply an ``index'' (a literal string), and the effect of the attribute
10820 definition is to set the value of the array at the specified index.
10821 For the @code{^Default_Switches^Default_Switches^} attribute,
10822 the index is a programming language (in our case, Ada),
10823 and the value specified (after @code{use}) must be a list
10824 of string expressions.
10825
10826 The attributes permitted in project files are restricted to a predefined set.
10827 Some may appear at project level, others in packages.
10828 For any attribute that is an associative array, the index must always be a
10829 literal string, but the restrictions on this string (e.g., a file name or a
10830 language name) depend on the individual attribute.
10831 Also depending on the attribute, its specified value will need to be either a
10832 string or a string list.
10833
10834 In the @code{Debug} project, we set the switches for two tools,
10835 @command{gnatmake} and the compiler, and thus we include the two corresponding
10836 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10837 attribute with index @code{"Ada"}.
10838 Note that the package corresponding to
10839 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10840 similar, but only includes the @code{Compiler} package.
10841
10842 In project @code{Debug} above, the ^switches^switches^ starting with
10843 @option{-gnat} that are specified in package @code{Compiler}
10844 could have been placed in package @code{Builder}, since @command{gnatmake}
10845 transmits all such ^switches^switches^ to the compiler.
10846
10847 @node Main Subprograms
10848 @unnumberedsubsubsec Main Subprograms
10849
10850 @noindent
10851 One of the specifiable properties of a project is a list of files that contain
10852 main subprograms.  This property is captured in the @code{Main} attribute,
10853 whose value is a list of strings.  If a project defines the @code{Main}
10854 attribute, it is not necessary to identify the main subprogram(s) when
10855 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
10856
10857 @node Executable File Names
10858 @unnumberedsubsubsec Executable File Names
10859
10860 @noindent
10861 By default, the executable file name corresponding to a main source is
10862 deduced from the main source file name. Through the attributes
10863 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10864 it is possible to change this default.
10865 In project @code{Debug} above, the executable file name
10866 for main source @file{^proc.adb^PROC.ADB^} is
10867 @file{^proc1^PROC1.EXE^}.
10868 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10869 of the the executable files, when no attribute @code{Executable} applies:
10870 its value replace the platform-specific executable suffix.
10871 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10872 specify a non default executable file name when several mains are built at once
10873 in a single @command{gnatmake} command.
10874
10875 @node Source File Naming Conventions
10876 @unnumberedsubsubsec Source File Naming Conventions
10877
10878 @noindent
10879 Since the project files above do not specify any source file naming
10880 conventions, the GNAT defaults are used.  The mechanism for defining source
10881 file naming conventions -- a package named @code{Naming} --
10882 is described below (@pxref{Naming Schemes}).
10883
10884 @node Source Language(s)
10885 @unnumberedsubsubsec Source Language(s)
10886
10887 @noindent
10888 Since the project files do not specify a @code{Languages} attribute, by
10889 default the GNAT tools assume that the language of the project file is Ada.
10890 More generally, a project can comprise source files
10891 in Ada, C, and/or other languages.
10892
10893 @node Using External Variables
10894 @subsection Using External Variables
10895
10896 @noindent
10897 Instead of supplying different project files for debug and release, we can
10898 define a single project file that queries an external variable (set either
10899 on the command line or via an ^environment variable^logical name^) in order to
10900 conditionally define the appropriate settings.  Again, assume that the
10901 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10902 located in directory @file{^/common^[COMMON]^}.  The following project file,
10903 @file{build.gpr}, queries the external variable named @code{STYLE} and
10904 defines an object directory and ^switch^switch^ settings based on whether
10905 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10906 the default is @code{"deb"}.
10907
10908 @smallexample @c projectfile
10909 @group
10910 project Build is
10911   for Main use ("proc");
10912
10913   type Style_Type is ("deb", "rel");
10914   Style : Style_Type := external ("STYLE", "deb");
10915
10916   case Style is
10917     when "deb" =>
10918       for Object_Dir use "debug";
10919
10920     when "rel" =>
10921       for Object_Dir use "release";
10922       for Exec_Dir use ".";
10923   end case;
10924 @end group
10925
10926 @group
10927   package Builder is
10928
10929     case Style is
10930       when "deb" =>
10931         for ^Default_Switches^Default_Switches^ ("Ada")
10932             use ("^-g^-g^");
10933         for Executable ("proc") use "proc1";
10934       when others =>
10935         null;
10936     end case;
10937
10938   end Builder;
10939 @end group
10940
10941 @group
10942   package Compiler is
10943
10944     case Style is
10945       when "deb" =>
10946         for ^Default_Switches^Default_Switches^ ("Ada")
10947             use ("^-gnata^-gnata^",
10948                  "^-gnato^-gnato^",
10949                  "^-gnatE^-gnatE^");
10950
10951       when "rel" =>
10952         for ^Default_Switches^Default_Switches^ ("Ada")
10953             use ("^-O2^-O2^");
10954     end case;
10955
10956   end Compiler;
10957
10958 end Build;
10959 @end group
10960 @end smallexample
10961
10962 @noindent
10963 @code{Style_Type} is an example of a @emph{string type}, which is the project
10964 file analog of an Ada enumeration type but whose components are string literals
10965 rather than identifiers.  @code{Style} is declared as a variable of this type.
10966
10967 The form @code{external("STYLE", "deb")} is known as an
10968 @emph{external reference}; its first argument is the name of an
10969 @emph{external variable}, and the second argument is a default value to be
10970 used if the external variable doesn't exist.  You can define an external
10971 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10972 or you can use ^an environment variable^a logical name^
10973 as an external variable.
10974
10975 Each @code{case} construct is expanded by the Project Manager based on the
10976 value of @code{Style}. Thus the command
10977 @ifclear vms
10978 @smallexample
10979 gnatmake -P/common/build.gpr -XSTYLE=deb
10980 @end smallexample
10981 @end ifclear
10982
10983 @ifset vms
10984 @smallexample
10985 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10986 @end smallexample
10987 @end ifset
10988
10989 @noindent
10990 is equivalent to the @command{gnatmake} invocation using the project file
10991 @file{debug.gpr} in the earlier example.  So is the command
10992 @smallexample
10993 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10994 @end smallexample
10995
10996 @noindent
10997 since @code{"deb"} is the default for @code{STYLE}.
10998
10999 Analogously,
11000
11001 @ifclear vms
11002 @smallexample
11003 gnatmake -P/common/build.gpr -XSTYLE=rel
11004 @end smallexample
11005 @end ifclear
11006
11007 @ifset vms
11008 @smallexample
11009 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11010 @end smallexample
11011 @end ifset
11012
11013 @noindent
11014 is equivalent to the @command{gnatmake} invocation using the project file
11015 @file{release.gpr} in the earlier example.
11016
11017 @node Importing Other Projects
11018 @subsection Importing Other Projects
11019 @cindex @code{ADA_PROJECT_PATH}
11020
11021 @noindent
11022 A compilation unit in a source file in one project may depend on compilation
11023 units in source files in other projects.  To compile this unit under
11024 control of a project file, the
11025 dependent project must @emph{import} the projects containing the needed source
11026 files.
11027 This effect is obtained using syntax similar to an Ada @code{with} clause,
11028 but where @code{with}ed entities are strings that denote project files.
11029
11030 As an example, suppose that the two projects @code{GUI_Proj} and
11031 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11032 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11033 and @file{^/comm^[COMM]^}, respectively.
11034 Suppose that the source files for @code{GUI_Proj} are
11035 @file{gui.ads} and @file{gui.adb}, and that the source files for
11036 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11037 files is located in its respective project file directory.  Schematically:
11038
11039 @smallexample
11040 @group
11041 ^/gui^[GUI]^
11042   gui_proj.gpr
11043   gui.ads
11044   gui.adb
11045 @end group
11046
11047 @group
11048 ^/comm^[COMM]^
11049   comm_proj.gpr
11050   comm.ads
11051   comm.adb
11052 @end group
11053 @end smallexample
11054
11055 @noindent
11056 We want to develop an application in directory @file{^/app^[APP]^} that
11057 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11058 the corresponding project files (e.g. the ^switch^switch^ settings
11059 and object directory).
11060 Skeletal code for a main procedure might be something like the following:
11061
11062 @smallexample @c ada
11063 @group
11064 with GUI, Comm;
11065 procedure App_Main is
11066    ...
11067 begin
11068    ...
11069 end App_Main;
11070 @end group
11071 @end smallexample
11072
11073 @noindent
11074 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11075 effect:
11076
11077 @smallexample @c projectfile
11078 @group
11079 with "/gui/gui_proj", "/comm/comm_proj";
11080 project App_Proj is
11081    for Main use ("app_main");
11082 end App_Proj;
11083 @end group
11084 @end smallexample
11085
11086 @noindent
11087 Building an executable is achieved through the command:
11088 @smallexample
11089 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11090 @end smallexample
11091 @noindent
11092 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11093 in the directory where @file{app_proj.gpr} resides.
11094
11095 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11096 (as illustrated above) the @code{with} clause can omit the extension.
11097
11098 Our example specified an absolute path for each imported project file.
11099 Alternatively, the directory name of an imported object can be omitted
11100 if either
11101 @itemize @bullet
11102 @item
11103 The imported project file is in the same directory as the importing project
11104 file, or
11105 @item
11106 You have defined ^an environment variable^a logical name^
11107 that includes the directory containing
11108 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11109 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11110 directory names separated by colons (semicolons on Windows).
11111 @end itemize
11112
11113 @noindent
11114 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11115 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11116 as follows:
11117
11118 @smallexample @c projectfile
11119 @group
11120 with "gui_proj", "comm_proj";
11121 project App_Proj is
11122    for Main use ("app_main");
11123 end App_Proj;
11124 @end group
11125 @end smallexample
11126
11127 @noindent
11128 Importing other projects can create ambiguities.
11129 For example, the same unit might be present in different imported projects, or
11130 it might be present in both the importing project and in an imported project.
11131 Both of these conditions are errors.  Note that in the current version of
11132 the Project Manager, it is illegal to have an ambiguous unit even if the
11133 unit is never referenced by the importing project.  This restriction may be
11134 relaxed in a future release.
11135
11136 @node Extending a Project
11137 @subsection Extending a Project
11138
11139 @noindent
11140 In large software systems it is common to have multiple
11141 implementations of a common interface; in Ada terms, multiple versions of a
11142 package body for the same specification.  For example, one implementation
11143 might be safe for use in tasking programs, while another might only be used
11144 in sequential applications.  This can be modeled in GNAT using the concept
11145 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11146 another project (the ``parent'') then by default all source files of the
11147 parent project are inherited by the child, but the child project can
11148 override any of the parent's source files with new versions, and can also
11149 add new files.  This facility is the project analog of a type extension in
11150 Object-Oriented Programming.  Project hierarchies are permitted (a child
11151 project may be the parent of yet another project), and a project that
11152 inherits one project can also import other projects.
11153
11154 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11155 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11156 @file{pack.adb}, and @file{proc.adb}:
11157
11158 @smallexample
11159 @group
11160 ^/seq^[SEQ]^
11161   pack.ads
11162   pack.adb
11163   proc.adb
11164   seq_proj.gpr
11165 @end group
11166 @end smallexample
11167
11168 @noindent
11169 Note that the project file can simply be empty (that is, no attribute or
11170 package is defined):
11171
11172 @smallexample @c projectfile
11173 @group
11174 project Seq_Proj is
11175 end Seq_Proj;
11176 @end group
11177 @end smallexample
11178
11179 @noindent
11180 implying that its source files are all the Ada source files in the project
11181 directory.
11182
11183 Suppose we want to supply an alternate version of @file{pack.adb}, in
11184 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11185 @file{pack.ads} and @file{proc.adb}.  We can define a project
11186 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11187
11188 @smallexample
11189 @group
11190 ^/tasking^[TASKING]^
11191   pack.adb
11192   tasking_proj.gpr
11193 @end group
11194
11195 @group
11196 project Tasking_Proj extends "/seq/seq_proj" is
11197 end Tasking_Proj;
11198 @end group
11199 @end smallexample
11200
11201 @noindent
11202 The version of @file{pack.adb} used in a build depends on which project file
11203 is specified.
11204
11205 Note that we could have obtained the desired behavior using project import
11206 rather than project inheritance; a @code{base} project would contain the
11207 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11208 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11209 would import @code{base} and add a different version of @file{pack.adb}.  The
11210 choice depends on whether other sources in the original project need to be
11211 overridden.  If they do, then project extension is necessary, otherwise,
11212 importing is sufficient.
11213
11214 @noindent
11215 In a project file that extends another project file, it is possible to
11216 indicate that an inherited source is not part of the sources of the extending
11217 project. This is necessary sometimes when a package spec has been overloaded
11218 and no longer requires a body: in this case, it is necessary to indicate that
11219 the inherited body is not part of the sources of the project, otherwise there
11220 will be a compilation error when compiling the spec.
11221
11222 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11223 Its value is a string list: a list of file names.
11224
11225 @smallexample @c @projectfile
11226 project B extends "a" is
11227    for Source_Files use ("pkg.ads");
11228    --  New spec of Pkg does not need a completion
11229    for Locally_Removed_Files use ("pkg.adb");
11230 end B;
11231 @end smallexample
11232
11233 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11234 is still needed: if it is possible to build using @command{gnatmake} when such
11235 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11236 it is possible to remove the source completely from a system that includes
11237 project P.
11238
11239 @c ***********************
11240 @c * Project File Syntax *
11241 @c ***********************
11242
11243 @node Project File Syntax
11244 @section Project File Syntax
11245
11246 @menu
11247 * Basic Syntax::
11248 * Packages::
11249 * Expressions::
11250 * String Types::
11251 * Variables::
11252 * Attributes::
11253 * Associative Array Attributes::
11254 * case Constructions::
11255 @end menu
11256
11257 @noindent
11258 This section describes the structure of project files.
11259
11260 A project may be an @emph{independent project}, entirely defined by a single
11261 project file. Any Ada source file in an independent project depends only
11262 on the predefined library and other Ada source files in the same project.
11263
11264 @noindent
11265 A project may also @dfn{depend on} other projects, in either or both of
11266 the following ways:
11267 @itemize @bullet
11268 @item It may import any number of projects
11269 @item It may extend at most one other project
11270 @end itemize
11271
11272 @noindent
11273 The dependence relation is a directed acyclic graph (the subgraph reflecting
11274 the ``extends'' relation is a tree).
11275
11276 A project's @dfn{immediate sources} are the source files directly defined by
11277 that project, either implicitly by residing in the project file's directory,
11278 or explicitly through any of the source-related attributes described below.
11279 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11280 of @var{proj} together with the immediate sources (unless overridden) of any
11281 project on which @var{proj} depends (either directly or indirectly).
11282
11283 @node Basic Syntax
11284 @subsection Basic Syntax
11285
11286 @noindent
11287 As seen in the earlier examples, project files have an Ada-like syntax.
11288 The minimal project file is:
11289 @smallexample @c projectfile
11290 @group
11291 project Empty is
11292
11293 end Empty;
11294 @end group
11295 @end smallexample
11296
11297 @noindent
11298 The identifier @code{Empty} is the name of the project.
11299 This project name must be present after the reserved
11300 word @code{end} at the end of the project file, followed by a semi-colon.
11301
11302 Any name in a project file, such as the project name or a variable name,
11303 has the same syntax as an Ada identifier.
11304
11305 The reserved words of project files are the Ada reserved words plus
11306 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11307 reserved words currently used in project file syntax are:
11308
11309 @itemize @bullet
11310 @item
11311 @code{case}
11312 @item
11313 @code{end}
11314 @item
11315 @code{for}
11316 @item
11317 @code{is}
11318 @item
11319 @code{others}
11320 @item
11321 @code{package}
11322 @item
11323 @code{renames}
11324 @item
11325 @code{type}
11326 @item
11327 @code{use}
11328 @item
11329 @code{when}
11330 @item
11331 @code{with}
11332 @end itemize
11333
11334 @noindent
11335 Comments in project files have the same syntax as in Ada, two consecutives
11336 hyphens through the end of the line.
11337
11338 @node Packages
11339 @subsection Packages
11340
11341 @noindent
11342 A project file may contain @emph{packages}. The name of a package must be one
11343 of the identifiers from the following list. A package
11344 with a given name may only appear once in a project file. Package names are
11345 case insensitive. The following package names are legal:
11346
11347 @itemize @bullet
11348 @item
11349 @code{Naming}
11350 @item
11351 @code{Builder}
11352 @item
11353 @code{Compiler}
11354 @item
11355 @code{Binder}
11356 @item
11357 @code{Linker}
11358 @item
11359 @code{Finder}
11360 @item
11361 @code{Cross_Reference}
11362 @item
11363 @code{Eliminate}
11364 @item
11365 @code{Pretty_Printer}
11366 @item
11367 @code{Metrics}
11368 @item
11369 @code{gnatls}
11370 @item
11371 @code{gnatstub}
11372 @item
11373 @code{IDE}
11374 @item
11375 @code{Language_Processing}
11376 @end itemize
11377
11378 @noindent
11379 In its simplest form, a package may be empty:
11380
11381 @smallexample @c projectfile
11382 @group
11383 project Simple is
11384   package Builder is
11385   end Builder;
11386 end Simple;
11387 @end group
11388 @end smallexample
11389
11390 @noindent
11391 A package may contain @emph{attribute declarations},
11392 @emph{variable declarations} and @emph{case constructions}, as will be
11393 described below.
11394
11395 When there is ambiguity between a project name and a package name,
11396 the name always designates the project. To avoid possible confusion, it is
11397 always a good idea to avoid naming a project with one of the
11398 names allowed for packages or any name that starts with @code{gnat}.
11399
11400 @node Expressions
11401 @subsection Expressions
11402
11403 @noindent
11404 An @emph{expression} is either a @emph{string expression} or a
11405 @emph{string list expression}.
11406
11407 A @emph{string expression} is either a @emph{simple string expression} or a
11408 @emph{compound string expression}.
11409
11410 A @emph{simple string expression} is one of the following:
11411 @itemize @bullet
11412 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11413 @item A string-valued variable reference (@pxref{Variables})
11414 @item A string-valued attribute reference (@pxref{Attributes})
11415 @item An external reference (@pxref{External References in Project Files})
11416 @end itemize
11417
11418 @noindent
11419 A @emph{compound string expression} is a concatenation of string expressions,
11420 using the operator @code{"&"}
11421 @smallexample
11422        Path & "/" & File_Name & ".ads"
11423 @end smallexample
11424
11425 @noindent
11426 A @emph{string list expression} is either a
11427 @emph{simple string list expression} or a
11428 @emph{compound string list expression}.
11429
11430 A @emph{simple string list expression} is one of the following:
11431 @itemize @bullet
11432 @item A parenthesized list of zero or more string expressions,
11433 separated by commas
11434 @smallexample
11435    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11436    Empty_List := ();
11437 @end smallexample
11438 @item A string list-valued variable reference
11439 @item A string list-valued attribute reference
11440 @end itemize
11441
11442 @noindent
11443 A @emph{compound string list expression} is the concatenation (using
11444 @code{"&"}) of a simple string list expression and an expression.  Note that
11445 each term in a compound string list expression, except the first, may be
11446 either a string expression or a string list expression.
11447
11448 @smallexample @c projectfile
11449 @group
11450    File_Name_List := () & File_Name; --  One string in this list
11451    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11452    --  Two strings
11453    Big_List := File_Name_List & Extended_File_Name_List;
11454    --  Concatenation of two string lists: three strings
11455    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11456    --  Illegal: must start with a string list
11457 @end group
11458 @end smallexample
11459
11460 @node String Types
11461 @subsection String Types
11462
11463 @noindent
11464 A @emph{string type declaration} introduces a discrete set of string literals.
11465 If a string variable is declared to have this type, its value
11466 is restricted to the given set of literals.
11467
11468 Here is an example of a string type declaration:
11469
11470 @smallexample @c projectfile
11471    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11472 @end smallexample
11473
11474 @noindent
11475 Variables of a string type are called @emph{typed variables}; all other
11476 variables are called @emph{untyped variables}. Typed variables are
11477 particularly useful in @code{case} constructions, to support conditional
11478 attribute declarations.
11479 (@pxref{case Constructions}).
11480
11481 The string literals in the list are case sensitive and must all be different.
11482 They may include any graphic characters allowed in Ada, including spaces.
11483
11484 A string type may only be declared at the project level, not inside a package.
11485
11486 A string type may be referenced by its name if it has been declared in the same
11487 project file, or by an expanded name whose prefix is the name of the project
11488 in which it is declared.
11489
11490 @node Variables
11491 @subsection Variables
11492
11493 @noindent
11494 A variable may be declared at the project file level, or within a package.
11495 Here are some examples of variable declarations:
11496
11497 @smallexample @c projectfile
11498 @group
11499    This_OS : OS := external ("OS"); --  a typed variable declaration
11500    That_OS := "GNU/Linux";          --  an untyped variable declaration
11501 @end group
11502 @end smallexample
11503
11504 @noindent
11505 The syntax of a @emph{typed variable declaration} is identical to the Ada
11506 syntax for an object declaration. By contrast, the syntax of an untyped
11507 variable declaration is identical to an Ada assignment statement. In fact,
11508 variable declarations in project files have some of the characteristics of
11509 an assignment, in that successive declarations for the same variable are
11510 allowed. Untyped variable declarations do establish the expected kind of the
11511 variable (string or string list), and successive declarations for it must
11512 respect the initial kind.
11513
11514 @noindent
11515 A string variable declaration (typed or untyped) declares a variable
11516 whose value is a string. This variable may be used as a string expression.
11517 @smallexample @c projectfile
11518    File_Name       := "readme.txt";
11519    Saved_File_Name := File_Name & ".saved";
11520 @end smallexample
11521
11522 @noindent
11523 A string list variable declaration declares a variable whose value is a list
11524 of strings. The list may contain any number (zero or more) of strings.
11525
11526 @smallexample @c projectfile
11527    Empty_List := ();
11528    List_With_One_Element := ("^-gnaty^-gnaty^");
11529    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11530    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11531                  "pack2.ada", "util_.ada", "util.ada");
11532 @end smallexample
11533
11534 @noindent
11535 The same typed variable may not be declared more than once at project level,
11536 and it may not be declared more than once in any package; it is in effect
11537 a constant.
11538
11539 The same untyped variable may be declared several times. Declarations are
11540 elaborated in the order in which they appear, so  the new value replaces
11541 the old one, and any subsequent reference to the variable uses the new value.
11542 However, as noted above, if a variable has been declared as a string, all
11543 subsequent
11544 declarations must give it a string value. Similarly, if a variable has
11545 been declared as a string list, all subsequent declarations
11546 must give it a string list value.
11547
11548 A @emph{variable reference} may take several forms:
11549
11550 @itemize @bullet
11551 @item The simple variable name, for a variable in the current package (if any)
11552 or in the current project
11553 @item An expanded name, whose prefix is a context name.
11554 @end itemize
11555
11556 @noindent
11557 A @emph{context} may be one of the following:
11558
11559 @itemize @bullet
11560 @item The name of an existing package in the current project
11561 @item The name of an imported project of the current project
11562 @item The name of an ancestor project (i.e., a project extended by the current
11563 project, either directly or indirectly)
11564 @item An expanded name whose prefix is an imported/parent project name, and
11565 whose selector is a package name in that project.
11566 @end itemize
11567
11568 @noindent
11569 A variable reference may be used in an expression.
11570
11571 @node Attributes
11572 @subsection Attributes
11573
11574 @noindent
11575 A project (and its packages) may have @emph{attributes} that define
11576 the project's properties.  Some attributes have values that are strings;
11577 others have values that are string lists.
11578
11579 There are two categories of attributes: @emph{simple attributes}
11580 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11581
11582 Legal project attribute names, and attribute names for each legal package are
11583 listed below. Attributes names are case-insensitive.
11584
11585 The following attributes are defined on projects (all are simple attributes):
11586
11587 @multitable @columnfractions .4 .3
11588 @item @emph{Attribute Name}
11589 @tab @emph{Value}
11590 @item @code{Source_Files}
11591 @tab string list
11592 @item @code{Source_Dirs}
11593 @tab string list
11594 @item @code{Source_List_File}
11595 @tab string
11596 @item @code{Object_Dir}
11597 @tab string
11598 @item @code{Exec_Dir}
11599 @tab string
11600 @item @code{Locally_Removed_Files}
11601 @tab string list
11602 @item @code{Main}
11603 @tab string list
11604 @item @code{Languages}
11605 @tab string list
11606 @item @code{Main_Language}
11607 @tab string
11608 @item @code{Library_Dir}
11609 @tab string
11610 @item @code{Library_Name}
11611 @tab string
11612 @item @code{Library_Kind}
11613 @tab string
11614 @item @code{Library_Version}
11615 @tab string
11616 @item @code{Library_Interface}
11617 @tab string
11618 @item @code{Library_Auto_Init}
11619 @tab string
11620 @item @code{Library_Options}
11621 @tab string list
11622 @item @code{Library_GCC}
11623 @tab string
11624 @end multitable
11625
11626 @noindent
11627 The following attributes are defined for package  @code{Naming}
11628 (@pxref{Naming Schemes}):
11629
11630 @multitable @columnfractions .4 .2 .2 .2
11631 @item Attribute Name @tab Category @tab Index @tab Value
11632 @item @code{Spec_Suffix}
11633 @tab associative array
11634 @tab language name
11635 @tab string
11636 @item @code{Body_Suffix}
11637 @tab associative array
11638 @tab language name
11639 @tab string
11640 @item @code{Separate_Suffix}
11641 @tab simple attribute
11642 @tab n/a
11643 @tab string
11644 @item @code{Casing}
11645 @tab simple attribute
11646 @tab n/a
11647 @tab string
11648 @item @code{Dot_Replacement}
11649 @tab simple attribute
11650 @tab n/a
11651 @tab string
11652 @item @code{Spec}
11653 @tab associative array
11654 @tab Ada unit name
11655 @tab string
11656 @item @code{Body}
11657 @tab associative array
11658 @tab Ada unit name
11659 @tab string
11660 @item @code{Specification_Exceptions}
11661 @tab associative array
11662 @tab language name
11663 @tab string list
11664 @item @code{Implementation_Exceptions}
11665 @tab associative array
11666 @tab language name
11667 @tab string list
11668 @end multitable
11669
11670 @noindent
11671 The following attributes are defined for packages @code{Builder},
11672 @code{Compiler}, @code{Binder},
11673 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11674 (@pxref{^Switches^Switches^ and Project Files}).
11675
11676 @multitable @columnfractions .4 .2 .2 .2
11677 @item Attribute Name @tab Category @tab Index @tab Value
11678 @item @code{^Default_Switches^Default_Switches^}
11679 @tab associative array
11680 @tab language name
11681 @tab string list
11682 @item @code{^Switches^Switches^}
11683 @tab associative array
11684 @tab file name
11685 @tab string list
11686 @end multitable
11687
11688 @noindent
11689 In addition, package @code{Compiler} has a single string attribute
11690 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11691 string attribute @code{Global_Configuration_Pragmas}.
11692
11693 @noindent
11694 Each simple attribute has a default value: the empty string (for string-valued
11695 attributes) and the empty list (for string list-valued attributes).
11696
11697 An attribute declaration defines a new value for an attribute.
11698
11699 Examples of simple attribute declarations:
11700
11701 @smallexample @c projectfile
11702    for Object_Dir use "objects";
11703    for Source_Dirs use ("units", "test/drivers");
11704 @end smallexample
11705
11706 @noindent
11707 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11708 attribute definition clause in Ada.
11709
11710 Attributes references may be appear in expressions.
11711 The general form for such a reference is @code{<entity>'<attribute>}:
11712 Associative array attributes are functions. Associative
11713 array attribute references must have an argument that is a string literal.
11714
11715 Examples are:
11716
11717 @smallexample @c projectfile
11718   project'Object_Dir
11719   Naming'Dot_Replacement
11720   Imported_Project'Source_Dirs
11721   Imported_Project.Naming'Casing
11722   Builder'^Default_Switches^Default_Switches^("Ada")
11723 @end smallexample
11724
11725 @noindent
11726 The prefix of an attribute may be:
11727 @itemize @bullet
11728 @item @code{project} for an attribute of the current project
11729 @item The name of an existing package of the current project
11730 @item The name of an imported project
11731 @item The name of a parent project that is extended by the current project
11732 @item An expanded name whose prefix is imported/parent project name,
11733       and whose selector is a package name
11734 @end itemize
11735
11736 @noindent
11737 Example:
11738 @smallexample @c projectfile
11739 @group
11740    project Prj is
11741      for Source_Dirs use project'Source_Dirs & "units";
11742      for Source_Dirs use project'Source_Dirs & "test/drivers"
11743    end Prj;
11744 @end group
11745 @end smallexample
11746
11747 @noindent
11748 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11749 has the default value: an empty string list. After this declaration,
11750 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11751 After the second attribute declaration @code{Source_Dirs} is a string list of
11752 two elements: @code{"units"} and @code{"test/drivers"}.
11753
11754 Note: this example is for illustration only. In practice,
11755 the project file would contain only one attribute declaration:
11756
11757 @smallexample @c projectfile
11758    for Source_Dirs use ("units", "test/drivers");
11759 @end smallexample
11760
11761 @node Associative Array Attributes
11762 @subsection Associative Array Attributes
11763
11764 @noindent
11765 Some attributes are defined as @emph{associative arrays}. An associative
11766 array may be regarded as a function that takes a string as a parameter
11767 and delivers a string or string list value as its result.
11768
11769 Here are some examples of single associative array attribute associations:
11770
11771 @smallexample @c projectfile
11772    for Body ("main") use "Main.ada";
11773    for ^Switches^Switches^ ("main.ada")
11774        use ("^-v^-v^",
11775             "^-gnatv^-gnatv^");
11776    for ^Switches^Switches^ ("main.ada")
11777             use Builder'^Switches^Switches^ ("main.ada")
11778               & "^-g^-g^";
11779 @end smallexample
11780
11781 @noindent
11782 Like untyped variables and simple attributes, associative array attributes
11783 may be declared several times. Each declaration supplies a new value for the
11784 attribute, and replaces the previous setting.
11785
11786 @noindent
11787 An associative array attribute may be declared as a full associative array
11788 declaration, with the value of the same attribute in an imported or extended
11789 project.
11790
11791 @smallexample @c projectfile
11792    package Builder is
11793       for Default_Switches use Default.Builder'Default_Switches;
11794    end Builder;
11795 @end smallexample
11796
11797 @noindent
11798 In this example, @code{Default} must be either an project imported by the
11799 current project, or the project that the current project extends. If the
11800 attribute is in a package (in this case, in package @code{Builder}), the same
11801 package needs to be specified.
11802
11803 @noindent
11804 A full associative array declaration replaces any other declaration for the
11805 attribute, including other full associative array declaration. Single
11806 associative array associations may be declare after a full associative
11807 declaration, modifying the value for a single association of the attribute.
11808
11809 @node case Constructions
11810 @subsection @code{case} Constructions
11811
11812 @noindent
11813 A @code{case} construction is used in a project file to effect conditional
11814 behavior.
11815 Here is a typical example:
11816
11817 @smallexample @c projectfile
11818 @group
11819 project MyProj is
11820    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11821
11822    OS : OS_Type := external ("OS", "GNU/Linux");
11823 @end group
11824
11825 @group
11826    package Compiler is
11827      case OS is
11828        when "GNU/Linux" | "Unix" =>
11829          for ^Default_Switches^Default_Switches^ ("Ada")
11830              use ("^-gnath^-gnath^");
11831        when "NT" =>
11832          for ^Default_Switches^Default_Switches^ ("Ada")
11833              use ("^-gnatP^-gnatP^");
11834        when others =>
11835      end case;
11836    end Compiler;
11837 end MyProj;
11838 @end group
11839 @end smallexample
11840
11841 @noindent
11842 The syntax of a @code{case} construction is based on the Ada case statement
11843 (although there is no @code{null} construction for empty alternatives).
11844
11845 The case expression must a typed string variable.
11846 Each alternative comprises the reserved word @code{when}, either a list of
11847 literal strings separated by the @code{"|"} character or the reserved word
11848 @code{others},  and the @code{"=>"} token.
11849 Each literal string must belong to the string type that is the type of the
11850 case variable.
11851 An @code{others} alternative, if present, must occur last.
11852
11853 After each @code{=>}, there are zero or more constructions.  The only
11854 constructions allowed in a case construction are other case constructions and
11855 attribute declarations. String type declarations, variable declarations and
11856 package declarations are not allowed.
11857
11858 The value of the case variable is often given by an external reference
11859 (@pxref{External References in Project Files}).
11860
11861 @c ****************************************
11862 @c * Objects and Sources in Project Files *
11863 @c ****************************************
11864
11865 @node Objects and Sources in Project Files
11866 @section Objects and Sources in Project Files
11867
11868 @menu
11869 * Object Directory::
11870 * Exec Directory::
11871 * Source Directories::
11872 * Source File Names::
11873 @end menu
11874
11875 @noindent
11876 Each project has exactly one object directory and one or more source
11877 directories. The source directories must contain at least one source file,
11878 unless  the project file explicitly specifies that no source files are present
11879 (@pxref{Source File Names}).
11880
11881 @node Object Directory
11882 @subsection Object Directory
11883
11884 @noindent
11885 The object directory for a project is the directory containing the compiler's
11886 output (such as @file{ALI} files and object files) for the project's immediate
11887 sources.
11888
11889 The object directory is given by the value of the attribute @code{Object_Dir}
11890 in the project file.
11891
11892 @smallexample @c projectfile
11893    for Object_Dir use "objects";
11894 @end smallexample
11895
11896 @noindent
11897 The attribute @var{Object_Dir} has a string value, the path name of the object
11898 directory. The path name may be absolute or relative to the directory of the
11899 project file. This directory must already exist, and be readable and writable.
11900
11901 By default, when the attribute @code{Object_Dir} is not given an explicit value
11902 or when its value is the empty string, the object directory is the same as the
11903 directory containing the project file.
11904
11905 @node Exec Directory
11906 @subsection Exec Directory
11907
11908 @noindent
11909 The exec directory for a project is the directory containing the executables
11910 for the project's main subprograms.
11911
11912 The exec directory is given by the value of the attribute @code{Exec_Dir}
11913 in the project file.
11914
11915 @smallexample @c projectfile
11916    for Exec_Dir use "executables";
11917 @end smallexample
11918
11919 @noindent
11920 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11921 directory. The path name may be absolute or relative to the directory of the
11922 project file. This directory must already exist, and be writable.
11923
11924 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11925 or when its value is the empty string, the exec directory is the same as the
11926 object directory of the project file.
11927
11928 @node Source Directories
11929 @subsection Source Directories
11930
11931 @noindent
11932 The source directories of a project are specified by the project file
11933 attribute @code{Source_Dirs}.
11934
11935 This attribute's value is a string list. If the attribute is not given an
11936 explicit value, then there is only one source directory, the one where the
11937 project file resides.
11938
11939 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11940 as in
11941
11942 @smallexample @c projectfile
11943     for Source_Dirs use ();
11944 @end smallexample
11945
11946 @noindent
11947 indicates that the project contains no source files.
11948
11949 Otherwise, each string in the string list designates one or more
11950 source directories.
11951
11952 @smallexample @c projectfile
11953    for Source_Dirs use ("sources", "test/drivers");
11954 @end smallexample
11955
11956 @noindent
11957 If a string in the list ends with @code{"/**"},  then the directory whose path
11958 name precedes the two asterisks, as well as all its subdirectories
11959 (recursively), are source directories.
11960
11961 @smallexample @c projectfile
11962    for Source_Dirs use ("/system/sources/**");
11963 @end smallexample
11964
11965 @noindent
11966 Here the directory @code{/system/sources} and all of its subdirectories
11967 (recursively) are source directories.
11968
11969 To specify that the source directories are the directory of the project file
11970 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11971 @smallexample @c projectfile
11972    for Source_Dirs use ("./**");
11973 @end smallexample
11974
11975 @noindent
11976 Each of the source directories must exist and be readable.
11977
11978 @node Source File Names
11979 @subsection Source File Names
11980
11981 @noindent
11982 In a project that contains source files, their names may be specified by the
11983 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11984 (a string). Source file names never include any directory information.
11985
11986 If the attribute @code{Source_Files} is given an explicit value, then each
11987 element of the list is a source file name.
11988
11989 @smallexample @c projectfile
11990    for Source_Files use ("main.adb");
11991    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11992 @end smallexample
11993
11994 @noindent
11995 If the attribute @code{Source_Files} is not given an explicit value,
11996 but the attribute @code{Source_List_File} is given a string value,
11997 then the source file names are contained in the text file whose path name
11998 (absolute or relative to the directory of the project file) is the
11999 value of the attribute @code{Source_List_File}.
12000
12001 Each line in the file that is not empty or is not a comment
12002 contains a source file name.
12003
12004 @smallexample @c projectfile
12005    for Source_List_File use "source_list.txt";
12006 @end smallexample
12007
12008 @noindent
12009 By default, if neither the attribute @code{Source_Files} nor the attribute
12010 @code{Source_List_File} is given an explicit value, then each file in the
12011 source directories that conforms to the project's naming scheme
12012 (@pxref{Naming Schemes}) is an immediate source of the project.
12013
12014 A warning is issued if both attributes @code{Source_Files} and
12015 @code{Source_List_File} are given explicit values. In this case, the attribute
12016 @code{Source_Files} prevails.
12017
12018 Each source file name must be the name of one existing source file
12019 in one of the source directories.
12020
12021 A @code{Source_Files} attribute whose value is an empty list
12022 indicates that there are no source files in the project.
12023
12024 If the order of the source directories is known statically, that is if
12025 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12026 be several files with the same source file name. In this case, only the file
12027 in the first directory is considered as an immediate source of the project
12028 file. If the order of the source directories is not known statically, it is
12029 an error to have several files with the same source file name.
12030
12031 Projects can be specified to have no Ada source
12032 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12033 list, or the @code{"Ada"} may be absent from @code{Languages}:
12034
12035 @smallexample @c projectfile
12036    for Source_Dirs use ();
12037    for Source_Files use ();
12038    for Languages use ("C", "C++");
12039 @end smallexample
12040
12041 @noindent
12042 Otherwise, a project must contain at least one immediate source.
12043
12044 Projects with no source files are useful as template packages
12045 (@pxref{Packages in Project Files}) for other projects; in particular to
12046 define a package @code{Naming} (@pxref{Naming Schemes}).
12047
12048 @c ****************************
12049 @c * Importing Projects *
12050 @c ****************************
12051
12052 @node  Importing Projects
12053 @section Importing Projects
12054 @cindex @code{ADA_PROJECT_PATH}
12055
12056 @noindent
12057 An immediate source of a project P may depend on source files that
12058 are neither immediate sources of P nor in the predefined library.
12059 To get this effect, P must @emph{import} the projects that contain the needed
12060 source files.
12061
12062 @smallexample @c projectfile
12063 @group
12064   with "project1", "utilities.gpr";
12065   with "/namings/apex.gpr";
12066   project Main is
12067     ...
12068 @end group
12069 @end smallexample
12070
12071 @noindent
12072 As can be seen in this example, the syntax for importing projects is similar
12073 to the syntax for importing compilation units in Ada. However, project files
12074 use literal strings instead of names, and the @code{with} clause identifies
12075 project files rather than packages.
12076
12077 Each literal string is the file name or path name (absolute or relative) of a
12078 project file. If a string corresponds to a file name, with no path or a
12079 relative path, then its location is determined by the @emph{project path}. The
12080 latter can be queried using @code{gnatls -v}. It contains:
12081
12082 @itemize @bullet
12083 @item
12084 In first position, the directory containing the current project file.
12085 @item
12086 In last position, the default project directory. This default project directory
12087 is part of the GNAT installation and is the standard place to install project
12088 files giving access to standard support libraries.
12089 @ifclear vms
12090 @ref{Installing a library}
12091 @end ifclear
12092
12093 @item
12094 In between, all the directories referenced in the
12095 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12096 @end itemize
12097
12098 @noindent
12099 If a relative pathname is used, as in
12100
12101 @smallexample @c projectfile
12102   with "tests/proj";
12103 @end smallexample
12104
12105 @noindent
12106 then the full path for the project is constructed by concatenating this
12107 relative path to those in the project path, in order, until a matching file is
12108 found. Any symbolic link will be fully resolved in the directory of the
12109 importing project file before the imported project file is examined.
12110
12111 If the @code{with}'ed project file name does not have an extension,
12112 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12113 then the file name as specified in the @code{with} clause (no extension) will
12114 be used. In the above example, if a file @code{project1.gpr} is found, then it
12115 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12116 then it will be used; if neither file exists, this is an error.
12117
12118 A warning is issued if the name of the project file does not match the
12119 name of the project; this check is case insensitive.
12120
12121 Any source file that is an immediate source of the imported project can be
12122 used by the immediate sources of the importing project, transitively. Thus
12123 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12124 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12125 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12126 because if and when @code{B} ceases to import @code{C}, some sources in
12127 @code{A} will no longer compile.
12128
12129 A side effect of this capability is that normally cyclic dependencies are not
12130 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12131 is not allowed to import @code{A}. However, there are cases when cyclic
12132 dependencies would be beneficial. For these cases, another form of import
12133 between projects exists, the @code{limited with}: a project @code{A} that
12134 imports a project @code{B} with a straigh @code{with} may also be imported,
12135 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12136 to @code{A} include at least one @code{limited with}.
12137
12138 @smallexample @c 0projectfile
12139 with "../b/b.gpr";
12140 with "../c/c.gpr";
12141 project A is
12142 end A;
12143
12144 limited with "../a/a.gpr";
12145 project B is
12146 end B;
12147
12148 with "../d/d.gpr";
12149 project C is
12150 end C;
12151
12152 limited with "../a/a.gpr";
12153 project D is
12154 end D;
12155 @end smallexample
12156
12157 @noindent
12158 In the above legal example, there are two project cycles:
12159 @itemize @bullet
12160 @item A-> B-> A
12161 @item A -> C -> D -> A
12162 @end itemize
12163
12164 @noindent
12165 In each of these cycle there is one @code{limited with}: import of @code{A}
12166 from @code{B} and import of @code{A} from @code{D}.
12167
12168 The difference between straight @code{with} and @code{limited with} is that
12169 the name of a project imported with a @code{limited with} cannot be used in the
12170 project that imports it. In particular, its packages cannot be renamed and
12171 its variables cannot be referred to.
12172
12173 An exception to the above rules for @code{limited with} is that for the main
12174 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12175 @code{limited with} is equivalent to a straight @code{with}. For example,
12176 in the example above, projects @code{B} and @code{D} could not be main
12177 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12178 each have a @code{limited with} that is the only one in a cycle of importing
12179 projects.
12180
12181 @c *********************
12182 @c * Project Extension *
12183 @c *********************
12184
12185 @node Project Extension
12186 @section Project Extension
12187
12188 @noindent
12189 During development of a large system, it is sometimes necessary to use
12190 modified versions of some of the source files, without changing the original
12191 sources. This can be achieved through the @emph{project extension} facility.
12192
12193 @smallexample @c projectfile
12194    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12195 @end smallexample
12196
12197 @noindent
12198 A project extension declaration introduces an extending project
12199 (the @emph{child}) and a project being extended (the @emph{parent}).
12200
12201 By default, a child project inherits all the sources of its parent.
12202 However, inherited sources can be overridden: a unit in a parent is hidden
12203 by a unit of the same name in the child.
12204
12205 Inherited sources are considered to be sources (but not immediate sources)
12206 of the child project; see @ref{Project File Syntax}.
12207
12208 An inherited source file retains any switches specified in the parent project.
12209
12210 For example if the project @code{Utilities} contains the specification and the
12211 body of an Ada package @code{Util_IO}, then the project
12212 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12213 The original body of @code{Util_IO} will not be considered in program builds.
12214 However, the package specification will still be found in the project
12215 @code{Utilities}.
12216
12217 A child project can have only one parent but it may import any number of other
12218 projects.
12219
12220 A project is not allowed to import directly or indirectly at the same time a
12221 child project and any of its ancestors.
12222
12223 @c *******************************
12224 @c * Project Hierarchy Extension *
12225 @c *******************************
12226
12227 @node Project Hierarchy Extension
12228 @section Project Hierarchy Extension
12229
12230 @noindent
12231 When extending a large system spanning multiple projects, it is often
12232 inconvenient to extend every project in the hierarchy that is impacted by a
12233 small change introduced. In such cases, it is possible to create a virtual
12234 extension of entire hierarchy using @code{extends all} relationship.
12235
12236 When the project is extended using @code{extends all} inheritance, all projects
12237 that are imported by it, both directly and indirectly, are considered virtually
12238 extended. That is, the Project Manager creates "virtual projects"
12239 that extend every project in the hierarchy; all these virtual projects have
12240 no sources of their own and have as object directory the object directory of
12241 the root of "extending all" project.
12242
12243 It is possible to explicitly extend one or more projects in the hierarchy
12244 in order to modify the sources. These extending projects must be imported by
12245 the "extending all" project, which will replace the corresponding virtual
12246 projects with the explicit ones.
12247
12248 When building such a project hierarchy extension, the Project Manager will
12249 ensure that both modified sources and sources in virtual extending projects
12250 that depend on them, are recompiled.
12251
12252 By means of example, consider the following hierarchy of projects.
12253
12254 @enumerate
12255 @item
12256 project A, containing package P1
12257 @item
12258 project B importing A and containing package P2 which depends on P1
12259 @item
12260 project C importing B and containing package P3 which depends on P2
12261 @end enumerate
12262
12263 @noindent
12264 We want to modify packages P1 and P3.
12265
12266 This project hierarchy will need to be extended as follows:
12267
12268 @enumerate
12269 @item
12270 Create project A1 that extends A, placing modified P1 there:
12271
12272 @smallexample @c 0projectfile
12273 project A1 extends "(...)/A" is
12274 end A1;
12275 @end smallexample
12276
12277 @item
12278 Create project C1 that "extends all" C and imports A1, placing modified
12279 P3 there:
12280
12281 @smallexample @c 0projectfile
12282 with "(...)/A1";
12283 project C1 extends all "(...)/C" is
12284 end C1;
12285 @end smallexample
12286 @end enumerate
12287
12288 When you build project C1, your entire modified project space will be
12289 recompiled, including the virtual project B1 that has been impacted by the
12290 "extending all" inheritance of project C.
12291
12292 Note that if a Library Project in the hierarchy is virtually extended,
12293 the virtual project that extends the Library Project is not a Library Project.
12294
12295 @c ****************************************
12296 @c * External References in Project Files *
12297 @c ****************************************
12298
12299 @node  External References in Project Files
12300 @section External References in Project Files
12301
12302 @noindent
12303 A project file may contain references to external variables; such references
12304 are called @emph{external references}.
12305
12306 An external variable is either defined as part of the environment (an
12307 environment variable in Unix, for example) or else specified on the command
12308 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12309 If both, then the command line value is used.
12310
12311 The value of an external reference is obtained by means of the built-in
12312 function @code{external}, which returns a string value.
12313 This function has two forms:
12314 @itemize @bullet
12315 @item @code{external (external_variable_name)}
12316 @item @code{external (external_variable_name, default_value)}
12317 @end itemize
12318
12319 @noindent
12320 Each parameter must be a string literal.  For example:
12321
12322 @smallexample @c projectfile
12323    external ("USER")
12324    external ("OS", "GNU/Linux")
12325 @end smallexample
12326
12327 @noindent
12328 In the form with one parameter, the function returns the value of
12329 the external variable given as parameter. If this name is not present in the
12330 environment, the function returns an empty string.
12331
12332 In the form with two string parameters, the second argument is
12333 the value returned when the variable given as the first argument is not
12334 present in the environment. In the example above, if @code{"OS"} is not
12335 the name of ^an environment variable^a logical name^ and is not passed on
12336 the command line, then the returned value is @code{"GNU/Linux"}.
12337
12338 An external reference may be part of a string expression or of a string
12339 list expression, and can therefore appear in a variable declaration or
12340 an attribute declaration.
12341
12342 @smallexample @c projectfile
12343 @group
12344    type Mode_Type is ("Debug", "Release");
12345    Mode : Mode_Type := external ("MODE");
12346    case Mode is
12347      when "Debug" =>
12348         ...
12349 @end group
12350 @end smallexample
12351
12352 @c *****************************
12353 @c * Packages in Project Files *
12354 @c *****************************
12355
12356 @node  Packages in Project Files
12357 @section Packages in Project Files
12358
12359 @noindent
12360 A @emph{package} defines the settings for project-aware tools within a
12361 project.
12362 For each such tool one can declare a package; the names for these
12363 packages are preset (@pxref{Packages}).
12364 A package may contain variable declarations, attribute declarations, and case
12365 constructions.
12366
12367 @smallexample @c projectfile
12368 @group
12369    project Proj is
12370       package Builder is  -- used by gnatmake
12371          for ^Default_Switches^Default_Switches^ ("Ada")
12372              use ("^-v^-v^",
12373                   "^-g^-g^");
12374       end Builder;
12375    end Proj;
12376 @end group
12377 @end smallexample
12378
12379 @noindent
12380 The syntax of package declarations mimics that of package in Ada.
12381
12382 Most of the packages have an attribute
12383 @code{^Default_Switches^Default_Switches^}.
12384 This attribute is an associative array, and its value is a string list.
12385 The index of the associative array is the name of a programming language (case
12386 insensitive). This attribute indicates the ^switch^switch^
12387 or ^switches^switches^ to be used
12388 with the corresponding tool.
12389
12390 Some packages also have another attribute, @code{^Switches^Switches^},
12391 an associative array whose value is a string list.
12392 The index is the name of a source file.
12393 This attribute indicates the ^switch^switch^
12394 or ^switches^switches^ to be used by the corresponding
12395 tool when dealing with this specific file.
12396
12397 Further information on these ^switch^switch^-related attributes is found in
12398 @ref{^Switches^Switches^ and Project Files}.
12399
12400 A package may be declared as a @emph{renaming} of another package; e.g., from
12401 the project file for an imported project.
12402
12403 @smallexample @c projectfile
12404 @group
12405   with "/global/apex.gpr";
12406   project Example is
12407     package Naming renames Apex.Naming;
12408     ...
12409   end Example;
12410 @end group
12411 @end smallexample
12412
12413 @noindent
12414 Packages that are renamed in other project files often come from project files
12415 that have no sources: they are just used as templates. Any modification in the
12416 template will be reflected automatically in all the project files that rename
12417 a package from the template.
12418
12419 In addition to the tool-oriented packages, you can also declare a package
12420 named @code{Naming} to establish specialized source file naming conventions
12421 (@pxref{Naming Schemes}).
12422
12423 @c ************************************
12424 @c * Variables from Imported Projects *
12425 @c ************************************
12426
12427 @node Variables from Imported Projects
12428 @section Variables from Imported Projects
12429
12430 @noindent
12431 An attribute or variable defined in an imported or parent project can
12432 be used in expressions in the importing / extending project.
12433 Such an attribute or variable is denoted by an expanded name whose prefix
12434 is either the name of the project or the expanded name of a package within
12435 a project.
12436
12437 @smallexample @c projectfile
12438 @group
12439   with "imported";
12440   project Main extends "base" is
12441      Var1 := Imported.Var;
12442      Var2 := Base.Var & ".new";
12443 @end group
12444
12445 @group
12446      package Builder is
12447         for ^Default_Switches^Default_Switches^ ("Ada")
12448             use Imported.Builder.Ada_^Switches^Switches^ &
12449                 "^-gnatg^-gnatg^" &
12450                 "^-v^-v^";
12451      end Builder;
12452 @end group
12453
12454 @group
12455      package Compiler is
12456         for ^Default_Switches^Default_Switches^ ("Ada")
12457             use Base.Compiler.Ada_^Switches^Switches^;
12458      end Compiler;
12459   end Main;
12460 @end group
12461 @end smallexample
12462
12463 @noindent
12464 In this example:
12465
12466 @itemize @bullet
12467 @item
12468 The value of @code{Var1} is a copy of the variable @code{Var} defined
12469 in the project file @file{"imported.gpr"}
12470 @item
12471 the value of @code{Var2} is a copy of the value of variable @code{Var}
12472 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12473 @item
12474 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12475 @code{Builder} is a string list that includes in its value a copy of the value
12476 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12477 in project file @file{imported.gpr} plus two new elements:
12478 @option{"^-gnatg^-gnatg^"}
12479 and @option{"^-v^-v^"};
12480 @item
12481 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12482 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12483 defined in the @code{Compiler} package in project file @file{base.gpr},
12484 the project being extended.
12485 @end itemize
12486
12487 @c ******************
12488 @c * Naming Schemes *
12489 @c ******************
12490
12491 @node  Naming Schemes
12492 @section Naming Schemes
12493
12494 @noindent
12495 Sometimes an Ada software system is ported from a foreign compilation
12496 environment to GNAT, and the file names do not use the default GNAT
12497 conventions. Instead of changing all the file names (which for a variety
12498 of reasons might not be possible), you can define the relevant file
12499 naming scheme in the @code{Naming} package in your project file.
12500
12501 @noindent
12502 Note that the use of pragmas described in
12503 @ref{Alternative File Naming Schemes} by mean of a configuration
12504 pragmas file is not supported when using project files. You must use
12505 the features described in this paragraph. You can however use specify
12506 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12507
12508 @ifclear vms
12509 For example, the following
12510 package models the Apex file naming rules:
12511
12512 @smallexample @c projectfile
12513 @group
12514   package Naming is
12515     for Casing               use "lowercase";
12516     for Dot_Replacement      use ".";
12517     for Spec_Suffix ("Ada")  use ".1.ada";
12518     for Body_Suffix ("Ada")  use ".2.ada";
12519   end Naming;
12520 @end group
12521 @end smallexample
12522 @end ifclear
12523
12524 @ifset vms
12525 For example, the following package models the DEC Ada file naming rules:
12526
12527 @smallexample @c projectfile
12528 @group
12529   package Naming is
12530     for Casing               use "lowercase";
12531     for Dot_Replacement      use "__";
12532     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12533     for Body_Suffix ("Ada")  use ".^ada^ada^";
12534   end Naming;
12535 @end group
12536 @end smallexample
12537
12538 @noindent
12539 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12540 names in lower case)
12541 @end ifset
12542
12543 @noindent
12544 You can define the following attributes in package @code{Naming}:
12545
12546 @table @code
12547
12548 @item @var{Casing}
12549 This must be a string with one of the three values @code{"lowercase"},
12550 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12551
12552 @noindent
12553 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12554
12555 @item @var{Dot_Replacement}
12556 This must be a string whose value satisfies the following conditions:
12557
12558 @itemize @bullet
12559 @item It must not be empty
12560 @item It cannot start or end with an alphanumeric character
12561 @item It cannot be a single underscore
12562 @item It cannot start with an underscore followed by an alphanumeric
12563 @item It cannot contain a dot @code{'.'} except if the entire string
12564 is @code{"."}
12565 @end itemize
12566
12567 @noindent
12568 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12569
12570 @item @var{Spec_Suffix}
12571 This is an associative array (indexed by the programming language name, case
12572 insensitive) whose value is a string that must satisfy the following
12573 conditions:
12574
12575 @itemize @bullet
12576 @item It must not be empty
12577 @item It must include at least one dot
12578 @end itemize
12579 @noindent
12580 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12581 @code{"^.ads^.ADS^"}.
12582
12583 @item @var{Body_Suffix}
12584 This is an associative array (indexed by the programming language name, case
12585 insensitive) whose value is a string that must satisfy the following
12586 conditions:
12587
12588 @itemize @bullet
12589 @item It must not be empty
12590 @item It must include at least one dot
12591 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12592 @end itemize
12593 @noindent
12594 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12595 @code{"^.adb^.ADB^"}.
12596
12597 @item @var{Separate_Suffix}
12598 This must be a string whose value satisfies the same conditions as
12599 @code{Body_Suffix}.
12600
12601 @noindent
12602 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12603 value as @code{Body_Suffix ("Ada")}.
12604
12605 @item @var{Spec}
12606 @noindent
12607 You can use the associative array attribute @code{Spec}  to define
12608 the source file name for an individual Ada compilation unit's spec. The array
12609 index must be a string literal that identifies the Ada unit (case insensitive).
12610 The value of this attribute must be a string that identifies the file that
12611 contains this unit's spec (case sensitive or insensitive depending on the
12612 operating system).
12613
12614 @smallexample @c projectfile
12615    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12616 @end smallexample
12617
12618 @item @var{Body}
12619
12620 You can use the associative array attribute @code{Body} to
12621 define the source file name for an individual Ada compilation unit's body
12622 (possibly a subunit).  The array index must be a string literal that identifies
12623 the Ada unit (case insensitive).  The value of this attribute must be a string
12624 that identifies the file that contains this unit's body or subunit (case
12625 sensitive or insensitive depending on the operating system).
12626
12627 @smallexample @c projectfile
12628    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12629 @end smallexample
12630 @end table
12631
12632 @c ********************
12633 @c * Library Projects *
12634 @c ********************
12635
12636 @node Library Projects
12637 @section Library Projects
12638
12639 @noindent
12640 @emph{Library projects} are projects whose object code is placed in a library.
12641 (Note that this facility is not yet supported on all platforms)
12642
12643 To create a library project, you need to define in its project file
12644 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12645 Additionally, you may define the library-related attributes
12646 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12647 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12648
12649 The @code{Library_Name} attribute has a string value. There is no restriction
12650 on the name of a library. It is the responsibility of the developer to
12651 choose a name that will be accepted by the platform. It is recommended to
12652 choose names that could be Ada identifiers; such names are almost guaranteed
12653 to be acceptable on all platforms.
12654
12655 The @code{Library_Dir} attribute has a string value that designates the path
12656 (absolute or relative) of the directory where the library will reside.
12657 It must designate an existing directory, and this directory must be
12658 different from the project's object directory. It also needs to be writable.
12659 The directory should only be used for one library; the reason is that all
12660 files contained in this directory may be deleted by the Project Manager.
12661
12662 If both @code{Library_Name} and @code{Library_Dir} are specified and
12663 are legal, then the project file defines a library project.  The optional
12664 library-related attributes are checked only for such project files.
12665
12666 The @code{Library_Kind} attribute has a string value that must be one of the
12667 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12668 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12669 attribute is not specified, the library is a static library, that is
12670 an archive of object files that can be potentially linked into an
12671 static executable. Otherwise, the library may be dynamic or
12672 relocatable, that is a library that is loaded only at the start of execution.
12673
12674 If you need to build both a static and a dynamic library, you should use two
12675 different object directories, since in some cases some extra code needs to
12676 be generated for the latter. For such cases, it is recommended to either use
12677 two different project files, or a single one which uses external variables
12678 to indicate what kind of library should be build.
12679
12680 The @code{Library_Version} attribute has a string value whose interpretation
12681 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12682 used only for dynamic/relocatable libraries as the internal name of the
12683 library (the @code{"soname"}). If the library file name (built from the
12684 @code{Library_Name}) is different from the @code{Library_Version}, then the
12685 library file will be a symbolic link to the actual file whose name will be
12686 @code{Library_Version}.
12687
12688 Example (on Unix):
12689
12690 @smallexample @c projectfile
12691 @group
12692 project Plib is
12693
12694    Version := "1";
12695
12696    for Library_Dir use "lib_dir";
12697    for Library_Name use "dummy";
12698    for Library_Kind use "relocatable";
12699    for Library_Version use "libdummy.so." & Version;
12700
12701 end Plib;
12702 @end group
12703 @end smallexample
12704
12705 @noindent
12706 Directory @file{lib_dir} will contain the internal library file whose name
12707 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12708 @file{libdummy.so.1}.
12709
12710 When @command{gnatmake} detects that a project file
12711 is a library project file, it will check all immediate sources of the project
12712 and rebuild the library if any of the sources have been recompiled.
12713
12714 Standard project files can import library project files. In such cases,
12715 the libraries will only be rebuild if some of its sources are recompiled
12716 because they are in the closure of some other source in an importing project.
12717 Sources of the library project files that are not in such a closure will
12718 not be checked, unless the full library is checked, because one of its sources
12719 needs to be recompiled.
12720
12721 For instance, assume the project file @code{A} imports the library project file
12722 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12723 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12724 @file{l2.ads}, @file{l2.adb}.
12725
12726 If @file{l1.adb} has been modified, then the library associated with @code{L}
12727 will be rebuild when compiling all the immediate sources of @code{A} only
12728 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12729 @code{"with L1;"}.
12730
12731 To be sure that all the sources in the library associated with @code{L} are
12732 up to date, and that all the sources of project @code{A} are also up to date,
12733 the following two commands needs to be used:
12734
12735 @smallexample
12736 gnatmake -Pl.gpr
12737 gnatmake -Pa.gpr
12738 @end smallexample
12739
12740 When a library is built or rebuilt, an attempt is made first to delete all
12741 files in the library directory.
12742 All @file{ALI} files will also be copied from the object directory to the
12743 library directory. To build executables, @command{gnatmake} will use the
12744 library rather than the individual object files.
12745
12746 @ifclear vms
12747 It is also possible to create library project files for third-party libraries
12748 that are precompiled and cannot be compiled locally thanks to the
12749 @code{externally_built} attribute. (See @ref{Installing a library}).
12750 @end ifclear
12751
12752 @c *******************************
12753 @c * Stand-alone Library Projects *
12754 @c *******************************
12755
12756 @node Stand-alone Library Projects
12757 @section Stand-alone Library Projects
12758
12759 @noindent
12760 A Stand-alone Library is a library that contains the necessary code to
12761 elaborate the Ada units that are included in the library. A Stand-alone
12762 Library is suitable to be used in an executable when the main is not
12763 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12764 subprogram.
12765
12766 A Stand-alone Library Project is a Library Project where the library is
12767 a Stand-alone Library.
12768
12769 To be a Stand-alone Library Project, in addition to the two attributes
12770 that make a project a Library Project (@code{Library_Name} and
12771 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12772 @code{Library_Interface} must be defined.
12773
12774 @smallexample @c projectfile
12775 @group
12776    for Library_Dir use "lib_dir";
12777    for Library_Name use "dummy";
12778    for Library_Interface use ("int1", "int1.child");
12779 @end group
12780 @end smallexample
12781
12782 Attribute @code{Library_Interface} has a non empty string list value,
12783 each string in the list designating a unit contained in an immediate source
12784 of the project file.
12785
12786 When a Stand-alone Library is built, first the binder is invoked to build
12787 a package whose name depends on the library name
12788 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12789 This binder-generated package includes initialization and
12790 finalization procedures whose
12791 names depend on the library name (dummyinit and dummyfinal in the example
12792 above). The object corresponding to this package is included in the library.
12793
12794 A dynamic or relocatable Stand-alone Library is automatically initialized
12795 if automatic initialization of Stand-alone Libraries is supported on the
12796 platform and if attribute @code{Library_Auto_Init} is not specified or
12797 is specified with the value "true". A static Stand-alone Library is never
12798 automatically initialized.
12799
12800 Single string attribute @code{Library_Auto_Init} may be specified with only
12801 two possible values: "false" or "true" (case-insensitive). Specifying
12802 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12803 initialization of dynamic or relocatable libraries.
12804
12805 When a non automatically initialized Stand-alone Library is used
12806 in an executable, its initialization procedure must be called before
12807 any service of the library is used.
12808 When the main subprogram is in Ada, it may mean that the initialization
12809 procedure has to be called during elaboration of another package.
12810
12811 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12812 (those that are listed in attribute @code{Library_Interface}) are copied to
12813 the Library Directory. As a consequence, only the Interface Units may be
12814 imported from Ada units outside of the library. If other units are imported,
12815 the binding phase will fail.
12816
12817 When a Stand-Alone Library is bound, the switches that are specified in
12818 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12819 used in the call to @command{gnatbind}.
12820
12821 The string list attribute @code{Library_Options} may be used to specified
12822 additional switches to the call to @command{gcc} to link the library.
12823
12824 The attribute @code{Library_Src_Dir}, may be specified for a
12825 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12826 single string value. Its value must be the path (absolute or relative to the
12827 project directory) of an existing directory. This directory cannot be the
12828 object directory or one of the source directories, but it can be the same as
12829 the library directory. The sources of the Interface
12830 Units of the library, necessary to an Ada client of the library, will be
12831 copied to the designated directory, called Interface Copy directory.
12832 These sources includes the specs of the Interface Units, but they may also
12833 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12834 are used, or when there is a generic units in the spec. Before the sources
12835 are copied to the Interface Copy directory, an attempt is made to delete all
12836 files in the Interface Copy directory.
12837
12838 @c *************************************
12839 @c * Switches Related to Project Files *
12840 @c *************************************
12841 @node Switches Related to Project Files
12842 @section Switches Related to Project Files
12843
12844 @noindent
12845 The following switches are used by GNAT tools that support project files:
12846
12847 @table @option
12848
12849 @item ^-P^/PROJECT_FILE=^@var{project}
12850 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12851 Indicates the name of a project file. This project file will be parsed with
12852 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12853 if any, and using the external references indicated
12854 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12855 @ifclear vms
12856 There may zero, one or more spaces between @option{-P} and @var{project}.
12857 @end ifclear
12858
12859 @noindent
12860 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12861
12862 @noindent
12863 Since the Project Manager parses the project file only after all the switches
12864 on the command line are checked, the order of the switches
12865 @option{^-P^/PROJECT_FILE^},
12866 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12867 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12868
12869 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12870 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12871 Indicates that external variable @var{name} has the value @var{value}.
12872 The Project Manager will use this value for occurrences of
12873 @code{external(name)} when parsing the project file.
12874
12875 @ifclear vms
12876 @noindent
12877 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12878 put between quotes.
12879 @smallexample
12880   -XOS=NT
12881   -X"user=John Doe"
12882 @end smallexample
12883 @end ifclear
12884
12885 @noindent
12886 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12887 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12888 @var{name}, only the last one is used.
12889
12890 @noindent
12891 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12892 takes precedence over the value of the same name in the environment.
12893
12894 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12895 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12896 @c Previous line uses code vs option command, to stay less than 80 chars
12897 Indicates the verbosity of the parsing of GNAT project files.
12898
12899 @ifclear vms
12900 @option{-vP0} means Default;
12901 @option{-vP1} means Medium;
12902 @option{-vP2} means High.
12903 @end ifclear
12904
12905 @ifset vms
12906 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12907 HIGH.
12908 @end ifset
12909
12910 @noindent
12911 The default is ^Default^DEFAULT^: no output for syntactically correct
12912 project files.
12913 @noindent
12914 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12915 only the last one is used.
12916
12917 @end table
12918
12919 @c **********************************
12920 @c * Tools Supporting Project Files *
12921 @c **********************************
12922
12923 @node  Tools Supporting Project Files
12924 @section Tools Supporting Project Files
12925
12926 @menu
12927 * gnatmake and Project Files::
12928 * The GNAT Driver and Project Files::
12929 @ifclear vms
12930 * Glide and Project Files::
12931 @end ifclear
12932 @end menu
12933
12934 @node gnatmake and Project Files
12935 @subsection gnatmake and Project Files
12936
12937 @noindent
12938 This section covers several topics related to @command{gnatmake} and
12939 project files: defining ^switches^switches^ for @command{gnatmake}
12940 and for the tools that it invokes; specifying configuration pragmas;
12941 the use of the @code{Main} attribute; building and rebuilding library project
12942 files.
12943
12944 @menu
12945 * ^Switches^Switches^ and Project Files::
12946 * Specifying Configuration Pragmas::
12947 * Project Files and Main Subprograms::
12948 * Library Project Files::
12949 @end menu
12950
12951 @node ^Switches^Switches^ and Project Files
12952 @subsubsection ^Switches^Switches^ and Project Files
12953
12954 @ifset vms
12955 It is not currently possible to specify VMS style qualifiers in the project
12956 files; only Unix style ^switches^switches^ may be specified.
12957 @end ifset
12958
12959 @noindent
12960 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12961 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12962 attribute, a @code{^Switches^Switches^} attribute, or both;
12963 as their names imply, these ^switch^switch^-related
12964 attributes affect the ^switches^switches^ that are used for each of these GNAT
12965 components when
12966 @command{gnatmake} is invoked.  As will be explained below, these
12967 component-specific ^switches^switches^ precede
12968 the ^switches^switches^ provided on the @command{gnatmake} command line.
12969
12970 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12971 array indexed by language name (case insensitive) whose value is a string list.
12972 For example:
12973
12974 @smallexample @c projectfile
12975 @group
12976 package Compiler is
12977   for ^Default_Switches^Default_Switches^ ("Ada")
12978       use ("^-gnaty^-gnaty^",
12979            "^-v^-v^");
12980 end Compiler;
12981 @end group
12982 @end smallexample
12983
12984 @noindent
12985 The @code{^Switches^Switches^} attribute is also an associative array,
12986 indexed by a file name (which may or may not be case sensitive, depending
12987 on the operating system) whose value is a string list.  For example:
12988
12989 @smallexample @c projectfile
12990 @group
12991 package Builder is
12992    for ^Switches^Switches^ ("main1.adb")
12993        use ("^-O2^-O2^");
12994    for ^Switches^Switches^ ("main2.adb")
12995        use ("^-g^-g^");
12996 end Builder;
12997 @end group
12998 @end smallexample
12999
13000 @noindent
13001 For the @code{Builder} package, the file names must designate source files
13002 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
13003 file names must designate @file{ALI} or source files for main subprograms.
13004 In each case just the file name without an explicit extension is acceptable.
13005
13006 For each tool used in a program build (@command{gnatmake}, the compiler, the
13007 binder, and the linker), the corresponding package @dfn{contributes} a set of
13008 ^switches^switches^ for each file on which the tool is invoked, based on the
13009 ^switch^switch^-related attributes defined in the package.
13010 In particular, the ^switches^switches^
13011 that each of these packages contributes for a given file @var{f} comprise:
13012
13013 @itemize @bullet
13014 @item
13015 the value of attribute @code{^Switches^Switches^ (@var{f})},
13016 if it is specified in the package for the given file,
13017 @item
13018 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13019 if it is specified in the package.
13020 @end itemize
13021
13022 @noindent
13023 If neither of these attributes is defined in the package, then the package does
13024 not contribute any ^switches^switches^ for the given file.
13025
13026 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13027 two sets, in the following order: those contributed for the file
13028 by the @code{Builder} package;
13029 and the switches passed on the command line.
13030
13031 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13032 the ^switches^switches^ passed to the tool comprise three sets,
13033 in the following order:
13034
13035 @enumerate
13036 @item
13037 the applicable ^switches^switches^ contributed for the file
13038 by the @code{Builder} package in the project file supplied on the command line;
13039
13040 @item
13041 those contributed for the file by the package (in the relevant project file --
13042 see below) corresponding to the tool; and
13043
13044 @item
13045 the applicable switches passed on the command line.
13046 @end enumerate
13047
13048 @noindent
13049 The term @emph{applicable ^switches^switches^} reflects the fact that
13050 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13051 tools, depending on the individual ^switch^switch^.
13052
13053 @command{gnatmake} may invoke the compiler on source files from different
13054 projects. The Project Manager will use the appropriate project file to
13055 determine the @code{Compiler} package for each source file being compiled.
13056 Likewise for the @code{Binder} and @code{Linker} packages.
13057
13058 As an example, consider the following package in a project file:
13059
13060 @smallexample @c projectfile
13061 @group
13062 project Proj1 is
13063    package Compiler is
13064       for ^Default_Switches^Default_Switches^ ("Ada")
13065           use ("^-g^-g^");
13066       for ^Switches^Switches^ ("a.adb")
13067           use ("^-O1^-O1^");
13068       for ^Switches^Switches^ ("b.adb")
13069           use ("^-O2^-O2^",
13070                "^-gnaty^-gnaty^");
13071    end Compiler;
13072 end Proj1;
13073 @end group
13074 @end smallexample
13075
13076 @noindent
13077 If @command{gnatmake} is invoked with this project file, and it needs to
13078 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13079 @file{a.adb} will be compiled with the ^switch^switch^
13080 @option{^-O1^-O1^},
13081 @file{b.adb} with ^switches^switches^
13082 @option{^-O2^-O2^}
13083 and @option{^-gnaty^-gnaty^},
13084 and @file{c.adb} with @option{^-g^-g^}.
13085
13086 The following example illustrates the ordering of the ^switches^switches^
13087 contributed by different packages:
13088
13089 @smallexample @c projectfile
13090 @group
13091 project Proj2 is
13092    package Builder is
13093       for ^Switches^Switches^ ("main.adb")
13094           use ("^-g^-g^",
13095                "^-O1^-)1^",
13096                "^-f^-f^");
13097    end Builder;
13098 @end group
13099
13100 @group
13101    package Compiler is
13102       for ^Switches^Switches^ ("main.adb")
13103           use ("^-O2^-O2^");
13104    end Compiler;
13105 end Proj2;
13106 @end group
13107 @end smallexample
13108
13109 @noindent
13110 If you issue the command:
13111
13112 @smallexample
13113     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13114 @end smallexample
13115
13116 @noindent
13117 then the compiler will be invoked on @file{main.adb} with the following
13118 sequence of ^switches^switches^
13119
13120 @smallexample
13121    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13122 @end smallexample
13123
13124 with the last @option{^-O^-O^}
13125 ^switch^switch^ having precedence over the earlier ones;
13126 several other ^switches^switches^
13127 (such as @option{^-c^-c^}) are added implicitly.
13128
13129 The ^switches^switches^
13130 @option{^-g^-g^}
13131 and @option{^-O1^-O1^} are contributed by package
13132 @code{Builder},  @option{^-O2^-O2^} is contributed
13133 by the package @code{Compiler}
13134 and @option{^-O0^-O0^} comes from the command line.
13135
13136 The @option{^-g^-g^}
13137 ^switch^switch^ will also be passed in the invocation of
13138 @command{Gnatlink.}
13139
13140 A final example illustrates switch contributions from packages in different
13141 project files:
13142
13143 @smallexample @c projectfile
13144 @group
13145 project Proj3 is
13146    for Source_Files use ("pack.ads", "pack.adb");
13147    package Compiler is
13148       for ^Default_Switches^Default_Switches^ ("Ada")
13149           use ("^-gnata^-gnata^");
13150    end Compiler;
13151 end Proj3;
13152 @end group
13153
13154 @group
13155 with "Proj3";
13156 project Proj4 is
13157    for Source_Files use ("foo_main.adb", "bar_main.adb");
13158    package Builder is
13159       for ^Switches^Switches^ ("foo_main.adb")
13160           use ("^-s^-s^",
13161                "^-g^-g^");
13162    end Builder;
13163 end Proj4;
13164 @end group
13165
13166 @group
13167 -- Ada source file:
13168 with Pack;
13169 procedure Foo_Main is
13170    ...
13171 end Foo_Main;
13172 @end group
13173 @end smallexample
13174
13175 If the command is
13176 @smallexample
13177 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13178 @end smallexample
13179
13180 @noindent
13181 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13182 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13183 @option{^-gnato^-gnato^} (passed on the command line).
13184 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13185 are @option{^-g^-g^} from @code{Proj4.Builder},
13186 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13187 and @option{^-gnato^-gnato^} from the command line.
13188
13189 @noindent
13190 When using @command{gnatmake} with project files, some ^switches^switches^ or
13191 arguments may be expressed as relative paths. As the working directory where
13192 compilation occurs may change, these relative paths are converted to absolute
13193 paths. For the ^switches^switches^ found in a project file, the relative paths
13194 are relative to the project file directory, for the switches on the command
13195 line, they are relative to the directory where @command{gnatmake} is invoked.
13196 The ^switches^switches^ for which this occurs are:
13197 ^-I^-I^,
13198 ^-A^-A^,
13199 ^-L^-L^,
13200 ^-aO^-aO^,
13201 ^-aL^-aL^,
13202 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13203 ^switch^switch^
13204 ^-o^-o^, object files specified in package @code{Linker} or after
13205 -largs on the command line). The exception to this rule is the ^switch^switch^
13206 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13207
13208 @node Specifying Configuration Pragmas
13209 @subsubsection Specifying Configuration Pragmas
13210
13211 When using @command{gnatmake} with project files, if there exists a file
13212 @file{gnat.adc} that contains configuration pragmas, this file will be
13213 ignored.
13214
13215 Configuration pragmas can be defined by means of the following attributes in
13216 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13217 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13218
13219 Both these attributes are single string attributes. Their values is the path
13220 name of a file containing configuration pragmas. If a path name is relative,
13221 then it is relative to the project directory of the project file where the
13222 attribute is defined.
13223
13224 When compiling a source, the configuration pragmas used are, in order,
13225 those listed in the file designated by attribute
13226 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13227 project file, if it is specified, and those listed in the file designated by
13228 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13229 the project file of the source, if it exists.
13230
13231 @node Project Files and Main Subprograms
13232 @subsubsection Project Files and Main Subprograms
13233
13234 @noindent
13235 When using a project file, you can invoke @command{gnatmake}
13236 with one or several main subprograms, by specifying their source files on the
13237 command line.
13238
13239 @smallexample
13240     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13241 @end smallexample
13242
13243 @noindent
13244 Each of these needs to be a source file of the same project, except
13245 when the switch ^-u^/UNIQUE^ is used.
13246
13247 @noindent
13248 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13249 same project, one of the project in the tree rooted at the project specified
13250 on the command line. The package @code{Builder} of this common project, the
13251 "main project" is the one that is considered by @command{gnatmake}.
13252
13253 @noindent
13254 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13255 imported directly or indirectly by the project specified on the command line.
13256 Note that if such a source file is not part of the project specified on the
13257 command line, the ^switches^switches^ found in package @code{Builder} of the
13258 project specified on the command line, if any, that are transmitted
13259 to the compiler will still be used, not those found in the project file of
13260 the source file.
13261
13262 @noindent
13263 When using a project file, you can also invoke @command{gnatmake} without
13264 explicitly specifying any main, and the effect depends on whether you have
13265 defined the @code{Main} attribute.  This attribute has a string list value,
13266 where each element in the list is the name of a source file (the file
13267 extension is optional) that contains a unit that can be a main subprogram.
13268
13269 If the @code{Main} attribute is defined in a project file as a non-empty
13270 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13271 line, then invoking @command{gnatmake} with this project file but without any
13272 main on the command line is equivalent to invoking @command{gnatmake} with all
13273 the file names in the @code{Main} attribute on the command line.
13274
13275 Example:
13276 @smallexample @c projectfile
13277 @group
13278    project Prj is
13279       for Main use ("main1", "main2", "main3");
13280    end Prj;
13281 @end group
13282 @end smallexample
13283
13284 @noindent
13285 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13286 is equivalent to
13287 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13288
13289 When the project attribute @code{Main} is not specified, or is specified
13290 as an empty string list, or when the switch @option{-u} is used on the command
13291 line, then invoking @command{gnatmake} with no main on the command line will
13292 result in all immediate sources of the project file being checked, and
13293 potentially recompiled. Depending on the presence of the switch @option{-u},
13294 sources from other project files on which the immediate sources of the main
13295 project file depend are also checked and potentially recompiled. In other
13296 words, the @option{-u} switch is applied to all of the immediate sources of the
13297 main project file.
13298
13299 When no main is specified on the command line and attribute @code{Main} exists
13300 and includes several mains, or when several mains are specified on the
13301 command line, the default ^switches^switches^ in package @code{Builder} will
13302 be used for all mains, even if there are specific ^switches^switches^
13303 specified for one or several mains.
13304
13305 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13306 the specific ^switches^switches^ for each main, if they are specified.
13307
13308 @node Library Project Files
13309 @subsubsection Library Project Files
13310
13311 @noindent
13312 When @command{gnatmake} is invoked with a main project file that is a library
13313 project file, it is not allowed to specify one or more mains on the command
13314 line.
13315
13316 @noindent
13317 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13318 ^-l^/ACTION=LINK^ have special meanings.
13319
13320 @itemize @bullet
13321 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13322 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13323 library.
13324
13325 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13326 to @command{gnatmake} that the binder generated file should be compiled
13327 (in the case of a stand-alone library) and that the library should be built.
13328
13329 @end itemize
13330
13331 @node The GNAT Driver and Project Files
13332 @subsection The GNAT Driver and Project Files
13333
13334 @noindent
13335 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13336 are project-aware:
13337 @command{^gnatbind^gnatbind^},
13338 @command{^gnatfind^gnatfind^},
13339 @command{^gnatlink^gnatlink^},
13340 @command{^gnatls^gnatls^},
13341 @command{^gnatelim^gnatelim^},
13342 @command{^gnatpp^gnatpp^},
13343 @command{^gnatmetric^gnatmetric^},
13344 @command{^gnatstub^gnatstub^},
13345 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13346 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13347 They must be invoked through the @command{gnat} driver.
13348
13349 The @command{gnat} driver is a front-end that accepts a number of commands and
13350 call the corresponding tool. It has been designed initially for VMS to convert
13351 VMS style qualifiers to Unix style switches, but it is now available to all
13352 the GNAT supported platforms.
13353
13354 On non VMS platforms, the @command{gnat} driver accepts the following commands
13355 (case insensitive):
13356
13357 @itemize @bullet
13358 @item
13359 BIND to invoke @command{^gnatbind^gnatbind^}
13360 @item
13361 CHOP to invoke @command{^gnatchop^gnatchop^}
13362 @item
13363 CLEAN to invoke @command{^gnatclean^gnatclean^}
13364 @item
13365 COMP or COMPILE to invoke the compiler
13366 @item
13367 ELIM to invoke @command{^gnatelim^gnatelim^}
13368 @item
13369 FIND to invoke @command{^gnatfind^gnatfind^}
13370 @item
13371 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13372 @item
13373 LINK to invoke @command{^gnatlink^gnatlink^}
13374 @item
13375 LS or LIST to invoke @command{^gnatls^gnatls^}
13376 @item
13377 MAKE to invoke @command{^gnatmake^gnatmake^}
13378 @item
13379 NAME to invoke @command{^gnatname^gnatname^}
13380 @item
13381 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13382 @item
13383 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13384 @item
13385 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13386 @item
13387 STUB to invoke @command{^gnatstub^gnatstub^}
13388 @item
13389 XREF to invoke @command{^gnatxref^gnatxref^}
13390 @end itemize
13391
13392 @noindent
13393 (note that the compiler is invoked using the command
13394 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13395
13396 @noindent
13397 On non VMS platforms, between @command{gnat} and the command, two
13398 special switches may be used:
13399
13400 @itemize @bullet
13401 @item
13402 @command{-v} to display the invocation of the tool.
13403 @item
13404 @command{-dn} to prevent the @command{gnat} driver from removing
13405 the temporary files it has created. These temporary files are
13406 configuration files and temporary file list files.
13407 @end itemize
13408
13409 @noindent
13410 The command may be followed by switches and arguments for the invoked
13411 tool.
13412
13413 @smallexample
13414   gnat bind -C main.ali
13415   gnat ls -a main
13416   gnat chop foo.txt
13417 @end smallexample
13418
13419 @noindent
13420 Switches may also be put in text files, one switch per line, and the text
13421 files may be specified with their path name preceded by '@@'.
13422
13423 @smallexample
13424    gnat bind @@args.txt main.ali
13425 @end smallexample
13426
13427 @noindent
13428 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13429 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13430 (@option{^-P^/PROJECT_FILE^},
13431 @option{^-X^/EXTERNAL_REFERENCE^} and
13432 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13433 the switches of the invoking tool.
13434
13435 @noindent
13436 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13437 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13438 the immediate sources of the specified project file.
13439
13440 @noindent
13441 When GNAT METRIC is used with a project file, but with no source
13442 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13443 with all the immediate sources of the specified project file and with
13444 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13445 of the project.
13446
13447 @noindent
13448 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13449 a project file, no source is specified on the command line and
13450 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13451 the underlying tool (^gnatpp^gnatpp^ or
13452 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13453 not only for the immediate sources of the main project.
13454 @ifclear vms
13455 (-U stands for Universal or Union of the project files of the project tree)
13456 @end ifclear
13457
13458 @noindent
13459 For each of the following commands, there is optionally a corresponding
13460 package in the main project.
13461
13462 @itemize @bullet
13463 @item
13464 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13465
13466 @item
13467 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13468
13469 @item
13470 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13471
13472 @item
13473 package @code{Eliminate} for command ELIM (invoking
13474 @code{^gnatelim^gnatelim^})
13475
13476 @item
13477 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13478
13479 @item
13480 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13481
13482 @item
13483 package @code{Metrics} for command METRIC
13484 (invoking @code{^gnatmetric^gnatmetric^})
13485
13486 @item
13487 package @code{Pretty_Printer} for command PP or PRETTY
13488 (invoking @code{^gnatpp^gnatpp^})
13489
13490 @item
13491 package @code{Gnatstub} for command STUB
13492 (invoking @code{^gnatstub^gnatstub^})
13493
13494 @item
13495 package @code{Cross_Reference} for command XREF (invoking
13496 @code{^gnatxref^gnatxref^})
13497
13498 @end itemize
13499
13500 @noindent
13501 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13502 a simple variable with a string list value. It contains ^switches^switches^
13503 for the invocation of @code{^gnatls^gnatls^}.
13504
13505 @smallexample @c projectfile
13506 @group
13507 project Proj1 is
13508    package gnatls is
13509       for ^Switches^Switches^
13510           use ("^-a^-a^",
13511                "^-v^-v^");
13512    end gnatls;
13513 end Proj1;
13514 @end group
13515 @end smallexample
13516
13517 @noindent
13518 All other packages have two attribute @code{^Switches^Switches^} and
13519 @code{^Default_Switches^Default_Switches^}.
13520
13521 @noindent
13522 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13523 source file name, that has a string list value: the ^switches^switches^ to be
13524 used when the tool corresponding to the package is invoked for the specific
13525 source file.
13526
13527 @noindent
13528 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13529 indexed by  the programming language that has a string list value.
13530 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13531 ^switches^switches^ for the invocation of the tool corresponding
13532 to the package, except if a specific @code{^Switches^Switches^} attribute
13533 is specified for the source file.
13534
13535 @smallexample @c projectfile
13536 @group
13537 project Proj is
13538
13539    for Source_Dirs use ("./**");
13540
13541    package gnatls is
13542       for ^Switches^Switches^ use
13543           ("^-a^-a^",
13544            "^-v^-v^");
13545    end gnatls;
13546 @end group
13547 @group
13548
13549    package Compiler is
13550       for ^Default_Switches^Default_Switches^ ("Ada")
13551           use ("^-gnatv^-gnatv^",
13552                "^-gnatwa^-gnatwa^");
13553    end Binder;
13554 @end group
13555 @group
13556
13557    package Binder is
13558       for ^Default_Switches^Default_Switches^ ("Ada")
13559           use ("^-C^-C^",
13560                "^-e^-e^");
13561    end Binder;
13562 @end group
13563 @group
13564
13565    package Linker is
13566       for ^Default_Switches^Default_Switches^ ("Ada")
13567           use ("^-C^-C^");
13568       for ^Switches^Switches^ ("main.adb")
13569           use ("^-C^-C^",
13570                "^-v^-v^",
13571                "^-v^-v^");
13572    end Linker;
13573 @end group
13574 @group
13575
13576    package Finder is
13577       for ^Default_Switches^Default_Switches^ ("Ada")
13578            use ("^-a^-a^",
13579                 "^-f^-f^");
13580    end Finder;
13581 @end group
13582 @group
13583
13584    package Cross_Reference is
13585       for ^Default_Switches^Default_Switches^ ("Ada")
13586           use ("^-a^-a^",
13587                "^-f^-f^",
13588                "^-d^-d^",
13589                "^-u^-u^");
13590    end Cross_Reference;
13591 end Proj;
13592 @end group
13593 @end smallexample
13594
13595 @noindent
13596 With the above project file, commands such as
13597
13598 @smallexample
13599    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13600    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13601    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13602    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13603    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13604 @end smallexample
13605
13606 @noindent
13607 will set up the environment properly and invoke the tool with the switches
13608 found in the package corresponding to the tool:
13609 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13610 except @code{^Switches^Switches^ ("main.adb")}
13611 for @code{^gnatlink^gnatlink^}.
13612
13613 @ifclear vms
13614 @node Glide and Project Files
13615 @subsection Glide and Project Files
13616
13617 @noindent
13618 Glide will automatically recognize the @file{.gpr} extension for
13619 project files, and will
13620 convert them to its own internal format automatically. However, it
13621 doesn't provide a syntax-oriented editor for modifying these
13622 files.
13623 The project file will be loaded as text when you select the menu item
13624 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13625 You can edit this text and save the @file{gpr} file;
13626 when you next select this project file in Glide it
13627 will be automatically reloaded.
13628 @end ifclear
13629
13630 @c **********************
13631 @node An Extended Example
13632 @section An Extended Example
13633
13634 @noindent
13635 Suppose that we have two programs, @var{prog1} and @var{prog2},
13636 whose sources are in corresponding directories. We would like
13637 to build them with a single @command{gnatmake} command, and we want to place
13638 their object files into @file{build} subdirectories of the source directories.
13639 Furthermore, we want to have to have two separate subdirectories
13640 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13641 the object files compiled with different set of compilation flags.
13642
13643 In other words, we have the following structure:
13644
13645 @smallexample
13646 @group
13647    main
13648      |- prog1
13649      |    |- build
13650      |         | debug
13651      |         | release
13652      |- prog2
13653           |- build
13654                | debug
13655                | release
13656 @end group
13657 @end smallexample
13658
13659 @noindent
13660 Here are the project files that we must place in a directory @file{main}
13661 to maintain this structure:
13662
13663 @enumerate
13664
13665 @item We create a @code{Common} project with a package @code{Compiler} that
13666 specifies the compilation ^switches^switches^:
13667
13668 @smallexample
13669 File "common.gpr":
13670 @group
13671 @b{project} Common @b{is}
13672
13673    @b{for} Source_Dirs @b{use} (); -- No source files
13674 @end group
13675
13676 @group
13677    @b{type} Build_Type @b{is} ("release", "debug");
13678    Build : Build_Type := External ("BUILD", "debug");
13679 @end group
13680 @group
13681    @b{package} Compiler @b{is}
13682       @b{case} Build @b{is}
13683          @b{when} "release" =>
13684            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13685                    @b{use} ("^-O2^-O2^");
13686          @b{when} "debug"   =>
13687            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13688                    @b{use} ("^-g^-g^");
13689       @b{end case};
13690    @b{end} Compiler;
13691
13692 @b{end} Common;
13693 @end group
13694 @end smallexample
13695
13696 @item We create separate projects for the two programs:
13697
13698 @smallexample
13699 @group
13700 File "prog1.gpr":
13701
13702 @b{with} "common";
13703 @b{project} Prog1 @b{is}
13704
13705     @b{for} Source_Dirs @b{use} ("prog1");
13706     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13707
13708     @b{package} Compiler @b{renames} Common.Compiler;
13709
13710 @b{end} Prog1;
13711 @end group
13712 @end smallexample
13713
13714 @smallexample
13715 @group
13716 File "prog2.gpr":
13717
13718 @b{with} "common";
13719 @b{project} Prog2 @b{is}
13720
13721     @b{for} Source_Dirs @b{use} ("prog2");
13722     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13723
13724     @b{package} Compiler @b{renames} Common.Compiler;
13725
13726 @end group
13727 @b{end} Prog2;
13728 @end smallexample
13729
13730 @item We create a wrapping project @code{Main}:
13731
13732 @smallexample
13733 @group
13734 File "main.gpr":
13735
13736 @b{with} "common";
13737 @b{with} "prog1";
13738 @b{with} "prog2";
13739 @b{project} Main @b{is}
13740
13741    @b{package} Compiler @b{renames} Common.Compiler;
13742
13743 @b{end} Main;
13744 @end group
13745 @end smallexample
13746
13747 @item Finally we need to create a dummy procedure that @code{with}s (either
13748 explicitly or implicitly) all the sources of our two programs.
13749
13750 @end enumerate
13751
13752 @noindent
13753 Now we can build the programs using the command
13754
13755 @smallexample
13756    gnatmake ^-P^/PROJECT_FILE=^main dummy
13757 @end smallexample
13758
13759 @noindent
13760 for the Debug mode, or
13761
13762 @ifclear vms
13763 @smallexample
13764    gnatmake -Pmain -XBUILD=release
13765 @end smallexample
13766 @end ifclear
13767
13768 @ifset vms
13769 @smallexample
13770    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13771 @end smallexample
13772 @end ifset
13773
13774 @noindent
13775 for the Release mode.
13776
13777 @c ********************************
13778 @c * Project File Complete Syntax *
13779 @c ********************************
13780
13781 @node Project File Complete Syntax
13782 @section Project File Complete Syntax
13783
13784 @smallexample
13785 project ::=
13786   context_clause project_declaration
13787
13788 context_clause ::=
13789   @{with_clause@}
13790
13791 with_clause ::=
13792   @b{with} path_name @{ , path_name @} ;
13793
13794 path_name ::=
13795    string_literal
13796
13797 project_declaration ::=
13798   simple_project_declaration | project_extension
13799
13800 simple_project_declaration ::=
13801   @b{project} <project_>simple_name @b{is}
13802     @{declarative_item@}
13803   @b{end} <project_>simple_name;
13804
13805 project_extension ::=
13806   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13807     @{declarative_item@}
13808   @b{end} <project_>simple_name;
13809
13810 declarative_item ::=
13811   package_declaration |
13812   typed_string_declaration |
13813   other_declarative_item
13814
13815 package_declaration ::=
13816   package_specification | package_renaming
13817
13818 package_specification ::=
13819   @b{package} package_identifier @b{is}
13820     @{simple_declarative_item@}
13821   @b{end} package_identifier ;
13822
13823 package_identifier ::=
13824   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13825   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13826   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13827
13828 package_renaming ::==
13829   @b{package} package_identifier @b{renames}
13830        <project_>simple_name.package_identifier ;
13831
13832 typed_string_declaration ::=
13833   @b{type} <typed_string_>_simple_name @b{is}
13834    ( string_literal @{, string_literal@} );
13835
13836 other_declarative_item ::=
13837   attribute_declaration |
13838   typed_variable_declaration |
13839   variable_declaration |
13840   case_construction
13841
13842 attribute_declaration ::=
13843   full_associative_array_declaration |
13844   @b{for} attribute_designator @b{use} expression ;
13845
13846 full_associative_array_declaration ::=
13847   @b{for} <associative_array_attribute_>simple_name @b{use}
13848   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13849
13850 attribute_designator ::=
13851   <simple_attribute_>simple_name |
13852   <associative_array_attribute_>simple_name ( string_literal )
13853
13854 typed_variable_declaration ::=
13855   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13856
13857 variable_declaration ::=
13858   <variable_>simple_name := expression;
13859
13860 expression ::=
13861   term @{& term@}
13862
13863 term ::=
13864   literal_string |
13865   string_list |
13866   <variable_>name |
13867   external_value |
13868   attribute_reference
13869
13870 string_literal ::=
13871   (same as Ada)
13872
13873 string_list ::=
13874   ( <string_>expression @{ , <string_>expression @} )
13875
13876 external_value ::=
13877   @b{external} ( string_literal [, string_literal] )
13878
13879 attribute_reference ::=
13880   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13881
13882 attribute_prefix ::=
13883   @b{project} |
13884   <project_>simple_name | package_identifier |
13885   <project_>simple_name . package_identifier
13886
13887 case_construction ::=
13888   @b{case} <typed_variable_>name @b{is}
13889     @{case_item@}
13890   @b{end case} ;
13891
13892 case_item ::=
13893   @b{when} discrete_choice_list =>
13894       @{case_construction | attribute_declaration@}
13895
13896 discrete_choice_list ::=
13897   string_literal @{| string_literal@} |
13898   @b{others}
13899
13900 name ::=
13901   simple_name @{. simple_name@}
13902
13903 simple_name ::=
13904   identifier (same as Ada)
13905
13906 @end smallexample
13907
13908 @node The Cross-Referencing Tools gnatxref and gnatfind
13909 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13910 @findex gnatxref
13911 @findex gnatfind
13912
13913 @noindent
13914 The compiler generates cross-referencing information (unless
13915 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13916 This information indicates where in the source each entity is declared and
13917 referenced. Note that entities in package Standard are not included, but
13918 entities in all other predefined units are included in the output.
13919
13920 Before using any of these two tools, you need to compile successfully your
13921 application, so that GNAT gets a chance to generate the cross-referencing
13922 information.
13923
13924 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13925 information to provide the user with the capability to easily locate the
13926 declaration and references to an entity. These tools are quite similar,
13927 the difference being that @code{gnatfind} is intended for locating
13928 definitions and/or references to a specified entity or entities, whereas
13929 @code{gnatxref} is oriented to generating a full report of all
13930 cross-references.
13931
13932 To use these tools, you must not compile your application using the
13933 @option{-gnatx} switch on the @command{gnatmake} command line
13934 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13935 information will not be generated.
13936
13937 @menu
13938 * gnatxref Switches::
13939 * gnatfind Switches::
13940 * Project Files for gnatxref and gnatfind::
13941 * Regular Expressions in gnatfind and gnatxref::
13942 * Examples of gnatxref Usage::
13943 * Examples of gnatfind Usage::
13944 @end menu
13945
13946 @node gnatxref Switches
13947 @section @code{gnatxref} Switches
13948
13949 @noindent
13950 The command invocation for @code{gnatxref} is:
13951 @smallexample
13952 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13953 @end smallexample
13954
13955 @noindent
13956 where
13957
13958 @table @code
13959 @item sourcefile1, sourcefile2
13960 identifies the source files for which a report is to be generated. The
13961 ``with''ed units will be processed too. You must provide at least one file.
13962
13963 These file names are considered to be regular expressions, so for instance
13964 specifying @file{source*.adb} is the same as giving every file in the current
13965 directory whose name starts with @file{source} and whose extension is
13966 @file{adb}.
13967
13968 You shouldn't specify any directory name, just base names. @command{gnatxref}
13969 and @command{gnatfind} will be able to locate these files by themselves using
13970 the source path. If you specify directories, no result is produced.
13971
13972 @end table
13973
13974 @noindent
13975 The switches can be :
13976 @table @option
13977 @c !sort!
13978 @item ^-a^/ALL_FILES^
13979 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13980 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13981 the read-only files found in the library search path. Otherwise, these files
13982 will be ignored. This option can be used to protect Gnat sources or your own
13983 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13984 much faster, and their output much smaller. Read-only here refers to access
13985 or permissions status in the file system for the current user.
13986
13987 @item -aIDIR
13988 @cindex @option{-aIDIR} (@command{gnatxref})
13989 When looking for source files also look in directory DIR. The order in which
13990 source file search is undertaken is the same as for @command{gnatmake}.
13991
13992 @item -aODIR
13993 @cindex @option{-aODIR} (@command{gnatxref})
13994 When searching for library and object files, look in directory
13995 DIR. The order in which library files are searched is the same as for
13996 @command{gnatmake}.
13997
13998 @item -nostdinc
13999 @cindex @option{-nostdinc} (@command{gnatxref})
14000 Do not look for sources in the system default directory.
14001
14002 @item -nostdlib
14003 @cindex @option{-nostdlib} (@command{gnatxref})
14004 Do not look for library files in the system default directory.
14005
14006 @item --RTS=@var{rts-path}
14007 @cindex @option{--RTS} (@command{gnatxref})
14008 Specifies the default location of the runtime library. Same meaning as the
14009 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14010
14011 @item ^-d^/DERIVED_TYPES^
14012 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14013 If this switch is set @code{gnatxref} will output the parent type
14014 reference for each matching derived types.
14015
14016 @item ^-f^/FULL_PATHNAME^
14017 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14018 If this switch is set, the output file names will be preceded by their
14019 directory (if the file was found in the search path). If this switch is
14020 not set, the directory will not be printed.
14021
14022 @item ^-g^/IGNORE_LOCALS^
14023 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14024 If this switch is set, information is output only for library-level
14025 entities, ignoring local entities. The use of this switch may accelerate
14026 @code{gnatfind} and @code{gnatxref}.
14027
14028 @item -IDIR
14029 @cindex @option{-IDIR} (@command{gnatxref})
14030 Equivalent to @samp{-aODIR -aIDIR}.
14031
14032 @item -pFILE
14033 @cindex @option{-pFILE} (@command{gnatxref})
14034 Specify a project file to use @xref{Project Files}. These project files are
14035 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
14036 project files, you should use gnatxref through the GNAT driver
14037 (@command{gnat xref -Pproject}).
14038
14039 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14040 project file in the current directory.
14041
14042 If a project file is either specified or found by the tools, then the content
14043 of the source directory and object directory lines are added as if they
14044 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14045 and @samp{^-aO^OBJECT_SEARCH^}.
14046 @item ^-u^/UNUSED^
14047 Output only unused symbols. This may be really useful if you give your
14048 main compilation unit on the command line, as @code{gnatxref} will then
14049 display every unused entity and 'with'ed package.
14050
14051 @ifclear vms
14052 @item -v
14053 Instead of producing the default output, @code{gnatxref} will generate a
14054 @file{tags} file that can be used by vi. For examples how to use this
14055 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14056 to the standard output, thus you will have to redirect it to a file.
14057 @end ifclear
14058
14059 @end table
14060
14061 @noindent
14062 All these switches may be in any order on the command line, and may even
14063 appear after the file names. They need not be separated by spaces, thus
14064 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14065 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14066
14067 @node gnatfind Switches
14068 @section @code{gnatfind} Switches
14069
14070 @noindent
14071 The command line for @code{gnatfind} is:
14072
14073 @smallexample
14074 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14075       [file1 file2 ...]
14076 @end smallexample
14077
14078 @noindent
14079 where
14080
14081 @table @code
14082 @item pattern
14083 An entity will be output only if it matches the regular expression found
14084 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14085
14086 Omitting the pattern is equivalent to specifying @samp{*}, which
14087 will match any entity. Note that if you do not provide a pattern, you
14088 have to provide both a sourcefile and a line.
14089
14090 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14091 for matching purposes. At the current time there is no support for
14092 8-bit codes other than Latin-1, or for wide characters in identifiers.
14093
14094 @item sourcefile
14095 @code{gnatfind} will look for references, bodies or declarations
14096 of symbols referenced in @file{sourcefile}, at line @samp{line}
14097 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14098 for syntax examples.
14099
14100 @item line
14101 is a decimal integer identifying the line number containing
14102 the reference to the entity (or entities) to be located.
14103
14104 @item column
14105 is a decimal integer identifying the exact location on the
14106 line of the first character of the identifier for the
14107 entity reference. Columns are numbered from 1.
14108
14109 @item file1 file2 ...
14110 The search will be restricted to these source files. If none are given, then
14111 the search will be done for every library file in the search path.
14112 These file must appear only after the pattern or sourcefile.
14113
14114 These file names are considered to be regular expressions, so for instance
14115 specifying 'source*.adb' is the same as giving every file in the current
14116 directory whose name starts with 'source' and whose extension is 'adb'.
14117
14118 The location of the spec of the entity will always be displayed, even if it
14119 isn't in one of file1, file2,... The occurrences of the entity in the
14120 separate units of the ones given on the command line will also be displayed.
14121
14122 Note that if you specify at least one file in this part, @code{gnatfind} may
14123 sometimes not be able to find the body of the subprograms...
14124
14125 @end table
14126
14127 @noindent
14128 At least one of 'sourcefile' or 'pattern' has to be present on
14129 the command line.
14130
14131 The following switches are available:
14132 @table @option
14133 @c !sort!
14134
14135 @item ^-a^/ALL_FILES^
14136 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14137 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14138 the read-only files found in the library search path. Otherwise, these files
14139 will be ignored. This option can be used to protect Gnat sources or your own
14140 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14141 much faster, and their output much smaller. Read-only here refers to access
14142 or permission status in the file system for the current user.
14143
14144 @item -aIDIR
14145 @cindex @option{-aIDIR} (@command{gnatfind})
14146 When looking for source files also look in directory DIR. The order in which
14147 source file search is undertaken is the same as for @command{gnatmake}.
14148
14149 @item -aODIR
14150 @cindex @option{-aODIR} (@command{gnatfind})
14151 When searching for library and object files, look in directory
14152 DIR. The order in which library files are searched is the same as for
14153 @command{gnatmake}.
14154
14155 @item -nostdinc
14156 @cindex @option{-nostdinc} (@command{gnatfind})
14157 Do not look for sources in the system default directory.
14158
14159 @item -nostdlib
14160 @cindex @option{-nostdlib} (@command{gnatfind})
14161 Do not look for library files in the system default directory.
14162
14163 @item --RTS=@var{rts-path}
14164 @cindex @option{--RTS} (@command{gnatfind})
14165 Specifies the default location of the runtime library. Same meaning as the
14166 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14167
14168 @item ^-d^/DERIVED_TYPE_INFORMATION^
14169 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14170 If this switch is set, then @code{gnatfind} will output the parent type
14171 reference for each matching derived types.
14172
14173 @item ^-e^/EXPRESSIONS^
14174 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14175 By default, @code{gnatfind} accept the simple regular expression set for
14176 @samp{pattern}. If this switch is set, then the pattern will be
14177 considered as full Unix-style regular expression.
14178
14179 @item ^-f^/FULL_PATHNAME^
14180 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14181 If this switch is set, the output file names will be preceded by their
14182 directory (if the file was found in the search path). If this switch is
14183 not set, the directory will not be printed.
14184
14185 @item ^-g^/IGNORE_LOCALS^
14186 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14187 If this switch is set, information is output only for library-level
14188 entities, ignoring local entities. The use of this switch may accelerate
14189 @code{gnatfind} and @code{gnatxref}.
14190
14191 @item -IDIR
14192 @cindex @option{-IDIR} (@command{gnatfind})
14193 Equivalent to @samp{-aODIR -aIDIR}.
14194
14195 @item -pFILE
14196 @cindex @option{-pFILE} (@command{gnatfind})
14197 Specify a project file (@pxref{Project Files}) to use.
14198 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14199 project file in the current directory.
14200
14201 If a project file is either specified or found by the tools, then the content
14202 of the source directory and object directory lines are added as if they
14203 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14204 @samp{^-aO^/OBJECT_SEARCH^}.
14205
14206 @item ^-r^/REFERENCES^
14207 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14208 By default, @code{gnatfind} will output only the information about the
14209 declaration, body or type completion of the entities. If this switch is
14210 set, the @code{gnatfind} will locate every reference to the entities in
14211 the files specified on the command line (or in every file in the search
14212 path if no file is given on the command line).
14213
14214 @item ^-s^/PRINT_LINES^
14215 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14216 If this switch is set, then @code{gnatfind} will output the content
14217 of the Ada source file lines were the entity was found.
14218
14219 @item ^-t^/TYPE_HIERARCHY^
14220 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14221 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14222 the specified type. It act like -d option but recursively from parent
14223 type to parent type. When this switch is set it is not possible to
14224 specify more than one file.
14225
14226 @end table
14227
14228 @noindent
14229 All these switches may be in any order on the command line, and may even
14230 appear after the file names. They need not be separated by spaces, thus
14231 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14232 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14233
14234 As stated previously, gnatfind will search in every directory in the
14235 search path. You can force it to look only in the current directory if
14236 you specify @code{*} at the end of the command line.
14237
14238 @node Project Files for gnatxref and gnatfind
14239 @section Project Files for @command{gnatxref} and @command{gnatfind}
14240
14241 @noindent
14242 Project files allow a programmer to specify how to compile its
14243 application, where to find sources, etc.  These files are used
14244 @ifclear vms
14245 primarily by the Glide Ada mode, but they can also be used
14246 @end ifclear
14247 by the two tools
14248 @code{gnatxref} and @code{gnatfind}.
14249
14250 A project file name must end with @file{.gpr}. If a single one is
14251 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14252 extract the information from it. If multiple project files are found, none of
14253 them is read, and you have to use the @samp{-p} switch to specify the one
14254 you want to use.
14255
14256 The following lines can be included, even though most of them have default
14257 values which can be used in most cases.
14258 The lines can be entered in any order in the file.
14259 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14260 each line. If you have multiple instances, only the last one is taken into
14261 account.
14262
14263 @table @code
14264 @item src_dir=DIR
14265 [default: @code{"^./^[]^"}]
14266 specifies a directory where to look for source files. Multiple @code{src_dir}
14267 lines can be specified and they will be searched in the order they
14268 are specified.
14269
14270 @item obj_dir=DIR
14271 [default: @code{"^./^[]^"}]
14272 specifies a directory where to look for object and library files. Multiple
14273 @code{obj_dir} lines can be specified, and they will be searched in the order
14274 they are specified
14275
14276 @item comp_opt=SWITCHES
14277 [default: @code{""}]
14278 creates a variable which can be referred to subsequently by using
14279 the @code{$@{comp_opt@}} notation. This is intended to store the default
14280 switches given to @command{gnatmake} and @command{gcc}.
14281
14282 @item bind_opt=SWITCHES
14283 [default: @code{""}]
14284 creates a variable which can be referred to subsequently by using
14285 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14286 switches given to @command{gnatbind}.
14287
14288 @item link_opt=SWITCHES
14289 [default: @code{""}]
14290 creates a variable which can be referred to subsequently by using
14291 the @samp{$@{link_opt@}} notation. This is intended to store the default
14292 switches given to @command{gnatlink}.
14293
14294 @item main=EXECUTABLE
14295 [default: @code{""}]
14296 specifies the name of the executable for the application. This variable can
14297 be referred to in the following lines by using the @samp{$@{main@}} notation.
14298
14299 @ifset vms
14300 @item comp_cmd=COMMAND
14301 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14302 @end ifset
14303 @ifclear vms
14304 @item comp_cmd=COMMAND
14305 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14306 @end ifclear
14307 specifies the command used to compile a single file in the application.
14308
14309 @ifset vms
14310 @item make_cmd=COMMAND
14311 [default: @code{"GNAT MAKE $@{main@}
14312 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14313 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14314 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14315 @end ifset
14316 @ifclear vms
14317 @item make_cmd=COMMAND
14318 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14319  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14320  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14321 @end ifclear
14322 specifies the command used to recompile the whole application.
14323
14324 @item run_cmd=COMMAND
14325 [default: @code{"$@{main@}"}]
14326 specifies the command used to run the application.
14327
14328 @item debug_cmd=COMMAND
14329 [default: @code{"gdb $@{main@}"}]
14330 specifies the command used to debug the application
14331
14332 @end table
14333
14334 @noindent
14335 @command{gnatxref} and @command{gnatfind} only take into account the
14336 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14337
14338 @node Regular Expressions in gnatfind and gnatxref
14339 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14340
14341 @noindent
14342 As specified in the section about @command{gnatfind}, the pattern can be a
14343 regular expression. Actually, there are to set of regular expressions
14344 which are recognized by the program :
14345
14346 @table @code
14347 @item globbing patterns
14348 These are the most usual regular expression. They are the same that you
14349 generally used in a Unix shell command line, or in a DOS session.
14350
14351 Here is a more formal grammar :
14352 @smallexample
14353 @group
14354 @iftex
14355 @leftskip=.5cm
14356 @end iftex
14357 regexp ::= term
14358 term   ::= elmt            -- matches elmt
14359 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14360 term   ::= *               -- any string of 0 or more characters
14361 term   ::= ?               -- matches any character
14362 term   ::= [char @{char@}] -- matches any character listed
14363 term   ::= [char - char]   -- matches any character in range
14364 @end group
14365 @end smallexample
14366
14367 @item full regular expression
14368 The second set of regular expressions is much more powerful. This is the
14369 type of regular expressions recognized by utilities such a @file{grep}.
14370
14371 The following is the form of a regular expression, expressed in Ada
14372 reference manual style BNF is as follows
14373
14374 @smallexample
14375 @iftex
14376 @leftskip=.5cm
14377 @end iftex
14378 @group
14379 regexp ::= term @{| term@} -- alternation (term or term ...)
14380
14381 term ::= item @{item@}     -- concatenation (item then item)
14382
14383 item ::= elmt              -- match elmt
14384 item ::= elmt *            -- zero or more elmt's
14385 item ::= elmt +            -- one or more elmt's
14386 item ::= elmt ?            -- matches elmt or nothing
14387 @end group
14388 @group
14389 elmt ::= nschar            -- matches given character
14390 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14391 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14392 elmt ::= [char - char]     -- matches chars in given range
14393 elmt ::= \ char            -- matches given character
14394 elmt ::= .                 -- matches any single character
14395 elmt ::= ( regexp )        -- parens used for grouping
14396
14397 char ::= any character, including special characters
14398 nschar ::= any character except ()[].*+?^^^
14399 @end group
14400 @end smallexample
14401
14402 Following are a few examples :
14403
14404 @table @samp
14405 @item abcde|fghi
14406 will match any of the two strings 'abcde' and 'fghi'.
14407
14408 @item abc*d
14409 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14410
14411 @item [a-z]+
14412 will match any string which has only lowercase characters in it (and at
14413 least one character
14414
14415 @end table
14416 @end table
14417
14418 @node Examples of gnatxref Usage
14419 @section Examples of @code{gnatxref} Usage
14420
14421 @subsection General Usage
14422
14423 @noindent
14424 For the following examples, we will consider the following units :
14425
14426 @smallexample @c ada
14427 @group
14428 @cartouche
14429 main.ads:
14430 1: with Bar;
14431 2: package Main is
14432 3:     procedure Foo (B : in Integer);
14433 4:     C : Integer;
14434 5: private
14435 6:     D : Integer;
14436 7: end Main;
14437
14438 main.adb:
14439 1: package body Main is
14440 2:     procedure Foo (B : in Integer) is
14441 3:     begin
14442 4:        C := B;
14443 5:        D := B;
14444 6:        Bar.Print (B);
14445 7:        Bar.Print (C);
14446 8:     end Foo;
14447 9: end Main;
14448
14449 bar.ads:
14450 1: package Bar is
14451 2:     procedure Print (B : Integer);
14452 3: end bar;
14453 @end cartouche
14454 @end group
14455 @end smallexample
14456
14457 @table @code
14458
14459 @noindent
14460 The first thing to do is to recompile your application (for instance, in
14461 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14462 the cross-referencing information.
14463 You can then issue any of the following commands:
14464
14465 @item gnatxref main.adb
14466 @code{gnatxref} generates cross-reference information for main.adb
14467 and every unit 'with'ed by main.adb.
14468
14469 The output would be:
14470 @smallexample
14471 @iftex
14472 @leftskip=0cm
14473 @end iftex
14474 B                                                      Type: Integer
14475   Decl: bar.ads           2:22
14476 B                                                      Type: Integer
14477   Decl: main.ads          3:20
14478   Body: main.adb          2:20
14479   Ref:  main.adb          4:13     5:13     6:19
14480 Bar                                                    Type: Unit
14481   Decl: bar.ads           1:9
14482   Ref:  main.adb          6:8      7:8
14483        main.ads           1:6
14484 C                                                      Type: Integer
14485   Decl: main.ads          4:5
14486   Modi: main.adb          4:8
14487   Ref:  main.adb          7:19
14488 D                                                      Type: Integer
14489   Decl: main.ads          6:5
14490   Modi: main.adb          5:8
14491 Foo                                                    Type: Unit
14492   Decl: main.ads          3:15
14493   Body: main.adb          2:15
14494 Main                                                    Type: Unit
14495   Decl: main.ads          2:9
14496   Body: main.adb          1:14
14497 Print                                                   Type: Unit
14498   Decl: bar.ads           2:15
14499   Ref:  main.adb          6:12     7:12
14500 @end smallexample
14501
14502 @noindent
14503 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14504 its body is in main.adb, line 1, column 14 and is not referenced any where.
14505
14506 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14507 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14508
14509 @item gnatxref package1.adb package2.ads
14510 @code{gnatxref} will generates cross-reference information for
14511 package1.adb, package2.ads and any other package 'with'ed by any
14512 of these.
14513
14514 @end table
14515
14516 @ifclear vms
14517 @subsection Using gnatxref with vi
14518
14519 @code{gnatxref} can generate a tags file output, which can be used
14520 directly from @file{vi}. Note that the standard version of @file{vi}
14521 will not work properly with overloaded symbols. Consider using another
14522 free implementation of @file{vi}, such as @file{vim}.
14523
14524 @smallexample
14525 $ gnatxref -v gnatfind.adb > tags
14526 @end smallexample
14527
14528 @noindent
14529 will generate the tags file for @code{gnatfind} itself (if the sources
14530 are in the search path!).
14531
14532 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14533 (replacing @i{entity} by whatever you are looking for), and vi will
14534 display a new file with the corresponding declaration of entity.
14535 @end ifclear
14536
14537 @node Examples of gnatfind Usage
14538 @section Examples of @code{gnatfind} Usage
14539
14540 @table @code
14541
14542 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14543 Find declarations for all entities xyz referenced at least once in
14544 main.adb. The references are search in every library file in the search
14545 path.
14546
14547 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14548 switch is set)
14549
14550 The output will look like:
14551 @smallexample
14552 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14553 ^directory/^[directory]^main.adb:24:10: xyz <= body
14554 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14555 @end smallexample
14556
14557 @noindent
14558 that is to say, one of the entities xyz found in main.adb is declared at
14559 line 12 of main.ads (and its body is in main.adb), and another one is
14560 declared at line 45 of foo.ads
14561
14562 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14563 This is the same command as the previous one, instead @code{gnatfind} will
14564 display the content of the Ada source file lines.
14565
14566 The output will look like:
14567
14568 @smallexample
14569 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14570    procedure xyz;
14571 ^directory/^[directory]^main.adb:24:10: xyz <= body
14572    procedure xyz is
14573 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14574    xyz : Integer;
14575 @end smallexample
14576
14577 @noindent
14578 This can make it easier to find exactly the location your are looking
14579 for.
14580
14581 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14582 Find references to all entities containing an x that are
14583 referenced on line 123 of main.ads.
14584 The references will be searched only in main.ads and foo.adb.
14585
14586 @item gnatfind main.ads:123
14587 Find declarations and bodies for all entities that are referenced on
14588 line 123 of main.ads.
14589
14590 This is the same as @code{gnatfind "*":main.adb:123}.
14591
14592 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14593 Find the declaration for the entity referenced at column 45 in
14594 line 123 of file main.adb in directory mydir. Note that it
14595 is usual to omit the identifier name when the column is given,
14596 since the column position identifies a unique reference.
14597
14598 The column has to be the beginning of the identifier, and should not
14599 point to any character in the middle of the identifier.
14600
14601 @end table
14602
14603 @c *********************************
14604 @node The GNAT Pretty-Printer gnatpp
14605 @chapter The GNAT Pretty-Printer @command{gnatpp}
14606 @findex gnatpp
14607 @cindex Pretty-Printer
14608
14609 @noindent
14610 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14611 for source reformatting / pretty-printing.
14612 It takes an Ada source file as input and generates a reformatted
14613 version as output.
14614 You can specify various style directives via switches; e.g.,
14615 identifier case conventions, rules of indentation, and comment layout.
14616
14617 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14618 tree for the input source and thus requires the input to be syntactically and
14619 semantically legal.
14620 If this condition is not met, @command{gnatpp} will terminate with an
14621 error message; no output file will be generated.
14622
14623 If the compilation unit
14624 contained in the input source depends semantically upon units located
14625 outside the current directory, you have to provide the source search path
14626 when invoking @command{gnatpp}, if these units are contained in files with
14627 names that do not follow the GNAT file naming rules, you have to provide
14628 the configuration file describing the corresponding naming scheme;
14629 see the description of the @command{gnatpp}
14630 switches below. Another possibility is to use a project file and to
14631 call @command{gnatpp} through the @command{gnat} driver
14632
14633 The @command{gnatpp} command has the form
14634
14635 @smallexample
14636 $ gnatpp [@var{switches}] @var{filename}
14637 @end smallexample
14638
14639 @noindent
14640 where
14641 @itemize @bullet
14642 @item
14643 @var{switches} is an optional sequence of switches defining such properties as
14644 the formatting rules, the source search path, and the destination for the
14645 output source file
14646
14647 @item
14648 @var{filename} is the name (including the extension) of the source file to
14649 reformat; ``wildcards'' or several file names on the same gnatpp command are
14650 allowed.  The file name may contain path information; it does not have to
14651 follow the GNAT file naming rules
14652 @end itemize
14653
14654 @menu
14655 * Switches for gnatpp::
14656 * Formatting Rules::
14657 @end menu
14658
14659 @node Switches for gnatpp
14660 @section Switches for @command{gnatpp}
14661
14662 @noindent
14663 The following subsections describe the various switches accepted by
14664 @command{gnatpp}, organized by category.
14665
14666 @ifclear vms
14667 You specify a switch by supplying a name and generally also a value.
14668 In many cases the values for a switch with a given name are incompatible with
14669 each other
14670 (for example the switch that controls the casing of a reserved word may have
14671 exactly one value: upper case, lower case, or
14672 mixed case) and thus exactly one such switch can be in effect for an
14673 invocation of @command{gnatpp}.
14674 If more than one is supplied, the last one is used.
14675 However, some values for the same switch are mutually compatible.
14676 You may supply several such switches to @command{gnatpp}, but then
14677 each must be specified in full, with both the name and the value.
14678 Abbreviated forms (the name appearing once, followed by each value) are
14679 not permitted.
14680 For example, to set
14681 the alignment of the assignment delimiter both in declarations and in
14682 assignment statements, you must write @option{-A2A3}
14683 (or @option{-A2 -A3}), but not @option{-A23}.
14684 @end ifclear
14685
14686 @ifset vms
14687 In many cases the set of options for a given qualifier are incompatible with
14688 each other (for example the qualifier that controls the casing of a reserved
14689 word may have exactly one option, which specifies either upper case, lower
14690 case, or mixed case), and thus exactly one such option can be in effect for
14691 an invocation of @command{gnatpp}.
14692 If more than one is supplied, the last one is used.
14693 However, some qualifiers have options that are mutually compatible,
14694 and then you may then supply several such options when invoking
14695 @command{gnatpp}.
14696 @end ifset
14697
14698 In most cases, it is obvious whether or not the
14699 ^values for a switch with a given name^options for a given qualifier^
14700 are compatible with each other.
14701 When the semantics might not be evident, the summaries below explicitly
14702 indicate the effect.
14703
14704 @menu
14705 * Alignment Control::
14706 * Casing Control::
14707 * Construct Layout Control::
14708 * General Text Layout Control::
14709 * Other Formatting Options::
14710 * Setting the Source Search Path::
14711 * Output File Control::
14712 * Other gnatpp Switches::
14713 @end menu
14714
14715 @node Alignment Control
14716 @subsection Alignment Control
14717 @cindex Alignment control in @command{gnatpp}
14718
14719 @noindent
14720 Programs can be easier to read if certain constructs are vertically aligned.
14721 By default all alignments are set ON.
14722 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14723 OFF, and then use one or more of the other
14724 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14725 to activate alignment for specific constructs.
14726
14727 @table @option
14728 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14729
14730 @ifset vms
14731 @item /ALIGN=ON
14732 Set all alignments to ON
14733 @end ifset
14734
14735 @item ^-A0^/ALIGN=OFF^
14736 Set all alignments to OFF
14737
14738 @item ^-A1^/ALIGN=COLONS^
14739 Align @code{:} in declarations
14740
14741 @item ^-A2^/ALIGN=DECLARATIONS^
14742 Align @code{:=} in initializations in declarations
14743
14744 @item ^-A3^/ALIGN=STATEMENTS^
14745 Align @code{:=} in assignment statements
14746
14747 @item ^-A4^/ALIGN=ARROWS^
14748 Align @code{=>} in associations
14749
14750 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14751 Align @code{at} keywords in the component clauses in record
14752 representation clauses
14753 @end table
14754
14755 @noindent
14756 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14757 is allowed.
14758
14759 @node Casing Control
14760 @subsection Casing Control
14761 @cindex Casing control in @command{gnatpp}
14762
14763 @noindent
14764 @command{gnatpp} allows you to specify the casing for reserved words,
14765 pragma names, attribute designators and identifiers.
14766 For identifiers you may define a
14767 general rule for name casing but also override this rule
14768 via a set of dictionary files.
14769
14770 Three types of casing are supported: lower case, upper case, and mixed case.
14771 Lower and upper case are self-explanatory (but since some letters in
14772 Latin1 and other GNAT-supported character sets
14773 exist only in lower-case form, an upper case conversion will have no
14774 effect on them.)
14775 ``Mixed case'' means that the first letter, and also each letter immediately
14776 following an underscore, are converted to their uppercase forms;
14777 all the other letters are converted to their lowercase forms.
14778
14779 @table @option
14780 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14781 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14782 Attribute designators are lower case
14783
14784 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14785 Attribute designators are upper case
14786
14787 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14788 Attribute designators are mixed case (this is the default)
14789
14790 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14791 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14792 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14793 lower case (this is the default)
14794
14795 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14796 Keywords are upper case
14797
14798 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14799 @item ^-nD^/NAME_CASING=AS_DECLARED^
14800 Name casing for defining occurrences are as they appear in the source file
14801 (this is the default)
14802
14803 @item ^-nU^/NAME_CASING=UPPER_CASE^
14804 Names are in upper case
14805
14806 @item ^-nL^/NAME_CASING=LOWER_CASE^
14807 Names are in lower case
14808
14809 @item ^-nM^/NAME_CASING=MIXED_CASE^
14810 Names are in mixed case
14811
14812 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14813 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14814 Pragma names are lower case
14815
14816 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14817 Pragma names are upper case
14818
14819 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14820 Pragma names are mixed case (this is the default)
14821
14822 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14823 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14824 Use @var{file} as a @emph{dictionary file} that defines
14825 the casing for a set of specified names,
14826 thereby overriding the effect on these names by
14827 any explicit or implicit
14828 ^-n^/NAME_CASING^ switch.
14829 To supply more than one dictionary file,
14830 use ^several @option{-D} switches^a list of files as options^.
14831
14832 @noindent
14833 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14834 to define the casing for the Ada predefined names and
14835 the names declared in the GNAT libraries.
14836
14837 @item ^-D-^/SPECIFIC_CASING^
14838 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14839 Do not use the default dictionary file;
14840 instead, use the casing
14841 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14842 dictionary file(s)
14843 @end table
14844
14845 @noindent
14846 The structure of a dictionary file, and details on the conventions
14847 used in the default dictionary file, are defined in @ref{Name Casing}.
14848
14849 The @option{^-D-^/SPECIFIC_CASING^} and
14850 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14851 compatible.
14852
14853 @node Construct Layout Control
14854 @subsection Construct Layout Control
14855 @cindex Layout control in @command{gnatpp}
14856
14857 @noindent
14858 This group of @command{gnatpp} switches controls the layout of comments and
14859 complex syntactic constructs.  See @ref{Formatting Comments} for details
14860 on their effect.
14861
14862 @table @option
14863 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14864 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14865 All the comments remain unchanged
14866
14867 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14868 GNAT-style comment line indentation (this is the default).
14869
14870 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14871 Reference-manual comment line indentation.
14872
14873 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14874 GNAT-style comment beginning
14875
14876 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14877 Reformat comment blocks
14878
14879 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14880 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14881 GNAT-style layout (this is the default)
14882
14883 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14884 Compact layout
14885
14886 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14887 Uncompact layout
14888
14889 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14890 @item ^-N^/NOTABS^
14891 All the VT characters are removed from the comment text. All the HT characters
14892 are expanded with the sequences of space characters to get to the next tab
14893 stops.
14894
14895 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14896 @item ^--no-separate-is^/NO_SEPARATE_IS^
14897 Do not place the keyword @code{is} on a separate line in a subprogram body in
14898 case if the specification occupies more then one line.
14899
14900 @end table
14901
14902 @ifclear vms
14903 @noindent
14904 The @option{-c1} and @option{-c2} switches are incompatible.
14905 The @option{-c3} and @option{-c4} switches are compatible with each other and
14906 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14907 the other comment formatting switches.
14908
14909 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14910 @end ifclear
14911
14912 @ifset vms
14913 @noindent
14914 For the @option{/COMMENTS_LAYOUT} qualifier:
14915 @itemize @bullet
14916 @item
14917 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14918 @item
14919 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14920 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14921 @end itemize
14922
14923 @noindent
14924 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14925 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14926 @end ifset
14927
14928 @node General Text Layout Control
14929 @subsection General Text Layout Control
14930
14931 @noindent
14932 These switches allow control over line length and indentation.
14933
14934 @table @option
14935 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14936 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14937 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14938
14939 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14940 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14941 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14942
14943 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14944 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14945 Indentation level for continuation lines (relative to the line being
14946 continued), @i{nnn} from 1 .. 9.
14947 The default
14948 value is one less then the (normal) indentation level, unless the
14949 indentation is set to 1 (in which case the default value for continuation
14950 line indentation is also 1)
14951 @end table
14952
14953 @node Other Formatting Options
14954 @subsection Other Formatting Options
14955
14956 @noindent
14957 These switches control the inclusion of missing end/exit labels, and
14958 the indentation level in @b{case} statements.
14959
14960 @table @option
14961 @item ^-e^/NO_MISSED_LABELS^
14962 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14963 Do not insert missing end/exit labels. An end label is the name of
14964 a construct that may optionally be repeated at the end of the
14965 construct's declaration;
14966 e.g., the names of packages, subprograms, and tasks.
14967 An exit label is the name of a loop that may appear as target
14968 of an exit statement within the loop.
14969 By default, @command{gnatpp} inserts these end/exit labels when
14970 they are absent from the original source. This option suppresses such
14971 insertion, so that the formatted source reflects the original.
14972
14973 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14974 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14975 Insert a Form Feed character after a pragma Page.
14976
14977 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14978 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14979 Do not use an additional indentation level for @b{case} alternatives
14980 and variants if there are @i{nnn} or more (the default
14981 value is 10).
14982 If @i{nnn} is 0, an additional indentation level is
14983 used for @b{case} alternatives and variants regardless of their number.
14984 @end table
14985
14986 @node Setting the Source Search Path
14987 @subsection Setting the Source Search Path
14988
14989 @noindent
14990 To define the search path for the input source file, @command{gnatpp}
14991 uses the same switches as the GNAT compiler, with the same effects.
14992
14993 @table @option
14994 @item ^-I^/SEARCH=^@var{dir}
14995 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14996 The same as the corresponding gcc switch
14997
14998 @item ^-I-^/NOCURRENT_DIRECTORY^
14999 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15000 The same as the corresponding gcc switch
15001
15002 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15003 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15004 The same as the corresponding gcc switch
15005
15006 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15007 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15008 The same as the corresponding gcc switch
15009
15010 @end table
15011
15012 @node Output File Control
15013 @subsection Output File Control
15014
15015 @noindent
15016 By default the output is sent to the file whose name is obtained by appending
15017 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15018 (if the file with this name already exists, it is unconditionally overwritten).
15019 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15020 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15021 as output file.
15022 The output may be redirected by the following switches:
15023
15024 @table @option
15025 @item ^-pipe^/STANDARD_OUTPUT^
15026 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15027 Send the output to @code{Standard_Output}
15028
15029 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15030 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15031 Write the output into @var{output_file}.
15032 If @var{output_file} already exists, @command{gnatpp} terminates without
15033 reading or processing the input file.
15034
15035 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15036 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15037 Write the output into @var{output_file}, overwriting the existing file
15038 (if one is present).
15039
15040 @item ^-r^/REPLACE^
15041 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15042 Replace the input source file with the reformatted output, and copy the
15043 original input source into the file whose name is obtained by appending the
15044 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15045 If a file with this name already exists, @command{gnatpp} terminates without
15046 reading or processing the input file.
15047
15048 @item ^-rf^/OVERRIDING_REPLACE^
15049 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15050 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15051 already exists, it is overwritten.
15052
15053 @item ^-rnb^/NO_BACKUP^
15054 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15055 Replace the input source file with the reformatted output without
15056 creating any backup copy of the input source.
15057
15058 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15059 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15060 Specifies the format of the reformatted output file. The @var{xxx}
15061 ^string specified with the switch^option^ may be either
15062 @itemize @bullet
15063 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15064 @item ``@option{^crlf^CRLF^}''
15065 the same as @option{^crlf^CRLF^}
15066 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15067 @item ``@option{^lf^LF^}''
15068 the same as @option{^unix^UNIX^}
15069 @end itemize
15070
15071 @end table
15072
15073 @noindent
15074 Options @option{^-pipe^/STANDARD_OUTPUT^},
15075 @option{^-o^/OUTPUT^} and
15076 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15077 contains only one file to reformat.
15078 Option
15079 @option{^--eol^/END_OF_LINE^}
15080 can not be used together
15081 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15082
15083 @node Other gnatpp Switches
15084 @subsection Other @code{gnatpp} Switches
15085
15086 @noindent
15087 The additional @command{gnatpp} switches are defined in this subsection.
15088
15089 @table @option
15090 @item ^-files @var{filename}^/FILES=@var{output_file}^
15091 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15092 Take the argument source files from the specified file. This file should be an
15093 ordinary textual file containing file names separated by spaces or
15094 line breaks. You can use this switch more then once in the same call to
15095 @command{gnatpp}. You also can combine this switch with explicit list of
15096 files.
15097
15098 @item ^-v^/VERBOSE^
15099 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15100 Verbose mode;
15101 @command{gnatpp} generates version information and then
15102 a trace of the actions it takes to produce or obtain the ASIS tree.
15103
15104 @item ^-w^/WARNINGS^
15105 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15106 Warning mode;
15107 @command{gnatpp} generates a warning whenever it can not provide
15108 a required layout in the result source.
15109 @end table
15110
15111 @node Formatting Rules
15112 @section Formatting Rules
15113
15114 @noindent
15115 The following subsections show how @command{gnatpp} treats ``white space'',
15116 comments, program layout, and name casing.
15117 They provide the detailed descriptions of the switches shown above.
15118
15119 @menu
15120 * White Space and Empty Lines::
15121 * Formatting Comments::
15122 * Construct Layout::
15123 * Name Casing::
15124 @end menu
15125
15126 @node White Space and Empty Lines
15127 @subsection White Space and Empty Lines
15128
15129 @noindent
15130 @command{gnatpp} does not have an option to control space characters.
15131 It will add or remove spaces according to the style illustrated by the
15132 examples in the @cite{Ada Reference Manual}.
15133
15134 The only format effectors
15135 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15136 that will appear in the output file are platform-specific line breaks,
15137 and also format effectors within (but not at the end of) comments.
15138 In particular, each horizontal tab character that is not inside
15139 a comment will be treated as a space and thus will appear in the
15140 output file as zero or more spaces depending on
15141 the reformatting of the line in which it appears.
15142 The only exception is a Form Feed character, which is inserted after a
15143 pragma @code{Page} when @option{-ff} is set.
15144
15145 The output file will contain no lines with trailing ``white space'' (spaces,
15146 format effectors).
15147
15148 Empty lines in the original source are preserved
15149 only if they separate declarations or statements.
15150 In such contexts, a
15151 sequence of two or more empty lines is replaced by exactly one empty line.
15152 Note that a blank line will be removed if it separates two ``comment blocks''
15153 (a comment block is a sequence of whole-line comments).
15154 In order to preserve a visual separation between comment blocks, use an
15155 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15156 Likewise, if for some reason you wish to have a sequence of empty lines,
15157 use a sequence of empty comments instead.
15158
15159 @node Formatting Comments
15160 @subsection Formatting Comments
15161
15162 @noindent
15163 Comments in Ada code are of two kinds:
15164 @itemize @bullet
15165 @item
15166 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15167 ``white space'') on a line
15168
15169 @item
15170 an @emph{end-of-line comment}, which follows some other Ada lexical element
15171 on the same line.
15172 @end itemize
15173
15174 @noindent
15175 The indentation of a whole-line comment is that of either
15176 the preceding or following line in
15177 the formatted source, depending on switch settings as will be described below.
15178
15179 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15180 between the end of the preceding Ada lexical element and the beginning
15181 of the comment as appear in the original source,
15182 unless either the comment has to be split to
15183 satisfy the line length limitation, or else the next line contains a
15184 whole line comment that is considered a continuation of this end-of-line
15185 comment (because it starts at the same position).
15186 In the latter two
15187 cases, the start of the end-of-line comment is moved right to the nearest
15188 multiple of the indentation level.
15189 This may result in a ``line overflow'' (the right-shifted comment extending
15190 beyond the maximum line length), in which case the comment is split as
15191 described below.
15192
15193 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15194 (GNAT-style comment line indentation)
15195 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15196 (reference-manual comment line indentation).
15197 With reference-manual style, a whole-line comment is indented as if it
15198 were a declaration or statement at the same place
15199 (i.e., according to the indentation of the preceding line(s)).
15200 With GNAT style, a whole-line comment that is immediately followed by an
15201 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15202 word @b{begin}, is indented based on the construct that follows it.
15203
15204 For example:
15205 @smallexample @c ada
15206 @cartouche
15207 if A then
15208     null;
15209        -- some comment
15210 else
15211    null;
15212 end if;
15213 @end cartouche
15214 @end smallexample
15215
15216 @noindent
15217 Reference-manual indentation produces:
15218
15219 @smallexample @c ada
15220 @cartouche
15221 if A then
15222    null;
15223    --  some comment
15224 else
15225    null;
15226 end if;
15227 @end cartouche
15228 @end smallexample
15229
15230 @noindent
15231 while GNAT-style indentation produces:
15232
15233 @smallexample @c ada
15234 @cartouche
15235 if A then
15236    null;
15237 --  some comment
15238 else
15239    null;
15240 end if;
15241 @end cartouche
15242 @end smallexample
15243
15244 @noindent
15245 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15246 (GNAT style comment beginning) has the following
15247 effect:
15248
15249 @itemize @bullet
15250 @item
15251 For each whole-line comment that does not end with two hyphens,
15252 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15253 to ensure that there are at least two spaces between these hyphens and the
15254 first non-blank character of the comment.
15255 @end itemize
15256
15257 @noindent
15258 For an end-of-line comment, if in the original source the next line is a
15259 whole-line comment that starts at the same position
15260 as the end-of-line comment,
15261 then the whole-line comment (and all whole-line comments
15262 that follow it and that start at the same position)
15263 will start at this position in the output file.
15264
15265 @noindent
15266 That is, if in the original source we have:
15267
15268 @smallexample @c ada
15269 @cartouche
15270 begin
15271 A := B + C;            --  B must be in the range Low1..High1
15272                        --  C must be in the range Low2..High2
15273              --B+C will be in the range Low1+Low2..High1+High2
15274 X := X + 1;
15275 @end cartouche
15276 @end smallexample
15277
15278 @noindent
15279 Then in the formatted source we get
15280
15281 @smallexample @c ada
15282 @cartouche
15283 begin
15284    A := B + C;            --  B must be in the range Low1..High1
15285                           --  C must be in the range Low2..High2
15286    --  B+C will be in the range Low1+Low2..High1+High2
15287    X := X + 1;
15288 @end cartouche
15289 @end smallexample
15290
15291 @noindent
15292 A comment that exceeds the line length limit will be split.
15293 Unless switch
15294 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15295 the line belongs to a reformattable block, splitting the line generates a
15296 @command{gnatpp} warning.
15297 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15298 comments may be reformatted in typical
15299 word processor style (that is, moving words between lines and putting as
15300 many words in a line as possible).
15301
15302 @node Construct Layout
15303 @subsection Construct Layout
15304
15305 @noindent
15306 In several cases the suggested layout in the Ada Reference Manual includes
15307 an extra level of indentation that many programmers prefer to avoid. The
15308 affected cases include:
15309
15310 @itemize @bullet
15311
15312 @item Record type declaration (RM 3.8)
15313
15314 @item Record representation clause (RM 13.5.1)
15315
15316 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15317
15318 @item Block statement in case if a block has a statement identifier (RM 5.6)
15319 @end itemize
15320
15321 @noindent
15322 In compact mode (when GNAT style layout or compact layout is set),
15323 the pretty printer uses one level of indentation instead
15324 of two. This is achieved in the record definition and record representation
15325 clause cases by putting the @code{record} keyword on the same line as the
15326 start of the declaration or representation clause, and in the block and loop
15327 case by putting the block or loop header on the same line as the statement
15328 identifier.
15329
15330 @noindent
15331 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15332 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15333 layout on the one hand, and uncompact layout
15334 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15335 can be illustrated by the following examples:
15336
15337 @iftex
15338 @cartouche
15339 @multitable @columnfractions .5 .5
15340 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15341
15342 @item
15343 @smallexample @c ada
15344 type q is record
15345    a : integer;
15346    b : integer;
15347 end record;
15348 @end smallexample
15349 @tab
15350 @smallexample @c ada
15351 type q is
15352    record
15353       a : integer;
15354       b : integer;
15355    end record;
15356 @end smallexample
15357
15358 @item
15359 @smallexample @c ada
15360 for q use record
15361    a at 0 range  0 .. 31;
15362    b at 4 range  0 .. 31;
15363 end record;
15364 @end smallexample
15365 @tab
15366 @smallexample @c ada
15367 for q use
15368    record
15369       a at 0 range  0 .. 31;
15370       b at 4 range  0 .. 31;
15371    end record;
15372 @end smallexample
15373
15374 @item
15375 @smallexample @c ada
15376 Block : declare
15377    A : Integer := 3;
15378 begin
15379    Proc (A, A);
15380 end Block;
15381 @end smallexample
15382 @tab
15383 @smallexample @c ada
15384 Block :
15385    declare
15386       A : Integer := 3;
15387    begin
15388       Proc (A, A);
15389    end Block;
15390 @end smallexample
15391
15392 @item
15393 @smallexample @c ada
15394 Clear : for J in 1 .. 10 loop
15395    A (J) := 0;
15396 end loop Clear;
15397 @end smallexample
15398 @tab
15399 @smallexample @c ada
15400 Clear :
15401    for J in 1 .. 10 loop
15402       A (J) := 0;
15403    end loop Clear;
15404 @end smallexample
15405 @end multitable
15406 @end cartouche
15407 @end iftex
15408
15409 @ifnottex
15410 @smallexample
15411 @cartouche
15412 GNAT style, compact layout              Uncompact layout
15413
15414 type q is record                        type q is
15415    a : integer;                            record
15416    b : integer;                               a : integer;
15417 end record;                                   b : integer;
15418                                            end record;
15419
15420 for q use record                        for q use
15421    a at 0 range  0 .. 31;                  record
15422    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15423 end record;                                   b at 4 range  0 .. 31;
15424                                            end record;
15425
15426 Block : declare                         Block :
15427    A : Integer := 3;                       declare
15428 begin                                         A : Integer := 3;
15429    Proc (A, A);                            begin
15430 end Block;                                    Proc (A, A);
15431                                            end Block;
15432
15433 Clear : for J in 1 .. 10 loop           Clear :
15434    A (J) := 0;                             for J in 1 .. 10 loop
15435 end loop Clear;                               A (J) := 0;
15436                                            end loop Clear;
15437 @end cartouche
15438 @end smallexample
15439 @end ifnottex
15440
15441 @noindent
15442 A further difference between GNAT style layout and compact layout is that
15443 GNAT style layout inserts empty lines as separation for
15444 compound statements, return statements and bodies.
15445
15446 @node Name Casing
15447 @subsection Name Casing
15448
15449 @noindent
15450 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15451 the same casing as the corresponding defining identifier.
15452
15453 You control the casing for defining occurrences via the
15454 @option{^-n^/NAME_CASING^} switch.
15455 @ifclear vms
15456 With @option{-nD} (``as declared'', which is the default),
15457 @end ifclear
15458 @ifset vms
15459 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15460 @end ifset
15461 defining occurrences appear exactly as in the source file
15462 where they are declared.
15463 The other ^values for this switch^options for this qualifier^ ---
15464 @option{^-nU^UPPER_CASE^},
15465 @option{^-nL^LOWER_CASE^},
15466 @option{^-nM^MIXED_CASE^} ---
15467 result in
15468 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15469 If @command{gnatpp} changes the casing of a defining
15470 occurrence, it analogously changes the casing of all the
15471 usage occurrences of this name.
15472
15473 If the defining occurrence of a name is not in the source compilation unit
15474 currently being processed by @command{gnatpp}, the casing of each reference to
15475 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15476 switch (subject to the dictionary file mechanism described below).
15477 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15478 had affected the
15479 casing for the defining occurrence of the name.
15480
15481 Some names may need to be spelled with casing conventions that are not
15482 covered by the upper-, lower-, and mixed-case transformations.
15483 You can arrange correct casing by placing such names in a
15484 @emph{dictionary file},
15485 and then supplying a @option{^-D^/DICTIONARY^} switch.
15486 The casing of names from dictionary files overrides
15487 any @option{^-n^/NAME_CASING^} switch.
15488
15489 To handle the casing of Ada predefined names and the names from GNAT libraries,
15490 @command{gnatpp} assumes a default dictionary file.
15491 The name of each predefined entity is spelled with the same casing as is used
15492 for the entity in the @cite{Ada Reference Manual}.
15493 The name of each entity in the GNAT libraries is spelled with the same casing
15494 as is used in the declaration of that entity.
15495
15496 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15497 default dictionary file.
15498 Instead, the casing for predefined and GNAT-defined names will be established
15499 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15500 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15501 will appear as just shown,
15502 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15503 To ensure that even such names are rendered in uppercase,
15504 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15505 (or else, less conveniently, place these names in upper case in a dictionary
15506 file).
15507
15508 A dictionary file is
15509 a plain text file; each line in this file can be either a blank line
15510 (containing only space characters and ASCII.HT characters), an Ada comment
15511 line, or the specification of exactly one @emph{casing schema}.
15512
15513 A casing schema is a string that has the following syntax:
15514
15515 @smallexample
15516 @cartouche
15517   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15518
15519   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15520 @end cartouche
15521 @end smallexample
15522
15523 @noindent
15524 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15525 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15526
15527 The casing schema string can be followed by white space and/or an Ada-style
15528 comment; any amount of white space is allowed before the string.
15529
15530 If a dictionary file is passed as
15531 @ifclear vms
15532 the value of a @option{-D@var{file}} switch
15533 @end ifclear
15534 @ifset vms
15535 an option to the @option{/DICTIONARY} qualifier
15536 @end ifset
15537 then for every
15538 simple name and every identifier, @command{gnatpp} checks if the dictionary
15539 defines the casing for the name or for some of its parts (the term ``subword''
15540 is used below to denote the part of a name which is delimited by ``_'' or by
15541 the beginning or end of the word and which does not contain any ``_'' inside):
15542
15543 @itemize @bullet
15544 @item
15545 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15546 the casing defined by the dictionary; no subwords are checked for this word
15547
15548 @item
15549 for every subword @command{gnatpp} checks if the dictionary contains the
15550 corresponding string of the form @code{*@var{simple_identifier}*},
15551 and if it does, the casing of this @var{simple_identifier} is used
15552 for this subword
15553
15554 @item
15555 if the whole name does not contain any ``_'' inside, and if for this name
15556 the dictionary contains two entries - one of the form @var{identifier},
15557 and another - of the form *@var{simple_identifier}*, then the first one
15558 is applied to define the casing of this name
15559
15560 @item
15561 if more than one dictionary file is passed as @command{gnatpp} switches, each
15562 dictionary adds new casing exceptions and overrides all the existing casing
15563 exceptions set by the previous dictionaries
15564
15565 @item
15566 when @command{gnatpp} checks if the word or subword is in the dictionary,
15567 this check is not case sensitive
15568 @end itemize
15569
15570 @noindent
15571 For example, suppose we have the following source to reformat:
15572
15573 @smallexample @c ada
15574 @cartouche
15575 procedure test is
15576    name1 : integer := 1;
15577    name4_name3_name2 : integer := 2;
15578    name2_name3_name4 : Boolean;
15579    name1_var : Float;
15580 begin
15581    name2_name3_name4 := name4_name3_name2 > name1;
15582 end;
15583 @end cartouche
15584 @end smallexample
15585
15586 @noindent
15587 And suppose we have two dictionaries:
15588
15589 @smallexample
15590 @cartouche
15591 @i{dict1:}
15592    NAME1
15593    *NaMe3*
15594    *Name1*
15595 @end cartouche
15596
15597 @cartouche
15598 @i{dict2:}
15599   *NAME3*
15600 @end cartouche
15601 @end smallexample
15602
15603 @noindent
15604 If @command{gnatpp} is called with the following switches:
15605
15606 @smallexample
15607 @ifclear vms
15608 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15609 @end ifclear
15610 @ifset vms
15611 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15612 @end ifset
15613 @end smallexample
15614
15615 @noindent
15616 then we will get the following name casing in the @command{gnatpp} output:
15617
15618 @smallexample @c ada
15619 @cartouche
15620 procedure Test is
15621    NAME1             : Integer := 1;
15622    Name4_NAME3_Name2 : Integer := 2;
15623    Name2_NAME3_Name4 : Boolean;
15624    Name1_Var         : Float;
15625 begin
15626    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15627 end Test;
15628 @end cartouche
15629 @end smallexample
15630
15631 @c *********************************
15632 @node The GNAT Metric Tool gnatmetric
15633 @chapter The GNAT Metric Tool @command{gnatmetric}
15634 @findex gnatmetric
15635 @cindex Metric tool
15636
15637 @noindent
15638 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15639 for computing various program metrics.
15640 It takes an Ada source file as input and generates a file containing the
15641 metrics data as output. Various switches control which
15642 metrics are computed and output.
15643
15644 @command{gnatmetric} generates and uses the ASIS
15645 tree for the input source and thus requires the input to be syntactically and
15646 semantically legal.
15647 If this condition is not met, @command{gnatmetric} will generate
15648 an error message; no metric information for this file will be
15649 computed and reported.
15650
15651 If the compilation unit contained in the input source depends semantically
15652 upon units in files located outside the current directory, you have to provide
15653 the source search path when invoking @command{gnatmetric}.
15654 If it depends semantically upon units that are contained
15655 in files with names that do not follow the GNAT file naming rules, you have to
15656 provide the configuration file describing the corresponding naming scheme (see
15657 the description of the @command{gnatmetric} switches below.)
15658 Alternatively, you may use a project file and invoke @command{gnatmetric}
15659 through the @command{gnat} driver.
15660
15661
15662 The @command{gnatmetric} command has the form
15663
15664 @smallexample
15665 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
15666 @end smallexample
15667
15668 @noindent
15669 where
15670 @itemize @bullet
15671 @item
15672 @i{switches} specify the metrics to compute and define the destination for
15673 the output
15674
15675 @item
15676 Each @i{filename} is the name (including the extension) of a source
15677 file to process. ``Wildcards'' are allowed, and
15678 the file name may contain path information.
15679 If no @i{filename} is supplied, then the @i{switches} list must contain
15680 at least one
15681 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15682 Including both a @option{-files} switch and one or more
15683 @i{filename} arguments is permitted.
15684
15685 @item
15686 @i{-cargs gcc_switches} is a list of switches for
15687 @command{gcc}. They will be passed on to all compiler invocations made by
15688 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15689 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15690 and use the @option{-gnatec} switch to set the configuration file.
15691 @end itemize
15692
15693 @menu
15694 * Switches for gnatmetric::
15695 @end menu
15696
15697 @node Switches for gnatmetric
15698 @section Switches for @command{gnatmetric}
15699
15700 @noindent
15701 The following subsections describe the various switches accepted by
15702 @command{gnatmetric}, organized by category.
15703
15704 @menu
15705 * Output Files Control::
15706 * Disable Metrics For Local Units::
15707 * Line Metrics Control::
15708 * Syntax Metrics Control::
15709 * Complexity Metrics Control::
15710 * Other gnatmetric Switches::
15711 @end menu
15712
15713 @node Output Files Control
15714 @subsection Output File Control
15715 @cindex Output file control in @command{gnatmetric}
15716
15717 @noindent
15718 @command{gnatmetric} has two output formats. It can generate a
15719 textual (human-readable) form, and also XML. By default only textual
15720 output is generated.
15721
15722 When generating the output in textual form, @command{gnatmetric} creates
15723 for each Ada source file a corresponding text file
15724 containing the computed metrics. By default, this file
15725 is placed in the same directory as where the source file is located, and
15726 its name is obtained
15727 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15728 input file.
15729
15730 All the output information generated in XML format is placed in a single
15731 file. By default this file is placed in the current directory and has the
15732 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15733
15734 Some of the computed metrics are summed over the units passed to
15735 @command{gnatmetric}; for example, the total number of lines of code.
15736 By default this information is sent to @file{stdout}, but a file
15737 can be specified with the @option{-og} switch.
15738
15739 The following switches control the @command{gnatmetric} output:
15740
15741 @table @option
15742 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15743 @item ^-x^/XML^
15744 Generate the XML output
15745
15746 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15747 @item ^-nt^/NO_TEXT^
15748 Do not generate the output in text form (implies @option{^-x^/XML^})
15749
15750 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15751 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15752 Put textual files with detailed metrics into @var{output_dir}
15753
15754 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15755 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15756 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15757 in the name of the output file.
15758
15759 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15760 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15761 Put global metrics into @var{file_name}
15762
15763 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15764 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15765 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15766
15767 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15768 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15769 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15770 output includes the name(s) of the Ada source file(s) from which the metrics
15771 are computed.  By default each name includes the absolute path. The
15772 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15773 to exclude all directory information from the file names that are output.)
15774
15775 @end table
15776
15777 @node Disable Metrics For Local Units
15778 @subsection Disable Metrics For Local Units
15779 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15780
15781 @noindent
15782 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15783 one compilation
15784 unit per one source file. It computes line metrics for the whole source
15785 file, and it also computes syntax
15786 and complexity metrics for the file's outermost unit.
15787
15788 By default, @command{gnatmetric} will also compute all metrics for certain
15789 kinds of locally declared program units:
15790
15791 @itemize @bullet
15792 @item
15793 subprogram (and generic subprogram) bodies;
15794
15795 @item
15796 package (and generic package) specifications and bodies;
15797
15798 @item
15799 task object and type specifications and bodies;
15800
15801 @item
15802 protected object and type specifications and bodies.
15803 @end itemize
15804
15805 @noindent
15806 These kinds of entities will be referred to as
15807 @emph{eligible local program units}, or simply @emph{eligible local units},
15808 @cindex Eligible local unit (for @command{gnatmetric})
15809 in the discussion below.
15810
15811 Note that a subprogram declaration, generic instantiation,
15812 or renaming declaration only receives metrics
15813 computation when it appear as the outermost entity
15814 in a source file.
15815
15816 Suppression of metrics computation for eligible local units can be
15817 obtained via the following switch:
15818
15819 @table @option
15820 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15821 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15822 Do not compute detailed metrics for eligible local program units
15823
15824 @end table
15825
15826 @node Line Metrics Control
15827 @subsection Line Metrics Control
15828 @cindex Line metrics control in @command{gnatmetric}
15829
15830 @noindent
15831 For any (legal) source file, and for each of its
15832 eligible local program units, @command{gnatmetric} computes the following
15833 metrics:
15834
15835 @itemize @bullet
15836 @item
15837 the total number of lines;
15838
15839 @item
15840 the total number of code lines (i.e., non-blank lines that are not comments)
15841
15842 @item
15843 the number of comment lines
15844
15845 @item
15846 the number of code lines containing end-of-line comments;
15847
15848 @item
15849 the number of empty lines and lines containing only space characters and/or
15850 format effectors (blank lines)
15851
15852 @end itemize
15853
15854 If @command{gnatmetric} is invoked on more than one source file, it sums the
15855 values of the line metrics for all the files being processed and then
15856 generates the cumulative results.
15857
15858 By default, all the line metrics are computed and reported. You can use the
15859 following switches to select the specific line metrics to be computed and
15860 reported (if any of these parameters is set, only explicitly specified line
15861 metrics are computed).
15862
15863 @table @option
15864 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15865 @item ^-la^/LINES_ALL^
15866 The number of all lines
15867
15868 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15869 @item ^-lcode^/CODE_LINES^
15870 The number of code lines
15871
15872 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15873 @item ^-lcomm^/COMENT_LINES^
15874 The number of comment lines
15875
15876 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15877 @item ^-leol^/MIXED_CODE_COMMENTS^
15878 The number of code lines containing
15879 end-of-line comments
15880
15881 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15882 @item ^-lb^/BLANK_LINES^
15883 The number of blank lines
15884
15885 @end table
15886
15887
15888 @node Syntax Metrics Control
15889 @subsection Syntax Metrics Control
15890 @cindex Syntax metrics control in @command{gnatmetric}
15891
15892 @noindent
15893 @command{gnatmetric} computes various syntactic metrics for the
15894 outermost unit and for each eligible local unit:
15895
15896 @table @emph
15897 @item LSLOC (``Logical Source Lines Of Code'')
15898 The total number of declarations and the total number of statements
15899
15900 @item Maximal static nesting level of inner program units
15901 According to
15902 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15903 package, a task unit, a protected unit, a
15904 protected entry, a generic unit, or an explicitly declared subprogram other
15905 than an enumeration literal.''
15906
15907 @item Maximal nesting level of composite syntactic constructs
15908 This corresponds to the notion of the
15909 maximum nesting level in the GNAT built-in style checks
15910 (@pxref{Style Checking})
15911 @end table
15912
15913 @noindent
15914 For the outermost unit in the file, @command{gnatmetric} additionally computes
15915 the following metrics:
15916
15917 @table @emph
15918 @item Public subprograms
15919 This metric is computed for package specifications. It is the
15920 number of subprograms and generic subprograms declared in the visible
15921 part (including in nested packages, protected objects, and
15922 protected types).
15923
15924 @item All subprograms
15925 This metric is computed for bodies and subunits. The
15926 metric is equal to a total number of subprogram bodies in the compilation
15927 unit.
15928 Neither generic instantiations nor renamings-as-a-body nor body stubs
15929 are counted. Any subprogram body is counted, independently of its nesting
15930 level and enclosing constructs. Generic bodies and bodies of protected
15931 subprograms are counted in the same way as ``usual'' subprogram bodies.
15932
15933 @item Public types
15934 This metric is computed for package specifications and
15935 generic package declarations. It is the total number of types
15936 that can be referenced from outside this compilation unit, plus the
15937 number of types from all the visible parts of all the visible generic packages.
15938 Generic formal types are not counted.  Only types, not subtypes,
15939 are included.
15940
15941 @noindent
15942 Along with the total number of public types, the following
15943 types are counted and reported separately:
15944
15945 @itemize @bullet
15946 @item
15947 Abstract types
15948
15949 @item
15950 Root tagged types (abstract, non-abstract, private, non-private). Type
15951 extensions are @emph{not} counted
15952
15953 @item
15954 Private types (including private extensions)
15955
15956 @item
15957 Task types
15958
15959 @item
15960 Protected types
15961
15962 @end itemize
15963
15964 @item All types
15965 This metric is computed for any compilation unit. It is equal to the total
15966 number of the declarations of different types given in the compilation unit.
15967 The private and the corresponding full type declaration are counted as one
15968 type declaration. Incomplete type declarations and generic formal types
15969 are not counted.
15970 No distinction is made among different kinds of types (abstract,
15971 private etc.); the total number of types is computed and reported.
15972
15973 @end table
15974
15975 @noindent
15976 By default, all the syntax metrics are computed and reported. You can use the
15977 following switches to select specific syntax metrics;
15978 if any of these is set, only the explicitly specified metrics are computed.
15979
15980 @table @option
15981 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
15982 @item ^-ed^/DECLARATION_TOTAL^
15983 The total number of declarations
15984
15985 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
15986 @item ^-es^/STATEMENT_TOTAL^
15987 The total number of statements
15988
15989 @cindex @option{^-eps^/^} (@command{gnatmetric})
15990 @item ^-eps^/INT_SUBPROGRAMS^
15991 The number of public subprograms in a compilation unit
15992
15993 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
15994 @item ^-eas^/SUBPROGRAMS_ALL^
15995 The number of all the subprograms in a compilation unit
15996
15997 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
15998 @item ^-ept^/INT_TYPES^
15999 The number of public types in a compilation unit
16000
16001 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
16002 @item ^-eat^/TYPES_ALL^
16003 The number of all the types in a compilation unit
16004
16005 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
16006 @item ^-enu^/PROGRAM_NESTING_MAX^
16007 The maximal program unit nesting level
16008
16009 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
16010 @item ^-ec^/CONSTRUCT_NESTING_MAX^
16011 The maximal construct nesting level
16012
16013 @end table
16014
16015 @node Complexity Metrics Control
16016 @subsection Complexity Metrics Control
16017 @cindex Complexity metrics control in @command{gnatmetric}
16018
16019 @noindent
16020 For a program unit that is an executable body (a subprogram body (including
16021 generic bodies), task body, entry body or a package body containing
16022 its own statement sequence ) @command{gnatmetric} computes the following
16023 complexity metrics:
16024
16025 @itemize @bullet
16026 @item
16027 McCabe cyclomatic complexity;
16028
16029 @item
16030 McCabe essential complexity;
16031
16032 @item
16033 maximal loop nesting level
16034
16035 @end itemize
16036
16037 @noindent
16038 The McCabe complexity metrics are defined
16039 in @url{www.mccabe.com/pdf/nist235r.pdf}
16040
16041 According to McCabe, both control statements and short-circuit control forms
16042 should be taken into account when computing cyclomatic complexity. For each
16043 body, we compute three metric values:
16044
16045 @itemize @bullet
16046 @item
16047 the complexity introduced by control
16048 statements only, without taking into account short-circuit forms,
16049
16050 @item
16051 the complexity introduced by short-circuit control forms only, and
16052
16053 @item
16054 the total
16055 cyclomatic complexity, which is the sum of these two values.
16056 @end itemize
16057
16058 @noindent
16059 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16060 the code in the exception handlers and in all the nested program units.
16061
16062 By default, all the complexity metrics are computed and reported.
16063 For more finely-grained control you can use
16064 the following switches:
16065
16066 @table @option
16067 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16068
16069 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
16070 Do not compute the McCabe Cyclomatic Complexity
16071
16072 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
16073 Do not compute the Essential Complexity
16074
16075 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
16076 Do not compute maximal loop nesting level
16077
16078 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
16079 Do not consider @code{exit} statements as @code{goto}s when
16080 computing Essential Complexity
16081
16082 @end table
16083
16084 @node Other gnatmetric Switches
16085 @subsection Other @code{gnatmetric} Switches
16086
16087 @noindent
16088 Additional @command{gnatmetric} switches are as follows:
16089
16090 @table @option
16091 @item ^-files @var{filename}^/FILES=@var{filename}^
16092 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16093 Take the argument source files from the specified file. This file should be an
16094 ordinary textual file containing file names separated by spaces or
16095 line breaks. You can use this switch more then once in the same call to
16096 @command{gnatmetric}. You also can combine this switch with
16097 an explicit list of files.
16098
16099 @item ^-v^/VERBOSE^
16100 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16101 Verbose mode;
16102 @command{gnatmetric} generates version information and then
16103 a trace of sources being processed.
16104
16105 @item ^-dv^/DEBUG_OUTPUT^
16106 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16107 Debug mode;
16108 @command{gnatmetric} generates various messages useful to understand what
16109 happens during the metrics computation
16110
16111 @item ^-q^/QUIET^
16112 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16113 Quiet mode.
16114 @end table
16115
16116 @c ***********************************
16117 @node File Name Krunching Using gnatkr
16118 @chapter File Name Krunching Using @code{gnatkr}
16119 @findex gnatkr
16120
16121 @noindent
16122 This chapter discusses the method used by the compiler to shorten
16123 the default file names chosen for Ada units so that they do not
16124 exceed the maximum length permitted. It also describes the
16125 @code{gnatkr} utility that can be used to determine the result of
16126 applying this shortening.
16127 @menu
16128 * About gnatkr::
16129 * Using gnatkr::
16130 * Krunching Method::
16131 * Examples of gnatkr Usage::
16132 @end menu
16133
16134 @node About gnatkr
16135 @section About @code{gnatkr}
16136
16137 @noindent
16138 The default file naming rule in GNAT
16139 is that the file name must be derived from
16140 the unit name. The exact default rule is as follows:
16141 @itemize @bullet
16142 @item
16143 Take the unit name and replace all dots by hyphens.
16144 @item
16145 If such a replacement occurs in the
16146 second character position of a name, and the first character is
16147 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16148 ^~ (tilde)^$ (dollar sign)^
16149 instead of a minus.
16150 @end itemize
16151 The reason for this exception is to avoid clashes
16152 with the standard names for children of System, Ada, Interfaces,
16153 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16154 respectively.
16155
16156 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16157 switch of the compiler activates a ``krunching''
16158 circuit that limits file names to nn characters (where nn is a decimal
16159 integer). For example, using OpenVMS,
16160 where the maximum file name length is
16161 39, the value of nn is usually set to 39, but if you want to generate
16162 a set of files that would be usable if ported to a system with some
16163 different maximum file length, then a different value can be specified.
16164 The default value of 39 for OpenVMS need not be specified.
16165
16166 The @code{gnatkr} utility can be used to determine the krunched name for
16167 a given file, when krunched to a specified maximum length.
16168
16169 @node Using gnatkr
16170 @section Using @code{gnatkr}
16171
16172 @noindent
16173 The @code{gnatkr} command has the form
16174
16175 @ifclear vms
16176 @smallexample
16177 $ gnatkr @var{name} [@var{length}]
16178 @end smallexample
16179 @end ifclear
16180
16181 @ifset vms
16182 @smallexample
16183 $ gnatkr @var{name} /COUNT=nn
16184 @end smallexample
16185 @end ifset
16186
16187 @noindent
16188 @var{name} is the uncrunched file name, derived from the name of the unit
16189 in the standard manner described in the previous section (i.e. in particular
16190 all dots are replaced by hyphens). The file name may or may not have an
16191 extension (defined as a suffix of the form period followed by arbitrary
16192 characters other than period). If an extension is present then it will
16193 be preserved in the output. For example, when krunching @file{hellofile.ads}
16194 to eight characters, the result will be hellofil.ads.
16195
16196 Note: for compatibility with previous versions of @code{gnatkr} dots may
16197 appear in the name instead of hyphens, but the last dot will always be
16198 taken as the start of an extension. So if @code{gnatkr} is given an argument
16199 such as @file{Hello.World.adb} it will be treated exactly as if the first
16200 period had been a hyphen, and for example krunching to eight characters
16201 gives the result @file{hellworl.adb}.
16202
16203 Note that the result is always all lower case (except on OpenVMS where it is
16204 all upper case). Characters of the other case are folded as required.
16205
16206 @var{length} represents the length of the krunched name. The default
16207 when no argument is given is ^8^39^ characters. A length of zero stands for
16208 unlimited, in other words do not chop except for system files where the
16209 implied crunching length is always eight characters.
16210
16211 @noindent
16212 The output is the krunched name. The output has an extension only if the
16213 original argument was a file name with an extension.
16214
16215 @node Krunching Method
16216 @section Krunching Method
16217
16218 @noindent
16219 The initial file name is determined by the name of the unit that the file
16220 contains. The name is formed by taking the full expanded name of the
16221 unit and replacing the separating dots with hyphens and
16222 using ^lowercase^uppercase^
16223 for all letters, except that a hyphen in the second character position is
16224 replaced by a ^tilde^dollar sign^ if the first character is
16225 ^a, i, g, or s^A, I, G, or S^.
16226 The extension is @code{.ads} for a
16227 specification and @code{.adb} for a body.
16228 Krunching does not affect the extension, but the file name is shortened to
16229 the specified length by following these rules:
16230
16231 @itemize @bullet
16232 @item
16233 The name is divided into segments separated by hyphens, tildes or
16234 underscores and all hyphens, tildes, and underscores are
16235 eliminated. If this leaves the name short enough, we are done.
16236
16237 @item
16238 If the name is too long, the longest segment is located (left-most
16239 if there are two of equal length), and shortened by dropping
16240 its last character. This is repeated until the name is short enough.
16241
16242 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16243 to fit the name into 8 characters as required by some operating systems.
16244
16245 @smallexample
16246 our-strings-wide_fixed 22
16247 our strings wide fixed 19
16248 our string  wide fixed 18
16249 our strin   wide fixed 17
16250 our stri    wide fixed 16
16251 our stri    wide fixe  15
16252 our str     wide fixe  14
16253 our str     wid  fixe  13
16254 our str     wid  fix   12
16255 ou  str     wid  fix   11
16256 ou  st      wid  fix   10
16257 ou  st      wi   fix   9
16258 ou  st      wi   fi    8
16259 Final file name: oustwifi.adb
16260 @end smallexample
16261
16262 @item
16263 The file names for all predefined units are always krunched to eight
16264 characters. The krunching of these predefined units uses the following
16265 special prefix replacements:
16266
16267 @table @file
16268 @item ada-
16269 replaced by @file{^a^A^-}
16270
16271 @item gnat-
16272 replaced by @file{^g^G^-}
16273
16274 @item interfaces-
16275 replaced by @file{^i^I^-}
16276
16277 @item system-
16278 replaced by @file{^s^S^-}
16279 @end table
16280
16281 These system files have a hyphen in the second character position. That
16282 is why normal user files replace such a character with a
16283 ^tilde^dollar sign^, to
16284 avoid confusion with system file names.
16285
16286 As an example of this special rule, consider
16287 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16288
16289 @smallexample
16290 ada-strings-wide_fixed 22
16291 a-  strings wide fixed 18
16292 a-  string  wide fixed 17
16293 a-  strin   wide fixed 16
16294 a-  stri    wide fixed 15
16295 a-  stri    wide fixe  14
16296 a-  str     wide fixe  13
16297 a-  str     wid  fixe  12
16298 a-  str     wid  fix   11
16299 a-  st      wid  fix   10
16300 a-  st      wi   fix   9
16301 a-  st      wi   fi    8
16302 Final file name: a-stwifi.adb
16303 @end smallexample
16304 @end itemize
16305
16306 Of course no file shortening algorithm can guarantee uniqueness over all
16307 possible unit names, and if file name krunching is used then it is your
16308 responsibility to ensure that no name clashes occur. The utility
16309 program @code{gnatkr} is supplied for conveniently determining the
16310 krunched name of a file.
16311
16312 @node Examples of gnatkr Usage
16313 @section Examples of @code{gnatkr} Usage
16314
16315 @smallexample
16316 @iftex
16317 @leftskip=0cm
16318 @end iftex
16319 @ifclear vms
16320 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16321 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16322 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16323 $ gnatkr grandparent-parent-child     --> grparchi
16324 @end ifclear
16325 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16326 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16327 @end smallexample
16328
16329 @node Preprocessing Using gnatprep
16330 @chapter Preprocessing Using @code{gnatprep}
16331 @findex gnatprep
16332
16333 @noindent
16334 The @code{gnatprep} utility provides
16335 a simple preprocessing capability for Ada programs.
16336 It is designed for use with GNAT, but is not dependent on any special
16337 features of GNAT.
16338
16339 @menu
16340 * Using gnatprep::
16341 * Switches for gnatprep::
16342 * Form of Definitions File::
16343 * Form of Input Text for gnatprep::
16344 @end menu
16345
16346 @node Using gnatprep
16347 @section Using @code{gnatprep}
16348
16349 @noindent
16350 To call @code{gnatprep} use
16351
16352 @smallexample
16353 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16354 @end smallexample
16355
16356 @noindent
16357 where
16358 @table @code
16359 @item infile
16360 is the full name of the input file, which is an Ada source
16361 file containing preprocessor directives.
16362
16363 @item outfile
16364 is the full name of the output file, which is an Ada source
16365 in standard Ada form. When used with GNAT, this file name will
16366 normally have an ads or adb suffix.
16367
16368 @item deffile
16369 is the full name of a text file containing definitions of
16370 symbols to be referenced by the preprocessor. This argument is
16371 optional, and can be replaced by the use of the @option{-D} switch.
16372
16373 @item switches
16374 is an optional sequence of switches as described in the next section.
16375 @end table
16376
16377 @node Switches for gnatprep
16378 @section Switches for @code{gnatprep}
16379
16380 @table @option
16381 @c !sort!
16382
16383 @item ^-b^/BLANK_LINES^
16384 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16385 Causes both preprocessor lines and the lines deleted by
16386 preprocessing to be replaced by blank lines in the output source file,
16387 preserving line numbers in the output file.
16388
16389 @item ^-c^/COMMENTS^
16390 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16391 Causes both preprocessor lines and the lines deleted
16392 by preprocessing to be retained in the output source as comments marked
16393 with the special string @code{"--! "}. This option will result in line numbers
16394 being preserved in the output file.
16395
16396 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16397 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16398 Defines a new symbol, associated with value. If no value is given on the
16399 command line, then symbol is considered to be @code{True}. This switch
16400 can be used in place of a definition file.
16401
16402 @ifset vms
16403 @item /REMOVE
16404 @cindex @option{/REMOVE} (@command{gnatprep})
16405 This is the default setting which causes lines deleted by preprocessing
16406 to be entirely removed from the output file.
16407 @end ifset
16408
16409 @item ^-r^/REFERENCE^
16410 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16411 Causes a @code{Source_Reference} pragma to be generated that
16412 references the original input file, so that error messages will use
16413 the file name of this original file. The use of this switch implies
16414 that preprocessor lines are not to be removed from the file, so its
16415 use will force @option{^-b^/BLANK_LINES^} mode if
16416 @option{^-c^/COMMENTS^}
16417 has not been specified explicitly.
16418
16419 Note that if the file to be preprocessed contains multiple units, then
16420 it will be necessary to @code{gnatchop} the output file from
16421 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16422 in the preprocessed file, it will be respected by
16423 @code{gnatchop ^-r^/REFERENCE^}
16424 so that the final chopped files will correctly refer to the original
16425 input source file for @code{gnatprep}.
16426
16427 @item ^-s^/SYMBOLS^
16428 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16429 Causes a sorted list of symbol names and values to be
16430 listed on the standard output file.
16431
16432 @item ^-u^/UNDEFINED^
16433 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16434 Causes undefined symbols to be treated as having the value FALSE in the context
16435 of a preprocessor test. In the absence of this option, an undefined symbol in
16436 a @code{#if} or @code{#elsif} test will be treated as an error.
16437
16438 @end table
16439
16440 @ifclear vms
16441 @noindent
16442 Note: if neither @option{-b} nor @option{-c} is present,
16443 then preprocessor lines and
16444 deleted lines are completely removed from the output, unless -r is
16445 specified, in which case -b is assumed.
16446 @end ifclear
16447
16448 @node Form of Definitions File
16449 @section Form of Definitions File
16450
16451 @noindent
16452 The definitions file contains lines of the form
16453
16454 @smallexample
16455 symbol := value
16456 @end smallexample
16457
16458 @noindent
16459 where symbol is an identifier, following normal Ada (case-insensitive)
16460 rules for its syntax, and value is one of the following:
16461
16462 @itemize @bullet
16463 @item
16464 Empty, corresponding to a null substitution
16465 @item
16466 A string literal using normal Ada syntax
16467 @item
16468 Any sequence of characters from the set
16469 (letters, digits, period, underline).
16470 @end itemize
16471
16472 @noindent
16473 Comment lines may also appear in the definitions file, starting with
16474 the usual @code{--},
16475 and comments may be added to the definitions lines.
16476
16477 @node Form of Input Text for gnatprep
16478 @section Form of Input Text for @code{gnatprep}
16479
16480 @noindent
16481 The input text may contain preprocessor conditional inclusion lines,
16482 as well as general symbol substitution sequences.
16483
16484 The preprocessor conditional inclusion commands have the form
16485
16486 @smallexample
16487 @group
16488 @cartouche
16489 #if @i{expression} [then]
16490    lines
16491 #elsif @i{expression} [then]
16492    lines
16493 #elsif @i{expression} [then]
16494    lines
16495 ...
16496 #else
16497    lines
16498 #end if;
16499 @end cartouche
16500 @end group
16501 @end smallexample
16502
16503 @noindent
16504 In this example, @i{expression} is defined by the following grammar:
16505 @smallexample
16506 @i{expression} ::=  <symbol>
16507 @i{expression} ::=  <symbol> = "<value>"
16508 @i{expression} ::=  <symbol> = <symbol>
16509 @i{expression} ::=  <symbol> 'Defined
16510 @i{expression} ::=  not @i{expression}
16511 @i{expression} ::=  @i{expression} and @i{expression}
16512 @i{expression} ::=  @i{expression} or @i{expression}
16513 @i{expression} ::=  @i{expression} and then @i{expression}
16514 @i{expression} ::=  @i{expression} or else @i{expression}
16515 @i{expression} ::=  ( @i{expression} )
16516 @end smallexample
16517
16518 @noindent
16519 For the first test (@i{expression} ::= <symbol>) the symbol must have
16520 either the value true or false, that is to say the right-hand of the
16521 symbol definition must be one of the (case-insensitive) literals
16522 @code{True} or @code{False}. If the value is true, then the
16523 corresponding lines are included, and if the value is false, they are
16524 excluded.
16525
16526 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16527 the symbol has been defined in the definition file or by a @option{-D}
16528 switch on the command line. Otherwise, the test is false.
16529
16530 The equality tests are case insensitive, as are all the preprocessor lines.
16531
16532 If the symbol referenced is not defined in the symbol definitions file,
16533 then the effect depends on whether or not switch @option{-u}
16534 is specified. If so, then the symbol is treated as if it had the value
16535 false and the test fails. If this switch is not specified, then
16536 it is an error to reference an undefined symbol. It is also an error to
16537 reference a symbol that is defined with a value other than @code{True}
16538 or @code{False}.
16539
16540 The use of the @code{not} operator inverts the sense of this logical test, so
16541 that the lines are included only if the symbol is not defined.
16542 The @code{then} keyword is optional as shown
16543
16544 The @code{#} must be the first non-blank character on a line, but
16545 otherwise the format is free form. Spaces or tabs may appear between
16546 the @code{#} and the keyword. The keywords and the symbols are case
16547 insensitive as in normal Ada code. Comments may be used on a
16548 preprocessor line, but other than that, no other tokens may appear on a
16549 preprocessor line. Any number of @code{elsif} clauses can be present,
16550 including none at all. The @code{else} is optional, as in Ada.
16551
16552 The @code{#} marking the start of a preprocessor line must be the first
16553 non-blank character on the line, i.e. it must be preceded only by
16554 spaces or horizontal tabs.
16555
16556 Symbol substitution outside of preprocessor lines is obtained by using
16557 the sequence
16558
16559 @smallexample
16560 $symbol
16561 @end smallexample
16562
16563 @noindent
16564 anywhere within a source line, except in a comment or within a
16565 string literal. The identifier
16566 following the @code{$} must match one of the symbols defined in the symbol
16567 definition file, and the result is to substitute the value of the
16568 symbol in place of @code{$symbol} in the output file.
16569
16570 Note that although the substitution of strings within a string literal
16571 is not possible, it is possible to have a symbol whose defined value is
16572 a string literal. So instead of setting XYZ to @code{hello} and writing:
16573
16574 @smallexample
16575 Header : String := "$XYZ";
16576 @end smallexample
16577
16578 @noindent
16579 you should set XYZ to @code{"hello"} and write:
16580
16581 @smallexample
16582 Header : String := $XYZ;
16583 @end smallexample
16584
16585 @noindent
16586 and then the substitution will occur as desired.
16587
16588 @ifset vms
16589 @node The GNAT Run-Time Library Builder gnatlbr
16590 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16591 @findex gnatlbr
16592 @cindex Library builder
16593
16594 @noindent
16595 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16596 supplied configuration pragmas.
16597
16598 @menu
16599 * Running gnatlbr::
16600 * Switches for gnatlbr::
16601 * Examples of gnatlbr Usage::
16602 @end menu
16603
16604 @node Running gnatlbr
16605 @section Running @code{gnatlbr}
16606
16607 @noindent
16608 The @code{gnatlbr} command has the form
16609
16610 @smallexample
16611 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16612 @end smallexample
16613
16614 @node Switches for gnatlbr
16615 @section Switches for @code{gnatlbr}
16616
16617 @noindent
16618 @code{gnatlbr} recognizes the following switches:
16619
16620 @table @option
16621 @c !sort!
16622 @item /CREATE=directory
16623 @cindex @code{/CREATE} (@code{gnatlbr})
16624      Create the new run-time library in the specified directory.
16625
16626 @item /SET=directory
16627 @cindex @code{/SET} (@code{gnatlbr})
16628      Make the library in the specified directory the current run-time
16629      library.
16630
16631 @item /DELETE=directory
16632 @cindex @code{/DELETE} (@code{gnatlbr})
16633      Delete the run-time library in the specified directory.
16634
16635 @item /CONFIG=file
16636 @cindex @code{/CONFIG} (@code{gnatlbr})
16637      With /CREATE:
16638      Use the configuration pragmas in the specified file when building
16639      the library.
16640
16641      With /SET:
16642      Use the configuration pragmas in the specified file when compiling.
16643
16644 @end table
16645
16646 @node Examples of gnatlbr Usage
16647 @section Example of @code{gnatlbr} Usage
16648
16649 @smallexample
16650 Contents of VAXFLOAT.ADC:
16651 pragma Float_Representation (VAX_Float);
16652
16653 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16654
16655 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16656
16657 @end smallexample
16658 @end ifset
16659
16660 @node The GNAT Library Browser gnatls
16661 @chapter The GNAT Library Browser @code{gnatls}
16662 @findex gnatls
16663 @cindex Library browser
16664
16665 @noindent
16666 @code{gnatls} is a tool that outputs information about compiled
16667 units. It gives the relationship between objects, unit names and source
16668 files. It can also be used to check the source dependencies of a unit
16669 as well as various characteristics.
16670
16671 @menu
16672 * Running gnatls::
16673 * Switches for gnatls::
16674 * Examples of gnatls Usage::
16675 @end menu
16676
16677 @node Running gnatls
16678 @section Running @code{gnatls}
16679
16680 @noindent
16681 The @code{gnatls} command has the form
16682
16683 @smallexample
16684 $ gnatls switches @var{object_or_ali_file}
16685 @end smallexample
16686
16687 @noindent
16688 The main argument is the list of object or @file{ali} files
16689 (@pxref{The Ada Library Information Files})
16690 for which information is requested.
16691
16692 In normal mode, without additional option, @code{gnatls} produces a
16693 four-column listing. Each line represents information for a specific
16694 object. The first column gives the full path of the object, the second
16695 column gives the name of the principal unit in this object, the third
16696 column gives the status of the source and the fourth column gives the
16697 full path of the source representing this unit.
16698 Here is a simple example of use:
16699
16700 @smallexample
16701 $ gnatls *.o
16702 ^./^[]^demo1.o            demo1            DIF demo1.adb
16703 ^./^[]^demo2.o            demo2             OK demo2.adb
16704 ^./^[]^hello.o            h1                OK hello.adb
16705 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16706 ^./^[]^instr.o            instr             OK instr.adb
16707 ^./^[]^tef.o              tef              DIF tef.adb
16708 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16709 ^./^[]^tgef.o             tgef             DIF tgef.adb
16710 @end smallexample
16711
16712 @noindent
16713 The first line can be interpreted as follows: the main unit which is
16714 contained in
16715 object file @file{demo1.o} is demo1, whose main source is in
16716 @file{demo1.adb}. Furthermore, the version of the source used for the
16717 compilation of demo1 has been modified (DIF). Each source file has a status
16718 qualifier which can be:
16719
16720 @table @code
16721 @item OK (unchanged)
16722 The version of the source file used for the compilation of the
16723 specified unit corresponds exactly to the actual source file.
16724
16725 @item MOK (slightly modified)
16726 The version of the source file used for the compilation of the
16727 specified unit differs from the actual source file but not enough to
16728 require recompilation. If you use gnatmake with the qualifier
16729 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16730 MOK will not be recompiled.
16731
16732 @item DIF (modified)
16733 No version of the source found on the path corresponds to the source
16734 used to build this object.
16735
16736 @item ??? (file not found)
16737 No source file was found for this unit.
16738
16739 @item HID (hidden,  unchanged version not first on PATH)
16740 The version of the source that corresponds exactly to the source used
16741 for compilation has been found on the path but it is hidden by another
16742 version of the same source that has been modified.
16743
16744 @end table
16745
16746 @node Switches for gnatls
16747 @section Switches for @code{gnatls}
16748
16749 @noindent
16750 @code{gnatls} recognizes the following switches:
16751
16752 @table @option
16753 @c !sort!
16754 @item ^-a^/ALL_UNITS^
16755 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16756 Consider all units, including those of the predefined Ada library.
16757 Especially useful with @option{^-d^/DEPENDENCIES^}.
16758
16759 @item ^-d^/DEPENDENCIES^
16760 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16761 List sources from which specified units depend on.
16762
16763 @item ^-h^/OUTPUT=OPTIONS^
16764 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16765 Output the list of options.
16766
16767 @item ^-o^/OUTPUT=OBJECTS^
16768 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16769 Only output information about object files.
16770
16771 @item ^-s^/OUTPUT=SOURCES^
16772 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16773 Only output information about source files.
16774
16775 @item ^-u^/OUTPUT=UNITS^
16776 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16777 Only output information about compilation units.
16778
16779 @item ^-files^/FILES^=@var{file}
16780 @cindex @option{^-files^/FILES^} (@code{gnatls})
16781 Take as arguments the files listed in text file @var{file}.
16782 Text file @var{file} may contain empty lines that are ignored.
16783 Each non empty line should contain the name of an existing file.
16784 Several such switches may be specified simultaneously.
16785
16786 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16787 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16788 @itemx ^-I^/SEARCH=^@var{dir}
16789 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16790 @itemx -nostdinc
16791 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16792 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16793 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16794 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16795 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16796 flags (@pxref{Switches for gnatmake}).
16797
16798 @item --RTS=@var{rts-path}
16799 @cindex @option{--RTS} (@code{gnatls})
16800 Specifies the default location of the runtime library. Same meaning as the
16801 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16802
16803 @item ^-v^/OUTPUT=VERBOSE^
16804 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16805 Verbose mode. Output the complete source, object and project paths. Do not use
16806 the default column layout but instead use long format giving as much as
16807 information possible on each requested units, including special
16808 characteristics such as:
16809
16810 @table @code
16811 @item  Preelaborable
16812 The unit is preelaborable in the Ada 95 sense.
16813
16814 @item No_Elab_Code
16815 No elaboration code has been produced by the compiler for this unit.
16816
16817 @item Pure
16818 The unit is pure in the Ada 95 sense.
16819
16820 @item Elaborate_Body
16821 The unit contains a pragma Elaborate_Body.
16822
16823 @item Remote_Types
16824 The unit contains a pragma Remote_Types.
16825
16826 @item Shared_Passive
16827 The unit contains a pragma Shared_Passive.
16828
16829 @item Predefined
16830 This unit is part of the predefined environment and cannot be modified
16831 by the user.
16832
16833 @item Remote_Call_Interface
16834 The unit contains a pragma Remote_Call_Interface.
16835
16836 @end table
16837
16838 @end table
16839
16840 @node Examples of gnatls Usage
16841 @section Example of @code{gnatls} Usage
16842 @ifclear vms
16843
16844 @noindent
16845 Example of using the verbose switch. Note how the source and
16846 object paths are affected by the -I switch.
16847
16848 @smallexample
16849 $ gnatls -v -I.. demo1.o
16850
16851 GNATLS 5.03w (20041123-34)
16852 Copyright 1997-2004 Free Software Foundation, Inc.
16853
16854 Source Search Path:
16855    <Current_Directory>
16856    ../
16857    /home/comar/local/adainclude/
16858
16859 Object Search Path:
16860    <Current_Directory>
16861    ../
16862    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16863
16864 Project Search Path:
16865    <Current_Directory>
16866    /home/comar/local/lib/gnat/
16867
16868 ./demo1.o
16869    Unit =>
16870      Name   => demo1
16871      Kind   => subprogram body
16872      Flags  => No_Elab_Code
16873      Source => demo1.adb    modified
16874 @end smallexample
16875
16876 @noindent
16877 The following is an example of use of the dependency list.
16878 Note the use of the -s switch
16879 which gives a straight list of source files. This can be useful for
16880 building specialized scripts.
16881
16882 @smallexample
16883 $ gnatls -d demo2.o
16884 ./demo2.o   demo2        OK demo2.adb
16885                          OK gen_list.ads
16886                          OK gen_list.adb
16887                          OK instr.ads
16888                          OK instr-child.ads
16889
16890 $ gnatls -d -s -a demo1.o
16891 demo1.adb
16892 /home/comar/local/adainclude/ada.ads
16893 /home/comar/local/adainclude/a-finali.ads
16894 /home/comar/local/adainclude/a-filico.ads
16895 /home/comar/local/adainclude/a-stream.ads
16896 /home/comar/local/adainclude/a-tags.ads
16897 gen_list.ads
16898 gen_list.adb
16899 /home/comar/local/adainclude/gnat.ads
16900 /home/comar/local/adainclude/g-io.ads
16901 instr.ads
16902 /home/comar/local/adainclude/system.ads
16903 /home/comar/local/adainclude/s-exctab.ads
16904 /home/comar/local/adainclude/s-finimp.ads
16905 /home/comar/local/adainclude/s-finroo.ads
16906 /home/comar/local/adainclude/s-secsta.ads
16907 /home/comar/local/adainclude/s-stalib.ads
16908 /home/comar/local/adainclude/s-stoele.ads
16909 /home/comar/local/adainclude/s-stratt.ads
16910 /home/comar/local/adainclude/s-tasoli.ads
16911 /home/comar/local/adainclude/s-unstyp.ads
16912 /home/comar/local/adainclude/unchconv.ads
16913 @end smallexample
16914 @end ifclear
16915
16916 @ifset vms
16917 @smallexample
16918 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16919
16920 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16921 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16922 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16923 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16924 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16925 demo1.adb
16926 gen_list.ads
16927 gen_list.adb
16928 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16929 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16930 instr.ads
16931 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16932 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16933 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16934 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16935 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16936 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16937 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16938 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16939 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16940 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16941 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16942 @end smallexample
16943 @end ifset
16944
16945 @node Cleaning Up Using gnatclean
16946 @chapter Cleaning Up Using @code{gnatclean}
16947 @findex gnatclean
16948 @cindex Cleaning tool
16949
16950 @noindent
16951 @code{gnatclean} is a tool that allows the deletion of files produced by the
16952 compiler, binder and linker, including ALI files, object files, tree files,
16953 expanded source files, library files, interface copy source files, binder
16954 generated files and executable files.
16955
16956 @menu
16957 * Running gnatclean::
16958 * Switches for gnatclean::
16959 @c * Examples of gnatclean Usage::
16960 @end menu
16961
16962 @node Running gnatclean
16963 @section Running @code{gnatclean}
16964
16965 @noindent
16966 The @code{gnatclean} command has the form:
16967
16968 @smallexample
16969 $ gnatclean switches @var{names}
16970 @end smallexample
16971
16972 @noindent
16973 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16974 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16975 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16976
16977 @noindent
16978 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16979 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16980 the linker. In informative-only mode, specified by switch
16981 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16982 normal mode is listed, but no file is actually deleted.
16983
16984 @node Switches for gnatclean
16985 @section Switches for @code{gnatclean}
16986
16987 @noindent
16988 @code{gnatclean} recognizes the following switches:
16989
16990 @table @option
16991 @c !sort!
16992 @item ^-c^/COMPILER_FILES_ONLY^
16993 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16994 Only attempt to delete the files produced by the compiler, not those produced
16995 by the binder or the linker. The files that are not to be deleted are library
16996 files, interface copy files, binder generated files and executable files.
16997
16998 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16999 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17000 Indicate that ALI and object files should normally be found in directory
17001 @var{dir}.
17002
17003 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17004 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17005 When using project files, if some errors or warnings are detected during
17006 parsing and verbose mode is not in effect (no use of switch
17007 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17008 file, rather than its simple file name.
17009
17010 @item ^-h^/HELP^
17011 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17012 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17013
17014 @item ^-n^/NODELETE^
17015 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17016 Informative-only mode. Do not delete any files. Output the list of the files
17017 that would have been deleted if this switch was not specified.
17018
17019 @item ^-P^/PROJECT_FILE=^@var{project}
17020 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17021 Use project file @var{project}. Only one such switch can be used.
17022 When cleaning a project file, the files produced by the compilation of the
17023 immediate sources or inherited sources of the project files are to be
17024 deleted. This is not depending on the presence or not of executable names
17025 on the command line.
17026
17027 @item ^-q^/QUIET^
17028 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17029 Quiet output. If there are no error, do not ouuput anything, except in
17030 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17031 (switch ^-n^/NODELETE^).
17032
17033 @item ^-r^/RECURSIVE^
17034 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17035 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17036 clean all imported and extended project files, recursively. If this switch
17037 is not specified, only the files related to the main project file are to be
17038 deleted. This switch has no effect if no project file is specified.
17039
17040 @item ^-v^/VERBOSE^
17041 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17042 Verbose mode.
17043
17044 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17045 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17046 Indicates the verbosity of the parsing of GNAT project files.
17047 @xref{Switches Related to Project Files}.
17048
17049 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17050 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17051 Indicates that external variable @var{name} has the value @var{value}.
17052 The Project Manager will use this value for occurrences of
17053 @code{external(name)} when parsing the project file.
17054 @xref{Switches Related to Project Files}.
17055
17056 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17057 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17058 When searching for ALI and object files, look in directory
17059 @var{dir}.
17060
17061 @item ^-I^/SEARCH=^@var{dir}
17062 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17063 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17064
17065 @item ^-I-^/NOCURRENT_DIRECTORY^
17066 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17067 @cindex Source files, suppressing search
17068 Do not look for ALI or object files in the directory
17069 where @code{gnatclean} was invoked.
17070
17071 @end table
17072
17073 @c @node Examples of gnatclean Usage
17074 @c @section Examples of @code{gnatclean} Usage
17075
17076 @ifclear vms
17077 @node GNAT and Libraries
17078 @chapter GNAT and Libraries
17079 @cindex Library, building, installing, using
17080
17081 @noindent
17082 This chapter describes how to build and use libraries with GNAT, and also shows
17083 how to recompile the GNAT run-time library. You should be familiar with the
17084 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17085 chapter.
17086
17087 @menu
17088 * Introduction to Libraries in GNAT::
17089 * General Ada Libraries::
17090 * Stand-alone Ada Libraries::
17091 * Rebuilding the GNAT Run-Time Library::
17092 @end menu
17093
17094 @node Introduction to Libraries in GNAT
17095 @section Introduction to Libraries in GNAT
17096
17097 @noindent
17098 A library is, conceptually, a collection of objects which does not have its
17099 own main thread of execution, but rather provides certain services to the
17100 applications that use it. A library can be either statically linked with the
17101 application, in which case its code is directly included in the application,
17102 or, on platforms that support it, be dynamically linked, in which case
17103 its code is shared by all applications making use of this library.
17104
17105 GNAT supports both types of libraries.
17106 In the static case, the compiled code can be provided in different ways. The
17107 simplest approach is to provide directly the set of objects resulting from
17108 compilation of the library source files. Alternatively, you can group the
17109 objects into an archive using whatever commands are provided by the operating
17110 system. For the latter case, the objects are grouped into a shared library.
17111
17112 In the GNAT environment, a library has three types of components:
17113 @itemize @bullet
17114 @item
17115 Source files.
17116 @item
17117 @file{ALI} files.
17118 @xref{The Ada Library Information Files}.
17119 @item
17120 Object files, an archive or a shared library.
17121 @end itemize
17122
17123 @noindent
17124 A GNAT library may expose all its source files, which is useful for
17125 documentation purposes. Alternatively, it may expose only the units needed by
17126 an external user to make use of the library. That is to say, the specs
17127 reflecting the library services along with all the units needed to compile
17128 those specs, which can include generic bodies or any body implementing an
17129 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17130 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17131
17132 All compilation units comprising an application, including those in a library,
17133 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17134 computes the elaboration order from the @file{ALI} files and this is why they
17135 constitute a mandatory part of GNAT libraries. Except in the case of
17136 @emph{stand-alone libraries}, where a specific library elaboration routine is
17137 produced independently of the application(s) using the library.
17138
17139 @node General Ada Libraries
17140 @section General Ada Libraries
17141
17142 @menu
17143 * Building a library::
17144 * Installing a library::
17145 * Using a library::
17146 @end menu
17147
17148 @node Building a library
17149 @subsection Building a library
17150
17151 @noindent
17152 The easiest way to build a library is to use the Project Manager,
17153 which supports a special type of project called a @emph{Library Project}
17154 (@pxref{Library Projects}).
17155
17156 A project is considered a library project, when two project-level attributes
17157 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17158 control different aspects of library configuration, additional optional
17159 project-level attributes can be specified:
17160 @table @code
17161 @item Library_Kind
17162 This attribute controls whether the library is to be static or dynamic
17163
17164 @item Library_Version
17165 This attribute specifies the library version; this value is used
17166 during dynamic linking of shared libraries to determine if the currently
17167 installed versions of the binaries are compatible.
17168
17169 @item Library_Options
17170 @item Library_GCC
17171 These attributes specify additional low-level options to be used during
17172 library generation, and redefine the actual application used to generate
17173 library.
17174 @end table
17175
17176 @noindent
17177 The GNAT Project Manager takes full care of the library maintenance task,
17178 including recompilation of the source files for which objects do not exist
17179 or are not up to date, assembly of the library archive, and installation of
17180 the library (i.e., copying associated source, object and @file{ALI} files
17181 to the specified location).
17182
17183 Here is a simple library project file:
17184 @smallexample @c ada
17185 project My_Lib is
17186    for Source_Dirs use ("src1", "src2");
17187    for Object_Dir use "obj";
17188    for Library_Name use "mylib";
17189    for Library_Dir use "lib";
17190    for Library_Kind use "dynamic";
17191 end My_lib;
17192 @end smallexample
17193
17194 @noindent
17195 and the compilation command to build and install the library:
17196
17197 @smallexample @c ada
17198   $ gnatmake -Pmy_lib
17199 @end smallexample
17200
17201 @noindent
17202 It is not entirely trivial to perform manually all the steps required to
17203 produce a library. We recommend that you use the GNAT Project Manager
17204 for this task. In special cases where this is not desired, the necessary
17205 steps are discussed below.
17206
17207 There are various possibilities for compiling the units that make up the
17208 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17209 with a conventional script. For simple libraries, it is also possible to create
17210 a dummy main program which depends upon all the packages that comprise the
17211 interface of the library. This dummy main program can then be given to
17212 @command{gnatmake}, which will ensure that all necessary objects are built.
17213
17214 After this task is accomplished, you should follow the standard procedure
17215 of the underlying operating system to produce the static or shared library.
17216
17217 Here is an example of such a dummy program:
17218 @smallexample @c ada
17219 @group
17220 with My_Lib.Service1;
17221 with My_Lib.Service2;
17222 with My_Lib.Service3;
17223 procedure My_Lib_Dummy is
17224 begin
17225    null;
17226 end;
17227 @end group
17228 @end smallexample
17229
17230 @noindent
17231 Here are the generic commands that will build an archive or a shared library.
17232
17233 @smallexample
17234 # compiling the library
17235 $ gnatmake -c my_lib_dummy.adb
17236
17237 # we don't need the dummy object itself
17238 $ rm my_lib_dummy.o my_lib_dummy.ali
17239
17240 # create an archive with the remaining objects
17241 $ ar rc libmy_lib.a *.o
17242 # some systems may require "ranlib" to be run as well
17243
17244 # or create a shared library
17245 $ gcc -shared -o libmy_lib.so *.o
17246 # some systems may require the code to have been compiled with -fPIC
17247
17248 # remove the object files that are now in the library
17249 $ rm *.o
17250
17251 # Make the ALI files read-only so that gnatmake will not try to
17252 # regenerate the objects that are in the library
17253 $ chmod -w *.ali
17254 @end smallexample
17255
17256 @noindent
17257 Please note that the library must have a name of the form @file{libxxx.a} or
17258 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17259 the directive @option{-lxxx} at link time.
17260
17261 @node Installing a library
17262 @subsection Installing a library
17263 @cindex @code{ADA_PROJECT_PATH}
17264
17265 @noindent
17266 If you use project files, library installation is part of the library build
17267 process. Thus no further action is needed in order to make use of the
17268 libraries that are built as part of the general application build. A usable
17269 version of the library is installed in the directory specified by the
17270 @code{Library_Dir} attribute of the library project file.
17271
17272 You may want to install a library in a context different from where the library
17273 is built. This situation arises with third party suppliers, who may want
17274 to distribute a library in binary form where the user is not expected to be
17275 able to recompile the library. The simplest option in this case is to provide
17276 a project file slightly different from the one used to build the library, by
17277 using the @code{externally_built} attribute. For instance, the project
17278 file used to build the library in the previous section can be changed into the
17279 following one when the library is installed:
17280
17281 @smallexample @c projectfile
17282 project My_Lib is
17283    for Source_Dirs use ("src1", "src2");
17284    for Library_Name use "mylib";
17285    for Library_Dir use "lib";
17286    for Library_Kind use "dynamic";
17287    for Externally_Built use "true";
17288 end My_lib;
17289 @end smallexample
17290
17291 @noindent
17292 This project file assumes that the directories @file{src1},
17293 @file{src2}, and @file{lib} exist in
17294 the directory containing the project file. The @code{externally_built}
17295 attribute makes it clear to the GNAT builder that it should not attempt to
17296 recompile any of the units from this library. It allows the library provider to
17297 restrict the source set to the minimum necessary for clients to make use of the
17298 library as described in the first section of this chapter. It is the
17299 responsibility of the library provider to install the necessary sources, ALI
17300 files and libraries in the directories mentioned in the project file. For
17301 convenience, the user's library project file should be installed in a location
17302 that will be searched automatically by the GNAT
17303 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
17304 environment variable (@pxref{Importing Projects}), and also the default GNAT
17305 library location that can be queried with @command{gnatls -v} and is usually of
17306 the form $gnat_install_root/lib/gnat.
17307
17308 When project files are not an option, it is also possible, but not recommended,
17309 to install the library so that the sources needed to use the library are on the
17310 Ada source path and the ALI files & libraries be on the Ada Object path (see
17311 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17312 administrator can place general-purpose libraries in the default compiler
17313 paths, by specifying the libraries' location in the configuration files
17314 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17315 must be located in the GNAT installation tree at the same place as the gcc spec
17316 file. The location of the gcc spec file can be determined as follows:
17317 @smallexample
17318 $ gcc -v
17319 @end smallexample
17320
17321 @noindent
17322 The configuration files mentioned above have a simple format: each line
17323 must contain one unique directory name.
17324 Those names are added to the corresponding path
17325 in their order of appearance in the file. The names can be either absolute
17326 or relative; in the latter case, they are relative to where theses files
17327 are located.
17328
17329 The files @file{ada_source_path} and @file{ada_object_path} might not be
17330 present in a
17331 GNAT installation, in which case, GNAT will look for its run-time library in
17332 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17333 objects and @file{ALI} files). When the files exist, the compiler does not
17334 look in @file{adainclude} and @file{adalib}, and thus the
17335 @file{ada_source_path} file
17336 must contain the location for the GNAT run-time sources (which can simply
17337 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17338 contain the location for the GNAT run-time objects (which can simply
17339 be @file{adalib}).
17340
17341 You can also specify a new default path to the run-time library at compilation
17342 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17343 the run-time library you want your program to be compiled with. This switch is
17344 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17345 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17346
17347 It is possible to install a library before or after the standard GNAT
17348 library, by reordering the lines in the configuration files. In general, a
17349 library must be installed before the GNAT library if it redefines
17350 any part of it.
17351
17352 @node Using a library
17353 @subsection Using a library
17354
17355 @noindent Once again, the project facility greatly simplifies the use of
17356 libraries. In this context, using a library is just a matter of adding a
17357 @code{with} clause in the user project. For instance, to make use of the
17358 library @code{My_Lib} shown in examples in earlier sections, you can
17359 write:
17360
17361 @smallexample @c projectfile
17362 with "my_lib";
17363 project My_Proj is
17364   ...
17365 end My_Proj;
17366 @end smallexample
17367
17368 Even if you have a third-party, non-Ada library, you can still use GNAT's
17369 Project Manager facility to provide a wrapper for it. For example, the
17370 following project, when @code{with}ed by your main project, will link with the
17371 third-party library @file{liba.a}:
17372
17373 @smallexample @c projectfile
17374 @group
17375 project Liba is
17376    for Externally_Built use "true";
17377    for Library_Dir use "lib";
17378    for Library_Name use "a";
17379    for Library_Kind use "static";
17380 end Liba;
17381 @end group
17382 @end smallexample
17383 This is an alternative to the use of @code{pragma Linker_Options}. It is
17384 especially interesting in the context of systems with several interdependant
17385 static libraries where finding a proper linker order is not easy and best be
17386 left to the tools having visibility over project dependancy information.
17387
17388 @noindent
17389 In order to use an Ada library manually, you need to make sure that this
17390 library is on both your source and object path
17391 (see @ref{Search Paths and the Run-Time Library (RTL)}
17392 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17393 in an archive or a shared library, you need to specify the desired
17394 library at link time.
17395
17396 For example, you can use the library @file{mylib} installed in
17397 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17398
17399 @smallexample
17400 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17401   -largs -lmy_lib
17402 @end smallexample
17403
17404 @noindent
17405 This can be expressed more simply:
17406 @smallexample
17407 $ gnatmake my_appl
17408 @end smallexample
17409 @noindent
17410 when the following conditions are met:
17411 @itemize @bullet
17412 @item
17413 @file{/dir/my_lib_src} has been added by the user to the environment
17414 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17415 @file{ada_source_path}
17416 @item
17417 @file{/dir/my_lib_obj} has been added by the user to the environment
17418 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17419 @file{ada_object_path}
17420 @item
17421 a pragma @code{Linker_Options} has been added to one of the sources.
17422 For example:
17423
17424 @smallexample @c ada
17425 pragma Linker_Options ("-lmy_lib");
17426 @end smallexample
17427 @end itemize
17428
17429 @node Stand-alone Ada Libraries
17430 @section Stand-alone Ada Libraries
17431 @cindex Stand-alone library, building, using
17432
17433 @menu
17434 * Introduction to Stand-alone Libraries::
17435 * Building a Stand-alone Library::
17436 * Creating a Stand-alone Library to be used in a non-Ada context::
17437 * Restrictions in Stand-alone Libraries::
17438 @end menu
17439
17440 @node Introduction to Stand-alone Libraries
17441 @subsection Introduction to Stand-alone Libraries
17442
17443 @noindent
17444 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17445 necessary code to
17446 elaborate the Ada units that are included in the library. In contrast with
17447 an ordinary library, which consists of all sources, objects and @file{ALI}
17448 files of the
17449 library, a SAL may specify a restricted subset of compilation units
17450 to serve as a library interface. In this case, the fully
17451 self-sufficient set of files will normally consist of an objects
17452 archive, the sources of interface units' specs, and the @file{ALI}
17453 files of interface units.
17454 If an interface spec contains a generic unit or an inlined subprogram,
17455 the body's
17456 source must also be provided; if the units that must be provided in the source
17457 form depend on other units, the source and @file{ALI} files of those must
17458 also be provided.
17459
17460 The main purpose of a SAL is to minimize the recompilation overhead of client
17461 applications when a new version of the library is installed. Specifically,
17462 if the interface sources have not changed, client applications do not need to
17463 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17464 version, controlled by @code{Library_Version} attribute, is not changed,
17465 then the clients do not need to be relinked.
17466
17467 SALs also allow the library providers to minimize the amount of library source
17468 text exposed to the clients.  Such ``information hiding'' might be useful or
17469 necessary for various reasons.
17470
17471 Stand-alone libraries are also well suited to be used in an executable whose
17472 main routine is not written in Ada.
17473
17474 @node Building a Stand-alone Library
17475 @subsection Building a Stand-alone Library
17476
17477 @noindent
17478 GNAT's Project facility provides a simple way of building and installing
17479 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17480 To be a Stand-alone Library Project, in addition to the two attributes
17481 that make a project a Library Project (@code{Library_Name} and
17482 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17483 @code{Library_Interface} must be defined.  For example:
17484
17485 @smallexample @c projectfile
17486 @group
17487    for Library_Dir use "lib_dir";
17488    for Library_Name use "dummy";
17489    for Library_Interface use ("int1", "int1.child");
17490 @end group
17491 @end smallexample
17492
17493 @noindent
17494 Attribute @code{Library_Interface} has a non-empty string list value,
17495 each string in the list designating a unit contained in an immediate source
17496 of the project file.
17497
17498 When a Stand-alone Library is built, first the binder is invoked to build
17499 a package whose name depends on the library name
17500 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17501 This binder-generated package includes initialization and
17502 finalization procedures whose
17503 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17504 in the example
17505 above). The object corresponding to this package is included in the library.
17506
17507 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17508 calling of these procedures if a static SAL is built, or if a shared SAL
17509 is built
17510 with the project-level attribute @code{Library_Auto_Init} set to
17511 @code{"false"}.
17512
17513 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17514 (those that are listed in attribute @code{Library_Interface}) are copied to
17515 the Library Directory. As a consequence, only the Interface Units may be
17516 imported from Ada units outside of the library. If other units are imported,
17517 the binding phase will fail.
17518
17519 The attribute @code{Library_Src_Dir} may be specified for a
17520 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17521 single string value. Its value must be the path (absolute or relative to the
17522 project directory) of an existing directory. This directory cannot be the
17523 object directory or one of the source directories, but it can be the same as
17524 the library directory. The sources of the Interface
17525 Units of the library that are needed by an Ada client of the library will be
17526 copied to the designated directory, called the Interface Copy directory.
17527 These sources include the specs of the Interface Units, but they may also
17528 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17529 are used, or when there is a generic unit in the spec. Before the sources
17530 are copied to the Interface Copy directory, an attempt is made to delete all
17531 files in the Interface Copy directory.
17532
17533 Building stand-alone libraries by hand is somewhat tedious, but for those
17534 occasions when it is necessary here are the steps that you need to perform:
17535 @itemize @bullet
17536 @item
17537 Compile all library sources.
17538
17539 @item
17540 Invoke the binder with the switch @option{-n} (No Ada main program),
17541 with all the @file{ALI} files of the interfaces, and
17542 with the switch @option{-L} to give specific names to the @code{init}
17543 and @code{final} procedures.  For example:
17544 @smallexample
17545   gnatbind -n int1.ali int2.ali -Lsal1
17546 @end smallexample
17547
17548 @item
17549 Compile the binder generated file:
17550 @smallexample
17551   gcc -c b~int2.adb
17552 @end smallexample
17553
17554 @item
17555 Link the dynamic library with all the necessary object files,
17556 indicating to the linker the names of the @code{init} (and possibly
17557 @code{final}) procedures for automatic initialization (and finalization).
17558 The built library should be placed in a directory different from
17559 the object directory.
17560
17561 @item
17562 Copy the @code{ALI} files of the interface to the library directory,
17563 add in this copy an indication that it is an interface to a SAL
17564 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17565 with letter ``P'') and make the modified copy of the @file{ALI} file
17566 read-only.
17567 @end itemize
17568
17569 @noindent
17570 Using SALs is not different from using other libraries
17571 (see @ref{Using a library}).
17572
17573 @node Creating a Stand-alone Library to be used in a non-Ada context
17574 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17575
17576 @noindent
17577 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17578 a non-Ada context.
17579
17580 The only extra step required is to ensure that library interface subprograms
17581 are compatible with the main program, by means of @code{pragma Export}
17582 or @code{pragma Convention}.
17583
17584 Here is an example of simple library interface for use with C main program:
17585
17586 @smallexample @c ada
17587 package Interface is
17588
17589    procedure Do_Something;
17590    pragma Export (C, Do_Something, "do_something");
17591
17592    procedure Do_Something_Else;
17593    pragma Export (C, Do_Something_Else, "do_something_else");
17594
17595 end Interface;
17596 @end smallexample
17597
17598 @noindent
17599 On the foreign language side, you must provide a ``foreign'' view of the
17600 library interface; remember that it should contain elaboration routines in
17601 addition to interface subprograms.
17602
17603 The example below shows the content of @code{mylib_interface.h} (note
17604 that there is no rule for the naming of this file, any name can be used)
17605 @smallexample
17606 /* the library elaboration procedure */
17607 extern void mylibinit (void);
17608
17609 /* the library finalization procedure */
17610 extern void mylibfinal (void);
17611
17612 /* the interface exported by the library */
17613 extern void do_something (void);
17614 extern void do_something_else (void);
17615 @end smallexample
17616
17617 @noindent
17618 Libraries built as explained above can be used from any program, provided
17619 that the elaboration procedures (named @code{mylibinit} in the previous
17620 example) are called before the library services are used. Any number of
17621 libraries can be used simultaneously, as long as the elaboration
17622 procedure of each library is called.
17623
17624 Below is an example of a C program that uses the @code{mylib} library.
17625
17626 @smallexample
17627 #include "mylib_interface.h"
17628
17629 int
17630 main (void)
17631 @{
17632    /* First, elaborate the library before using it */
17633    mylibinit ();
17634
17635    /* Main program, using the library exported entities */
17636    do_something ();
17637    do_something_else ();
17638
17639    /* Library finalization at the end of the program */
17640    mylibfinal ();
17641    return 0;
17642 @}
17643 @end smallexample
17644
17645 @noindent
17646 Note that invoking any library finalization procedure generated by
17647 @code{gnatbind} shuts down the Ada run-time environment.
17648 Consequently, the
17649 finalization of all Ada libraries must be performed at the end of the program.
17650 No call to these libraries or to the Ada run-time library should be made
17651 after the finalization phase.
17652
17653 @node Restrictions in Stand-alone Libraries
17654 @subsection Restrictions in Stand-alone Libraries
17655
17656 @noindent
17657 The pragmas listed below should be used with caution inside libraries,
17658 as they can create incompatibilities with other Ada libraries:
17659 @itemize @bullet
17660 @item pragma @code{Locking_Policy}
17661 @item pragma @code{Queuing_Policy}
17662 @item pragma @code{Task_Dispatching_Policy}
17663 @item pragma @code{Unreserve_All_Interrupts}
17664 @end itemize
17665
17666 @noindent
17667 When using a library that contains such pragmas, the user must make sure
17668 that all libraries use the same pragmas with the same values. Otherwise,
17669 @code{Program_Error} will
17670 be raised during the elaboration of the conflicting
17671 libraries. The usage of these pragmas and its consequences for the user
17672 should therefore be well documented.
17673
17674 Similarly, the traceback in the exception occurrence mechanism should be
17675 enabled or disabled in a consistent manner across all libraries.
17676 Otherwise, Program_Error will be raised during the elaboration of the
17677 conflicting libraries.
17678
17679 If the @code{Version} or @code{Body_Version}
17680 attributes are used inside a library, then you need to
17681 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17682 libraries, so that version identifiers can be properly computed.
17683 In practice these attributes are rarely used, so this is unlikely
17684 to be a consideration.
17685
17686 @node  Rebuilding the GNAT Run-Time Library
17687 @section Rebuilding the GNAT Run-Time Library
17688 @cindex GNAT Run-Time Library, rebuilding
17689
17690 @noindent
17691 It may be useful to recompile the GNAT library in various contexts, the
17692 most important one being the use of partition-wide configuration pragmas
17693 such as @code{Normalize_Scalars}. A special Makefile called
17694 @code{Makefile.adalib} is provided to that effect and can be found in
17695 the directory containing the GNAT library. The location of this
17696 directory depends on the way the GNAT environment has been installed and can
17697 be determined by means of the command:
17698
17699 @smallexample
17700 $ gnatls -v
17701 @end smallexample
17702
17703 @noindent
17704 The last entry in the object search path usually contains the
17705 gnat library. This Makefile contains its own documentation and in
17706 particular the set of instructions needed to rebuild a new library and
17707 to use it.
17708
17709 @node Using the GNU make Utility
17710 @chapter Using the GNU @code{make} Utility
17711 @findex make
17712
17713 @noindent
17714 This chapter offers some examples of makefiles that solve specific
17715 problems. It does not explain how to write a makefile (see the GNU make
17716 documentation), nor does it try to replace the @command{gnatmake} utility
17717 (@pxref{The GNAT Make Program gnatmake}).
17718
17719 All the examples in this section are specific to the GNU version of
17720 make. Although @code{make} is a standard utility, and the basic language
17721 is the same, these examples use some advanced features found only in
17722 @code{GNU make}.
17723
17724 @menu
17725 * Using gnatmake in a Makefile::
17726 * Automatically Creating a List of Directories::
17727 * Generating the Command Line Switches::
17728 * Overcoming Command Line Length Limits::
17729 @end menu
17730
17731 @node Using gnatmake in a Makefile
17732 @section Using gnatmake in a Makefile
17733 @findex makefile
17734 @cindex GNU make
17735
17736 @noindent
17737 Complex project organizations can be handled in a very powerful way by
17738 using GNU make combined with gnatmake. For instance, here is a Makefile
17739 which allows you to build each subsystem of a big project into a separate
17740 shared library. Such a makefile allows you to significantly reduce the link
17741 time of very big applications while maintaining full coherence at
17742 each step of the build process.
17743
17744 The list of dependencies are handled automatically by
17745 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17746 the appropriate directories.
17747
17748 Note that you should also read the example on how to automatically
17749 create the list of directories
17750 (@pxref{Automatically Creating a List of Directories})
17751 which might help you in case your project has a lot of subdirectories.
17752
17753 @smallexample
17754 @iftex
17755 @leftskip=0cm
17756 @font@heightrm=cmr8
17757 @heightrm
17758 @end iftex
17759 ## This Makefile is intended to be used with the following directory
17760 ## configuration:
17761 ##  - The sources are split into a series of csc (computer software components)
17762 ##    Each of these csc is put in its own directory.
17763 ##    Their name are referenced by the directory names.
17764 ##    They will be compiled into shared library (although this would also work
17765 ##    with static libraries
17766 ##  - The main program (and possibly other packages that do not belong to any
17767 ##    csc is put in the top level directory (where the Makefile is).
17768 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17769 ##                    \_ second_csc (sources) __ lib (will contain the library)
17770 ##                    \_ ...
17771 ## Although this Makefile is build for shared library, it is easy to modify
17772 ## to build partial link objects instead (modify the lines with -shared and
17773 ## gnatlink below)
17774 ##
17775 ## With this makefile, you can change any file in the system or add any new
17776 ## file, and everything will be recompiled correctly (only the relevant shared
17777 ## objects will be recompiled, and the main program will be re-linked).
17778
17779 # The list of computer software component for your project. This might be
17780 # generated automatically.
17781 CSC_LIST=aa bb cc
17782
17783 # Name of the main program (no extension)
17784 MAIN=main
17785
17786 # If we need to build objects with -fPIC, uncomment the following line
17787 #NEED_FPIC=-fPIC
17788
17789 # The following variable should give the directory containing libgnat.so
17790 # You can get this directory through 'gnatls -v'. This is usually the last
17791 # directory in the Object_Path.
17792 GLIB=...
17793
17794 # The directories for the libraries
17795 # (This macro expands the list of CSC to the list of shared libraries, you
17796 # could simply use the expanded form :
17797 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17798 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17799
17800 $@{MAIN@}: objects $@{LIB_DIR@}
17801     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17802     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17803
17804 objects::
17805     # recompile the sources
17806     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17807
17808 # Note: In a future version of GNAT, the following commands will be simplified
17809 # by a new tool, gnatmlib
17810 $@{LIB_DIR@}:
17811     mkdir -p $@{dir $@@ @}
17812     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17813     cd $@{dir $@@ @}; cp -f ../*.ali .
17814
17815 # The dependencies for the modules
17816 # Note that we have to force the expansion of *.o, since in some cases
17817 # make won't be able to do it itself.
17818 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17819 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17820 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17821
17822 # Make sure all of the shared libraries are in the path before starting the
17823 # program
17824 run::
17825     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17826
17827 clean::
17828     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17829     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17830     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17831     $@{RM@} *.o *.ali $@{MAIN@}
17832 @end smallexample
17833
17834 @node Automatically Creating a List of Directories
17835 @section Automatically Creating a List of Directories
17836
17837 @noindent
17838 In most makefiles, you will have to specify a list of directories, and
17839 store it in a variable. For small projects, it is often easier to
17840 specify each of them by hand, since you then have full control over what
17841 is the proper order for these directories, which ones should be
17842 included...
17843
17844 However, in larger projects, which might involve hundreds of
17845 subdirectories, it might be more convenient to generate this list
17846 automatically.
17847
17848 The example below presents two methods. The first one, although less
17849 general, gives you more control over the list. It involves wildcard
17850 characters, that are automatically expanded by @code{make}. Its
17851 shortcoming is that you need to explicitly specify some of the
17852 organization of your project, such as for instance the directory tree
17853 depth, whether some directories are found in a separate tree,...
17854
17855 The second method is the most general one. It requires an external
17856 program, called @code{find}, which is standard on all Unix systems. All
17857 the directories found under a given root directory will be added to the
17858 list.
17859
17860 @smallexample
17861 @iftex
17862 @leftskip=0cm
17863 @font@heightrm=cmr8
17864 @heightrm
17865 @end iftex
17866 # The examples below are based on the following directory hierarchy:
17867 # All the directories can contain any number of files
17868 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17869 #                       ->  ab
17870 #                       ->  ac
17871 #                ->  b  ->  ba  ->  baa
17872 #                       ->  bb
17873 #                       ->  bc
17874 # This Makefile creates a variable called DIRS, that can be reused any time
17875 # you need this list (see the other examples in this section)
17876
17877 # The root of your project's directory hierarchy
17878 ROOT_DIRECTORY=.
17879
17880 ####
17881 # First method: specify explicitly the list of directories
17882 # This allows you to specify any subset of all the directories you need.
17883 ####
17884
17885 DIRS := a/aa/ a/ab/ b/ba/
17886
17887 ####
17888 # Second method: use wildcards
17889 # Note that the argument(s) to wildcard below should end with a '/'.
17890 # Since wildcards also return file names, we have to filter them out
17891 # to avoid duplicate directory names.
17892 # We thus use make's @code{dir} and @code{sort} functions.
17893 # It sets DIRs to the following value (note that the directories aaa and baa
17894 # are not given, unless you change the arguments to wildcard).
17895 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17896 ####
17897
17898 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17899                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17900
17901 ####
17902 # Third method: use an external program
17903 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17904 # This is the most complete command: it sets DIRs to the following value:
17905 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17906 ####
17907
17908 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17909
17910 @end smallexample
17911
17912 @node Generating the Command Line Switches
17913 @section Generating the Command Line Switches
17914
17915 @noindent
17916 Once you have created the list of directories as explained in the
17917 previous section (@pxref{Automatically Creating a List of Directories}),
17918 you can easily generate the command line arguments to pass to gnatmake.
17919
17920 For the sake of completeness, this example assumes that the source path
17921 is not the same as the object path, and that you have two separate lists
17922 of directories.
17923
17924 @smallexample
17925 # see "Automatically creating a list of directories" to create
17926 # these variables
17927 SOURCE_DIRS=
17928 OBJECT_DIRS=
17929
17930 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17931 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17932
17933 all:
17934         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17935 @end smallexample
17936
17937 @node Overcoming Command Line Length Limits
17938 @section Overcoming Command Line Length Limits
17939
17940 @noindent
17941 One problem that might be encountered on big projects is that many
17942 operating systems limit the length of the command line. It is thus hard to give
17943 gnatmake the list of source and object directories.
17944
17945 This example shows how you can set up environment variables, which will
17946 make @command{gnatmake} behave exactly as if the directories had been
17947 specified on the command line, but have a much higher length limit (or
17948 even none on most systems).
17949
17950 It assumes that you have created a list of directories in your Makefile,
17951 using one of the methods presented in
17952 @ref{Automatically Creating a List of Directories}.
17953 For the sake of completeness, we assume that the object
17954 path (where the ALI files are found) is different from the sources patch.
17955
17956 Note a small trick in the Makefile below: for efficiency reasons, we
17957 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17958 expanded immediately by @code{make}. This way we overcome the standard
17959 make behavior which is to expand the variables only when they are
17960 actually used.
17961
17962 On Windows, if you are using the standard Windows command shell, you must
17963 replace colons with semicolons in the assignments to these variables.
17964
17965 @smallexample
17966 @iftex
17967 @leftskip=0cm
17968 @font@heightrm=cmr8
17969 @heightrm
17970 @end iftex
17971 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17972 # This is the same thing as putting the -I arguments on the command line.
17973 # (the equivalent of using -aI on the command line would be to define
17974 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17975 # You can of course have different values for these variables.
17976 #
17977 # Note also that we need to keep the previous values of these variables, since
17978 # they might have been set before running 'make' to specify where the GNAT
17979 # library is installed.
17980
17981 # see "Automatically creating a list of directories" to create these
17982 # variables
17983 SOURCE_DIRS=
17984 OBJECT_DIRS=
17985
17986 empty:=
17987 space:=$@{empty@} $@{empty@}
17988 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17989 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17990 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17991 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17992 export ADA_INCLUDE_PATH
17993 export ADA_OBJECT_PATH
17994
17995 all:
17996         gnatmake main_unit
17997 @end smallexample
17998 @end ifclear
17999
18000 @node Memory Management Issues
18001 @chapter Memory Management Issues
18002
18003 @noindent
18004 This chapter describes some useful memory pools provided in the GNAT library
18005 and in particular the GNAT Debug Pool facility, which can be used to detect
18006 incorrect uses of access values (including ``dangling references'').
18007 @ifclear vms
18008 It also describes the @command{gnatmem} tool, which can be used to track down
18009 ``memory leaks''.
18010 @end ifclear
18011
18012 @menu
18013 * Some Useful Memory Pools::
18014 * The GNAT Debug Pool Facility::
18015 @ifclear vms
18016 * The gnatmem Tool::
18017 @end ifclear
18018 @end menu
18019
18020 @node Some Useful Memory Pools
18021 @section Some Useful Memory Pools
18022 @findex Memory Pool
18023 @cindex storage, pool
18024
18025 @noindent
18026 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18027 storage pool. Allocations use the standard system call @code{malloc} while
18028 deallocations use the standard system call @code{free}. No reclamation is
18029 performed when the pool goes out of scope. For performance reasons, the
18030 standard default Ada allocators/deallocators do not use any explicit storage
18031 pools but if they did, they could use this storage pool without any change in
18032 behavior. That is why this storage pool is used  when the user
18033 manages to make the default implicit allocator explicit as in this example:
18034 @smallexample @c ada
18035    type T1 is access Something;
18036     -- no Storage pool is defined for T2
18037    type T2 is access Something_Else;
18038    for T2'Storage_Pool use T1'Storage_Pool;
18039    -- the above is equivalent to
18040    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18041 @end smallexample
18042
18043 @noindent
18044 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18045 pool. The allocation strategy is similar to @code{Pool_Local}'s
18046 except that the all
18047 storage allocated with this pool is reclaimed when the pool object goes out of
18048 scope. This pool provides a explicit mechanism similar to the implicit one
18049 provided by several Ada 83 compilers for allocations performed through a local
18050 access type and whose purpose was to reclaim memory when exiting the
18051 scope of a given local access. As an example, the following program does not
18052 leak memory even though it does not perform explicit deallocation:
18053
18054 @smallexample @c ada
18055 with System.Pool_Local;
18056 procedure Pooloc1 is
18057    procedure Internal is
18058       type A is access Integer;
18059       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18060       for A'Storage_Pool use X;
18061       v : A;
18062    begin
18063       for I in  1 .. 50 loop
18064          v := new Integer;
18065       end loop;
18066    end Internal;
18067 begin
18068    for I in  1 .. 100 loop
18069       Internal;
18070    end loop;
18071 end Pooloc1;
18072 @end smallexample
18073
18074 @noindent
18075 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18076 @code{Storage_Size} is specified for an access type.
18077 The whole storage for the pool is
18078 allocated at once, usually on the stack at the point where the access type is
18079 elaborated. It is automatically reclaimed when exiting the scope where the
18080 access type is defined. This package is not intended to be used directly by the
18081 user and it is implicitly used for each such declaration:
18082
18083 @smallexample @c ada
18084    type T1 is access Something;
18085    for T1'Storage_Size use 10_000;
18086 @end smallexample
18087
18088
18089 @node The GNAT Debug Pool Facility
18090 @section The GNAT Debug Pool Facility
18091 @findex Debug Pool
18092 @cindex storage, pool, memory corruption
18093
18094 @noindent
18095 The use of unchecked deallocation and unchecked conversion can easily
18096 lead to incorrect memory references. The problems generated by such
18097 references are usually difficult to tackle because the symptoms can be
18098 very remote from the origin of the problem. In such cases, it is
18099 very helpful to detect the problem as early as possible. This is the
18100 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18101
18102 In order to use the GNAT specific debugging pool, the user must
18103 associate a debug pool object with each of the access types that may be
18104 related to suspected memory problems. See Ada Reference Manual 13.11.
18105 @smallexample @c ada
18106 type Ptr is access Some_Type;
18107 Pool : GNAT.Debug_Pools.Debug_Pool;
18108 for Ptr'Storage_Pool use Pool;
18109 @end smallexample
18110
18111 @noindent
18112 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18113 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18114 allow the user to redefine allocation and deallocation strategies. They
18115 also provide a checkpoint for each dereference, through the use of
18116 the primitive operation @code{Dereference} which is implicitly called at
18117 each dereference of an access value.
18118
18119 Once an access type has been associated with a debug pool, operations on
18120 values of the type may raise four distinct exceptions,
18121 which correspond to four potential kinds of memory corruption:
18122 @itemize @bullet
18123 @item
18124 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18125 @item
18126 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18127 @item
18128 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18129 @item
18130 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18131 @end itemize
18132
18133 @noindent
18134 For types associated with a Debug_Pool, dynamic allocation is performed using
18135 the standard GNAT allocation routine. References to all allocated chunks of
18136 memory are kept in an internal dictionary. Several deallocation strategies are
18137 provided, whereupon the user can choose to release the memory to the system,
18138 keep it allocated for further invalid access checks, or fill it with an easily
18139 recognizable pattern for debug sessions. The memory pattern is the old IBM
18140 hexadecimal convention: @code{16#DEADBEEF#}.
18141
18142 See the documentation in the file g-debpoo.ads for more information on the
18143 various strategies.
18144
18145 Upon each dereference, a check is made that the access value denotes a
18146 properly allocated memory location. Here is a complete example of use of
18147 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18148 @smallexample @c ada
18149 @iftex
18150 @leftskip=0cm
18151 @end iftex
18152 with Gnat.Io; use Gnat.Io;
18153 with Unchecked_Deallocation;
18154 with Unchecked_Conversion;
18155 with GNAT.Debug_Pools;
18156 with System.Storage_Elements;
18157 with Ada.Exceptions; use Ada.Exceptions;
18158 procedure Debug_Pool_Test is
18159
18160    type T is access Integer;
18161    type U is access all T;
18162
18163    P : GNAT.Debug_Pools.Debug_Pool;
18164    for T'Storage_Pool use P;
18165
18166    procedure Free is new Unchecked_Deallocation (Integer, T);
18167    function UC is new Unchecked_Conversion (U, T);
18168    A, B : aliased T;
18169
18170    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18171
18172 begin
18173    Info (P);
18174    A := new Integer;
18175    B := new Integer;
18176    B := A;
18177    Info (P);
18178    Free (A);
18179    begin
18180       Put_Line (Integer'Image(B.all));
18181    exception
18182       when E : others => Put_Line ("raised: " & Exception_Name (E));
18183    end;
18184    begin
18185       Free (B);
18186    exception
18187       when E : others => Put_Line ("raised: " & Exception_Name (E));
18188    end;
18189    B := UC(A'Access);
18190    begin
18191       Put_Line (Integer'Image(B.all));
18192    exception
18193       when E : others => Put_Line ("raised: " & Exception_Name (E));
18194    end;
18195    begin
18196       Free (B);
18197    exception
18198       when E : others => Put_Line ("raised: " & Exception_Name (E));
18199    end;
18200    Info (P);
18201 end Debug_Pool_Test;
18202 @end smallexample
18203
18204 @noindent
18205 The debug pool mechanism provides the following precise diagnostics on the
18206 execution of this erroneous program:
18207 @smallexample
18208 Debug Pool info:
18209   Total allocated bytes :  0
18210   Total deallocated bytes :  0
18211   Current Water Mark:  0
18212   High Water Mark:  0
18213
18214 Debug Pool info:
18215   Total allocated bytes :  8
18216   Total deallocated bytes :  0
18217   Current Water Mark:  8
18218   High Water Mark:  8
18219
18220 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18221 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18222 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18223 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18224 Debug Pool info:
18225   Total allocated bytes :  8
18226   Total deallocated bytes :  4
18227   Current Water Mark:  4
18228   High Water Mark:  8
18229 @end smallexample
18230
18231 @ifclear vms
18232 @node The gnatmem Tool
18233 @section The @command{gnatmem} Tool
18234 @findex gnatmem
18235
18236 @noindent
18237 The @code{gnatmem} utility monitors dynamic allocation and
18238 deallocation activity in a program, and displays information about
18239 incorrect deallocations and possible sources of memory leaks.
18240 It provides three type of information:
18241 @itemize @bullet
18242 @item
18243 General information concerning memory management, such as the total
18244 number of allocations and deallocations, the amount of allocated
18245 memory and the high water mark, i.e. the largest amount of allocated
18246 memory in the course of program execution.
18247
18248 @item
18249 Backtraces for all incorrect deallocations, that is to say deallocations
18250 which do not correspond to a valid allocation.
18251
18252 @item
18253 Information on each allocation that is potentially the origin of a memory
18254 leak.
18255 @end itemize
18256
18257 @menu
18258 * Running gnatmem::
18259 * Switches for gnatmem::
18260 * Example of gnatmem Usage::
18261 @end menu
18262
18263 @node Running gnatmem
18264 @subsection Running @code{gnatmem}
18265
18266 @noindent
18267 @code{gnatmem} makes use of the output created by the special version of
18268 allocation and deallocation routines that record call information. This
18269 allows to obtain accurate dynamic memory usage history at a minimal cost to
18270 the execution speed. Note however, that @code{gnatmem} is not supported on
18271 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18272 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18273
18274 @noindent
18275 The @code{gnatmem} command has the form
18276
18277 @smallexample
18278    $ gnatmem [switches] user_program
18279 @end smallexample
18280
18281 @noindent
18282 The program must have been linked with the instrumented version of the
18283 allocation and deallocation routines. This is done by linking with the
18284 @file{libgmem.a} library. For correct symbolic backtrace information,
18285 the user program should be compiled with debugging options
18286 @ref{Switches for gcc}. For example to build @file{my_program}:
18287
18288 @smallexample
18289 $ gnatmake -g my_program -largs -lgmem
18290 @end smallexample
18291
18292 @noindent
18293 When running @file{my_program} the file @file{gmem.out} is produced. This file
18294 contains information about all allocations and deallocations done by the
18295 program. It is produced by the instrumented allocations and
18296 deallocations routines and will be used by @code{gnatmem}.
18297
18298 @noindent
18299 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18300 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18301 @code{-i} switch, gnatmem will assume that this file can be found in the
18302 current directory. For example, after you have executed @file{my_program},
18303 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18304
18305 @smallexample
18306 $ gnatmem my_program
18307 @end smallexample
18308
18309 @noindent
18310 This will produce the output with the following format:
18311
18312 *************** debut cc
18313 @smallexample
18314 $ gnatmem my_program
18315
18316 Global information
18317 ------------------
18318    Total number of allocations        :  45
18319    Total number of deallocations      :   6
18320    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18321    High Water Mark                    :  11.40 Kilobytes
18322
18323 .
18324 .
18325 .
18326 Allocation Root # 2
18327 -------------------
18328  Number of non freed allocations    :  11
18329  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18330  High Water Mark                    :   1.27 Kilobytes
18331  Backtrace                          :
18332    my_program.adb:23 my_program.alloc
18333 .
18334 .
18335 .
18336 @end smallexample
18337
18338 The first block of output gives general information. In this case, the
18339 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18340 Unchecked_Deallocation routine occurred.
18341
18342 @noindent
18343 Subsequent paragraphs display  information on all allocation roots.
18344 An allocation root is a specific point in the execution of the program
18345 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18346 construct. This root is represented by an execution backtrace (or subprogram
18347 call stack). By default the backtrace depth for allocations roots is 1, so
18348 that a root corresponds exactly to a source location. The backtrace can
18349 be made deeper, to make the root more specific.
18350
18351 @node Switches for gnatmem
18352 @subsection Switches for @code{gnatmem}
18353
18354 @noindent
18355 @code{gnatmem} recognizes the following switches:
18356
18357 @table @option
18358
18359 @item -q
18360 @cindex @option{-q} (@code{gnatmem})
18361 Quiet. Gives the minimum output needed to identify the origin of the
18362 memory leaks. Omits statistical information.
18363
18364 @item @var{N}
18365 @cindex @var{N} (@code{gnatmem})
18366 N is an integer literal (usually between 1 and 10) which controls the
18367 depth of the backtraces defining allocation root. The default value for
18368 N is 1. The deeper the backtrace, the more precise the localization of
18369 the root. Note that the total number of roots can depend on this
18370 parameter. This parameter must be specified @emph{before} the name of the
18371 executable to be analyzed, to avoid ambiguity.
18372
18373 @item -b n
18374 @cindex @option{-b} (@code{gnatmem})
18375 This switch has the same effect as just depth parameter.
18376
18377 @item -i @var{file}
18378 @cindex @option{-i} (@code{gnatmem})
18379 Do the @code{gnatmem} processing starting from @file{file}, rather than
18380 @file{gmem.out} in the current directory.
18381
18382 @item -m n
18383 @cindex @option{-m} (@code{gnatmem})
18384 This switch causes @code{gnatmem} to mask the allocation roots that have less
18385 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18386 examine even the roots that didn't result in leaks.
18387
18388 @item -s order
18389 @cindex @option{-s} (@code{gnatmem})
18390 This switch causes @code{gnatmem} to sort the allocation roots according to the
18391 specified order of sort criteria, each identified by a single letter. The
18392 currently supported criteria are @code{n, h, w} standing respectively for
18393 number of unfreed allocations, high watermark, and final watermark
18394 corresponding to a specific root. The default order is @code{nwh}.
18395
18396 @end table
18397
18398 @node Example of gnatmem Usage
18399 @subsection Example of @code{gnatmem} Usage
18400
18401 @noindent
18402 The following example shows the use of @code{gnatmem}
18403 on a simple memory-leaking program.
18404 Suppose that we have the following Ada program:
18405
18406 @smallexample @c ada
18407 @group
18408 @cartouche
18409 with Unchecked_Deallocation;
18410 procedure Test_Gm is
18411
18412    type T is array (1..1000) of Integer;
18413    type Ptr is access T;
18414    procedure Free is new Unchecked_Deallocation (T, Ptr);
18415    A : Ptr;
18416
18417    procedure My_Alloc is
18418    begin
18419       A := new T;
18420    end My_Alloc;
18421
18422    procedure My_DeAlloc is
18423       B : Ptr := A;
18424    begin
18425       Free (B);
18426    end My_DeAlloc;
18427
18428 begin
18429    My_Alloc;
18430    for I in 1 .. 5 loop
18431       for J in I .. 5 loop
18432          My_Alloc;
18433       end loop;
18434       My_Dealloc;
18435    end loop;
18436 end;
18437 @end cartouche
18438 @end group
18439 @end smallexample
18440
18441 @noindent
18442 The program needs to be compiled with debugging option and linked with
18443 @code{gmem} library:
18444
18445 @smallexample
18446 $ gnatmake -g test_gm -largs -lgmem
18447 @end smallexample
18448
18449 @noindent
18450 Then we execute the program as usual:
18451
18452 @smallexample
18453 $ test_gm
18454 @end smallexample
18455
18456 @noindent
18457 Then @code{gnatmem} is invoked simply with
18458 @smallexample
18459 $ gnatmem test_gm
18460 @end smallexample
18461
18462 @noindent
18463 which produces the following output (result may vary on different platforms):
18464
18465 @smallexample
18466 Global information
18467 ------------------
18468    Total number of allocations        :  18
18469    Total number of deallocations      :   5
18470    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18471    High Water Mark                    :  56.90 Kilobytes
18472
18473 Allocation Root # 1
18474 -------------------
18475  Number of non freed allocations    :  11
18476  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18477  High Water Mark                    :  46.88 Kilobytes
18478  Backtrace                          :
18479    test_gm.adb:11 test_gm.my_alloc
18480
18481 Allocation Root # 2
18482 -------------------
18483  Number of non freed allocations    :   1
18484  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18485  High Water Mark                    :  10.02 Kilobytes
18486  Backtrace                          :
18487    s-secsta.adb:81 system.secondary_stack.ss_init
18488
18489 Allocation Root # 3
18490 -------------------
18491  Number of non freed allocations    :   1
18492  Final Water Mark (non freed mem)   :  12 Bytes
18493  High Water Mark                    :  12 Bytes
18494  Backtrace                          :
18495    s-secsta.adb:181 system.secondary_stack.ss_init
18496 @end smallexample
18497
18498 @noindent
18499 Note that the GNAT run time contains itself a certain number of
18500 allocations that have no  corresponding deallocation,
18501 as shown here for root #2 and root
18502 #3. This is a normal behavior when the number of non freed allocations
18503 is one, it allocates dynamic data structures that the run time needs for
18504 the complete lifetime of the program. Note also that there is only one
18505 allocation root in the user program with a single line back trace:
18506 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18507 program shows that 'My_Alloc' is called at 2 different points in the
18508 source (line 21 and line 24). If those two allocation roots need to be
18509 distinguished, the backtrace depth parameter can be used:
18510
18511 @smallexample
18512 $ gnatmem 3 test_gm
18513 @end smallexample
18514
18515 @noindent
18516 which will give the following output:
18517
18518 @smallexample
18519 Global information
18520 ------------------
18521    Total number of allocations        :  18
18522    Total number of deallocations      :   5
18523    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18524    High Water Mark                    :  56.90 Kilobytes
18525
18526 Allocation Root # 1
18527 -------------------
18528  Number of non freed allocations    :  10
18529  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18530  High Water Mark                    :  42.97 Kilobytes
18531  Backtrace                          :
18532    test_gm.adb:11 test_gm.my_alloc
18533    test_gm.adb:24 test_gm
18534    b_test_gm.c:52 main
18535
18536 Allocation Root # 2
18537 -------------------
18538  Number of non freed allocations    :   1
18539  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18540  High Water Mark                    :  10.02 Kilobytes
18541  Backtrace                          :
18542    s-secsta.adb:81  system.secondary_stack.ss_init
18543    s-secsta.adb:283 <system__secondary_stack___elabb>
18544    b_test_gm.c:33   adainit
18545
18546 Allocation Root # 3
18547 -------------------
18548  Number of non freed allocations    :   1
18549  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18550  High Water Mark                    :   3.91 Kilobytes
18551  Backtrace                          :
18552    test_gm.adb:11 test_gm.my_alloc
18553    test_gm.adb:21 test_gm
18554    b_test_gm.c:52 main
18555
18556 Allocation Root # 4
18557 -------------------
18558  Number of non freed allocations    :   1
18559  Final Water Mark (non freed mem)   :  12 Bytes
18560  High Water Mark                    :  12 Bytes
18561  Backtrace                          :
18562    s-secsta.adb:181 system.secondary_stack.ss_init
18563    s-secsta.adb:283 <system__secondary_stack___elabb>
18564    b_test_gm.c:33   adainit
18565 @end smallexample
18566
18567 @noindent
18568 The allocation root #1 of the first example has been split in 2 roots #1
18569 and #3 thanks to the more precise associated backtrace.
18570
18571 @end ifclear
18572
18573 @node Creating Sample Bodies Using gnatstub
18574 @chapter Creating Sample Bodies Using @command{gnatstub}
18575 @findex gnatstub
18576
18577 @noindent
18578 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18579 for library unit declarations.
18580
18581 To create a body stub, @command{gnatstub} has to compile the library
18582 unit declaration. Therefore, bodies can be created only for legal
18583 library units. Moreover, if a library unit depends semantically upon
18584 units located outside the current directory, you have to provide
18585 the source search path when calling @command{gnatstub}, see the description
18586 of @command{gnatstub} switches below.
18587
18588 @menu
18589 * Running gnatstub::
18590 * Switches for gnatstub::
18591 @end menu
18592
18593 @node Running gnatstub
18594 @section Running @command{gnatstub}
18595
18596 @noindent
18597 @command{gnatstub} has the command-line interface of the form
18598
18599 @smallexample
18600 $ gnatstub [switches] filename [directory]
18601 @end smallexample
18602
18603 @noindent
18604 where
18605 @table @emph
18606 @item filename
18607 is the name of the source file that contains a library unit declaration
18608 for which a body must be created. The file name may contain the path
18609 information.
18610 The file name does not have to follow the GNAT file name conventions. If the
18611 name
18612 does not follow GNAT file naming conventions, the name of the body file must
18613 be provided
18614 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18615 If the file name follows the GNAT file naming
18616 conventions and the name of the body file is not provided,
18617 @command{gnatstub}
18618 creates the name
18619 of the body file from the argument file name by replacing the @file{.ads}
18620 suffix
18621 with the @file{.adb} suffix.
18622
18623 @item directory
18624 indicates the directory in which the body stub is to be placed (the default
18625 is the
18626 current directory)
18627
18628 @item switches
18629 is an optional sequence of switches as described in the next section
18630 @end table
18631
18632 @node Switches for gnatstub
18633 @section Switches for @command{gnatstub}
18634
18635 @table @option
18636 @c !sort!
18637
18638 @item ^-f^/FULL^
18639 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18640 If the destination directory already contains a file with the name of the
18641 body file
18642 for the argument spec file, replace it with the generated body stub.
18643
18644 @item ^-hs^/HEADER=SPEC^
18645 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18646 Put the comment header (i.e., all the comments preceding the
18647 compilation unit) from the source of the library unit declaration
18648 into the body stub.
18649
18650 @item ^-hg^/HEADER=GENERAL^
18651 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18652 Put a sample comment header into the body stub.
18653
18654 @ifclear vms
18655 @item -IDIR
18656 @cindex @option{-IDIR} (@command{gnatstub})
18657 @itemx -I-
18658 @cindex @option{-I-} (@command{gnatstub})
18659 @end ifclear
18660 @ifset vms
18661 @item /NOCURRENT_DIRECTORY
18662 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18663 @end ifset
18664 ^These switches have ^This switch has^ the same meaning as in calls to
18665 @command{gcc}.
18666 ^They define ^It defines ^ the source search path in the call to
18667 @command{gcc} issued
18668 by @command{gnatstub} to compile an argument source file.
18669
18670 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18671 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18672 This switch has the same meaning as in calls to @command{gcc}.
18673 It defines the additional configuration file to be passed to the call to
18674 @command{gcc} issued
18675 by @command{gnatstub} to compile an argument source file.
18676
18677 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18678 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18679 (@var{n} is a non-negative integer). Set the maximum line length in the
18680 body stub to @var{n}; the default is 79. The maximum value that can be
18681 specified is 32767. Note that in the special case of configuration
18682 pragma files, the maximum is always 32767 regardless of whether or
18683 not this switch appears.
18684
18685 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18686 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18687 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18688 the generated body sample to @var{n}.
18689 The default indentation is 3.
18690
18691 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18692 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18693 Order local bodies alphabetically. (By default local bodies are ordered
18694 in the same way as the corresponding local specs in the argument spec file.)
18695
18696 @item ^-i^/INDENTATION=^@var{n}
18697 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18698 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18699
18700 @item ^-k^/TREE_FILE=SAVE^
18701 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18702 Do not remove the tree file (i.e., the snapshot of the compiler internal
18703 structures used by @command{gnatstub}) after creating the body stub.
18704
18705 @item ^-l^/LINE_LENGTH=^@var{n}
18706 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18707 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18708
18709 @item ^-o^/BODY=^@var{body-name}
18710 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18711 Body file name.  This should be set if the argument file name does not
18712 follow
18713 the GNAT file naming
18714 conventions. If this switch is omitted the default name for the body will be
18715 obtained
18716 from the argument file name according to the GNAT file naming conventions.
18717
18718 @item ^-q^/QUIET^
18719 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18720 Quiet mode: do not generate a confirmation when a body is
18721 successfully created, and do not generate a message when a body is not
18722 required for an
18723 argument unit.
18724
18725 @item ^-r^/TREE_FILE=REUSE^
18726 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18727 Reuse the tree file (if it exists) instead of creating it.  Instead of
18728 creating the tree file for the library unit declaration, @command{gnatstub}
18729 tries to find it in the current directory and use it for creating
18730 a body. If the tree file is not found, no body is created. This option
18731 also implies @option{^-k^/SAVE^}, whether or not
18732 the latter is set explicitly.
18733
18734 @item ^-t^/TREE_FILE=OVERWRITE^
18735 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18736 Overwrite the existing tree file.  If the current directory already
18737 contains the file which, according to the GNAT file naming rules should
18738 be considered as a tree file for the argument source file,
18739 @command{gnatstub}
18740 will refuse to create the tree file needed to create a sample body
18741 unless this option is set.
18742
18743 @item ^-v^/VERBOSE^
18744 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18745 Verbose mode: generate version information.
18746
18747 @end table
18748
18749 @node Other Utility Programs
18750 @chapter Other Utility Programs
18751
18752 @noindent
18753 This chapter discusses some other utility programs available in the Ada
18754 environment.
18755
18756 @menu
18757 * Using Other Utility Programs with GNAT::
18758 * The External Symbol Naming Scheme of GNAT::
18759 @ifclear vms
18760 * Ada Mode for Glide::
18761 @end ifclear
18762 * Converting Ada Files to html with gnathtml::
18763 * Installing gnathtml::
18764 @ifset vms
18765 * LSE::
18766 * Profiling::
18767 @end ifset
18768 @end menu
18769
18770 @node Using Other Utility Programs with GNAT
18771 @section Using Other Utility Programs with GNAT
18772
18773 @noindent
18774 The object files generated by GNAT are in standard system format and in
18775 particular the debugging information uses this format. This means
18776 programs generated by GNAT can be used with existing utilities that
18777 depend on these formats.
18778
18779 @ifclear vms
18780 In general, any utility program that works with C will also often work with
18781 Ada programs generated by GNAT. This includes software utilities such as
18782 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18783 as Purify.
18784 @end ifclear
18785
18786 @node The External Symbol Naming Scheme of GNAT
18787 @section The External Symbol Naming Scheme of GNAT
18788
18789 @noindent
18790 In order to interpret the output from GNAT, when using tools that are
18791 originally intended for use with other languages, it is useful to
18792 understand the conventions used to generate link names from the Ada
18793 entity names.
18794
18795 All link names are in all lowercase letters. With the exception of library
18796 procedure names, the mechanism used is simply to use the full expanded
18797 Ada name with dots replaced by double underscores. For example, suppose
18798 we have the following package spec:
18799
18800 @smallexample @c ada
18801 @group
18802 @cartouche
18803 package QRS is
18804    MN : Integer;
18805 end QRS;
18806 @end cartouche
18807 @end group
18808 @end smallexample
18809
18810 @noindent
18811 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18812 the corresponding link name is @code{qrs__mn}.
18813 @findex Export
18814 Of course if a @code{pragma Export} is used this may be overridden:
18815
18816 @smallexample @c ada
18817 @group
18818 @cartouche
18819 package Exports is
18820    Var1 : Integer;
18821    pragma Export (Var1, C, External_Name => "var1_name");
18822    Var2 : Integer;
18823    pragma Export (Var2, C, Link_Name => "var2_link_name");
18824 end Exports;
18825 @end cartouche
18826 @end group
18827 @end smallexample
18828
18829 @noindent
18830 In this case, the link name for @var{Var1} is whatever link name the
18831 C compiler would assign for the C function @var{var1_name}. This typically
18832 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18833 system conventions, but other possibilities exist. The link name for
18834 @var{Var2} is @var{var2_link_name}, and this is not operating system
18835 dependent.
18836
18837 @findex _main
18838 One exception occurs for library level procedures. A potential ambiguity
18839 arises between the required name @code{_main} for the C main program,
18840 and the name we would otherwise assign to an Ada library level procedure
18841 called @code{Main} (which might well not be the main program).
18842
18843 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18844 names. So if we have a library level procedure such as
18845
18846 @smallexample @c ada
18847 @group
18848 @cartouche
18849 procedure Hello (S : String);
18850 @end cartouche
18851 @end group
18852 @end smallexample
18853
18854 @noindent
18855 the external name of this procedure will be @var{_ada_hello}.
18856
18857 @ifclear vms
18858 @node Ada Mode for Glide
18859 @section Ada Mode for @code{Glide}
18860 @cindex Ada mode (for Glide)
18861
18862 @noindent
18863 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18864 user to understand and navigate existing code, and facilitates writing
18865 new code. It furthermore provides some utility functions for easier
18866 integration of standard Emacs features when programming in Ada.
18867
18868 Its general features include:
18869
18870 @itemize @bullet
18871 @item
18872 An Integrated Development Environment with functionality such as the
18873 following
18874
18875 @itemize @bullet
18876 @item
18877 ``Project files'' for configuration-specific aspects
18878 (e.g. directories and compilation options)
18879
18880 @item
18881 Compiling and stepping through error messages.
18882
18883 @item
18884 Running and debugging an applications within Glide.
18885 @end itemize
18886
18887 @item
18888 Pull-down menus
18889
18890 @item
18891 User configurability
18892 @end itemize
18893
18894 Some of the specific Ada mode features are:
18895
18896 @itemize @bullet
18897 @item
18898 Functions for easy and quick stepping through Ada code
18899
18900 @item
18901 Getting cross reference information for identifiers (e.g., finding a
18902 defining occurrence)
18903
18904 @item
18905 Displaying an index menu of types and subprograms, allowing
18906 direct selection for browsing
18907
18908 @item
18909 Automatic color highlighting of the various Ada entities
18910 @end itemize
18911
18912 Glide directly supports writing Ada code, via several facilities:
18913
18914 @itemize @bullet
18915 @item
18916 Switching between spec and body files with possible
18917 autogeneration of body files
18918
18919 @item
18920 Automatic formating of subprogram parameter lists
18921
18922 @item
18923 Automatic indentation according to Ada syntax
18924
18925 @item
18926 Automatic completion of identifiers
18927
18928 @item
18929 Automatic (and configurable) casing of identifiers, keywords, and attributes
18930
18931 @item
18932 Insertion of syntactic templates
18933
18934 @item
18935 Block commenting / uncommenting
18936 @end itemize
18937
18938 @noindent
18939 For more information, please refer to the online documentation
18940 available in the @code{Glide} @result{} @code{Help} menu.
18941 @end ifclear
18942
18943 @node Converting Ada Files to html with gnathtml
18944 @section Converting Ada Files to HTML with @code{gnathtml}
18945
18946 @noindent
18947 This @code{Perl} script allows Ada source files to be browsed using
18948 standard Web browsers. For installation procedure, see the section
18949 @xref{Installing gnathtml}.
18950
18951 Ada reserved keywords are highlighted in a bold font and Ada comments in
18952 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18953 switch to suppress the generation of cross-referencing information, user
18954 defined variables and types will appear in a different color; you will
18955 be able to click on any identifier and go to its declaration.
18956
18957 The command line is as follow:
18958 @smallexample
18959 $ perl gnathtml.pl [switches] ada-files
18960 @end smallexample
18961
18962 @noindent
18963 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18964 an html file for every ada file, and a global file called @file{index.htm}.
18965 This file is an index of every identifier defined in the files.
18966
18967 The available switches are the following ones :
18968
18969 @table @option
18970 @item -83
18971 @cindex @option{-83} (@code{gnathtml})
18972 Only the subset on the Ada 83 keywords will be highlighted, not the full
18973 Ada 95 keywords set.
18974
18975 @item -cc @var{color}
18976 @cindex @option{-cc} (@code{gnathtml})
18977 This option allows you to change the color used for comments. The default
18978 value is green. The color argument can be any name accepted by html.
18979
18980 @item -d
18981 @cindex @option{-d} (@code{gnathtml})
18982 If the ada files depend on some other files (using for instance the
18983 @code{with} command, the latter will also be converted to html.
18984 Only the files in the user project will be converted to html, not the files
18985 in the run-time library itself.
18986
18987 @item -D
18988 @cindex @option{-D} (@code{gnathtml})
18989 This command is the same as @option{-d} above, but @command{gnathtml} will
18990 also look for files in the run-time library, and generate html files for them.
18991
18992 @item -ext @var{extension}
18993 @cindex @option{-ext} (@code{gnathtml})
18994 This option allows you to change the extension of the generated HTML files.
18995 If you do not specify an extension, it will default to @file{htm}.
18996
18997 @item -f
18998 @cindex @option{-f} (@code{gnathtml})
18999 By default, gnathtml will generate html links only for global entities
19000 ('with'ed units, global variables and types,...). If you specify the
19001 @option{-f} on the command line, then links will be generated for local
19002 entities too.
19003
19004 @item -l @var{number}
19005 @cindex @option{-l} (@code{gnathtml})
19006 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
19007 will number the html files every @var{number} line.
19008
19009 @item -I @var{dir}
19010 @cindex @option{-I} (@code{gnathtml})
19011 Specify a directory to search for library files (@file{.ALI} files) and
19012 source files. You can provide several -I switches on the command line,
19013 and the directories will be parsed in the order of the command line.
19014
19015 @item -o @var{dir}
19016 @cindex @option{-o} (@code{gnathtml})
19017 Specify the output directory for html files. By default, gnathtml will
19018 saved the generated html files in a subdirectory named @file{html/}.
19019
19020 @item -p @var{file}
19021 @cindex @option{-p} (@code{gnathtml})
19022 If you are using Emacs and the most recent Emacs Ada mode, which provides
19023 a full Integrated Development Environment for compiling, checking,
19024 running and debugging applications, you may use @file{.gpr} files
19025 to give the directories where Emacs can find sources and object files.
19026
19027 Using this switch, you can tell gnathtml to use these files. This allows
19028 you to get an html version of your application, even if it is spread
19029 over multiple directories.
19030
19031 @item -sc @var{color}
19032 @cindex @option{-sc} (@code{gnathtml})
19033 This option allows you to change the color used for symbol definitions.
19034 The default value is red. The color argument can be any name accepted by html.
19035
19036 @item -t @var{file}
19037 @cindex @option{-t} (@code{gnathtml})
19038 This switch provides the name of a file. This file contains a list of
19039 file names to be converted, and the effect is exactly as though they had
19040 appeared explicitly on the command line. This
19041 is the recommended way to work around the command line length limit on some
19042 systems.
19043
19044 @end table
19045
19046 @node Installing gnathtml
19047 @section Installing @code{gnathtml}
19048
19049 @noindent
19050 @code{Perl} needs to be installed on your machine to run this script.
19051 @code{Perl} is freely available for almost every architecture and
19052 Operating System via the Internet.
19053
19054 On Unix systems, you  may want to modify  the  first line of  the script
19055 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19056 is. The syntax of this line is :
19057 @smallexample
19058 #!full_path_name_to_perl
19059 @end smallexample
19060
19061 @noindent
19062 Alternatively, you may run the script using the following command line:
19063
19064 @smallexample
19065 $ perl gnathtml.pl [switches] files
19066 @end smallexample
19067
19068 @ifset vms
19069 @node LSE
19070 @section LSE
19071 @findex LSE
19072
19073 @noindent
19074 The GNAT distribution provides an Ada 95 template for the Digital Language
19075 Sensitive Editor (LSE), a component of DECset. In order to
19076 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19077
19078 @node Profiling
19079 @section Profiling
19080 @findex PCA
19081
19082 @noindent
19083 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
19084 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19085 the collection phase with the /DEBUG qualifier.
19086
19087 @smallexample
19088 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19089 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19090 $ RUN/DEBUG <PROGRAM_NAME>
19091 @end smallexample
19092 @noindent
19093 @end ifset
19094
19095 @node Running and Debugging Ada Programs
19096 @chapter Running and Debugging Ada Programs
19097 @cindex Debugging
19098
19099 @noindent
19100 This chapter discusses how to debug Ada programs.
19101 @ifset vms
19102 It applies to the Alpha OpenVMS platform;
19103 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
19104 @end ifset
19105
19106 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19107
19108 @enumerate
19109 @item
19110 The illegality may be a violation of the static semantics of Ada. In
19111 that case GNAT diagnoses the constructs in the program that are illegal.
19112 It is then a straightforward matter for the user to modify those parts of
19113 the program.
19114
19115 @item
19116 The illegality may be a violation of the dynamic semantics of Ada. In
19117 that case the program compiles and executes, but may generate incorrect
19118 results, or may terminate abnormally with some exception.
19119
19120 @item
19121 When presented with a program that contains convoluted errors, GNAT
19122 itself may terminate abnormally without providing full diagnostics on
19123 the incorrect user program.
19124 @end enumerate
19125
19126 @menu
19127 * The GNAT Debugger GDB::
19128 * Running GDB::
19129 * Introduction to GDB Commands::
19130 * Using Ada Expressions::
19131 * Calling User-Defined Subprograms::
19132 * Using the Next Command in a Function::
19133 * Ada Exceptions::
19134 * Ada Tasks::
19135 * Debugging Generic Units::
19136 * GNAT Abnormal Termination or Failure to Terminate::
19137 * Naming Conventions for GNAT Source Files::
19138 * Getting Internal Debugging Information::
19139 * Stack Traceback::
19140 @end menu
19141
19142 @cindex Debugger
19143 @findex gdb
19144
19145 @node The GNAT Debugger GDB
19146 @section The GNAT Debugger GDB
19147
19148 @noindent
19149 @code{GDB} is a general purpose, platform-independent debugger that
19150 can be used to debug mixed-language programs compiled with @command{gcc},
19151 and in particular is capable of debugging Ada programs compiled with
19152 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19153 complex Ada data structures.
19154
19155 The manual @cite{Debugging with GDB}
19156 @ifset vms
19157 , located in the GNU:[DOCS] directory,
19158 @end ifset
19159 contains full details on the usage of @code{GDB}, including a section on
19160 its usage on programs. This manual should be consulted for full
19161 details. The section that follows is a brief introduction to the
19162 philosophy and use of @code{GDB}.
19163
19164 When GNAT programs are compiled, the compiler optionally writes debugging
19165 information into the generated object file, including information on
19166 line numbers, and on declared types and variables. This information is
19167 separate from the generated code. It makes the object files considerably
19168 larger, but it does not add to the size of the actual executable that
19169 will be loaded into memory, and has no impact on run-time performance. The
19170 generation of debug information is triggered by the use of the
19171 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19172 the compilations. It is important to emphasize that the use of these
19173 options does not change the generated code.
19174
19175 The debugging information is written in standard system formats that
19176 are used by many tools, including debuggers and profilers. The format
19177 of the information is typically designed to describe C types and
19178 semantics, but GNAT implements a translation scheme which allows full
19179 details about Ada types and variables to be encoded into these
19180 standard C formats. Details of this encoding scheme may be found in
19181 the file exp_dbug.ads in the GNAT source distribution. However, the
19182 details of this encoding are, in general, of no interest to a user,
19183 since @code{GDB} automatically performs the necessary decoding.
19184
19185 When a program is bound and linked, the debugging information is
19186 collected from the object files, and stored in the executable image of
19187 the program. Again, this process significantly increases the size of
19188 the generated executable file, but it does not increase the size of
19189 the executable program itself. Furthermore, if this program is run in
19190 the normal manner, it runs exactly as if the debug information were
19191 not present, and takes no more actual memory.
19192
19193 However, if the program is run under control of @code{GDB}, the
19194 debugger is activated.  The image of the program is loaded, at which
19195 point it is ready to run.  If a run command is given, then the program
19196 will run exactly as it would have if @code{GDB} were not present. This
19197 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19198 entirely non-intrusive until a breakpoint is encountered.  If no
19199 breakpoint is ever hit, the program will run exactly as it would if no
19200 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19201 the debugging information and can respond to user commands to inspect
19202 variables, and more generally to report on the state of execution.
19203
19204 @c **************
19205 @node Running GDB
19206 @section Running GDB
19207
19208 @noindent
19209 The debugger can be launched directly and simply from @code{glide} or
19210 through its graphical interface: @code{gvd}. It can also be used
19211 directly in text mode. Here is described the basic use of @code{GDB}
19212 in text mode. All the commands described below can be used in the
19213 @code{gvd} console window even though there is usually other more
19214 graphical ways to achieve the same goals.
19215
19216 @ifclear vms
19217 @noindent
19218 The command to run the graphical interface of the debugger is
19219 @smallexample
19220 $ gvd program
19221 @end smallexample
19222 @end ifclear
19223
19224 @noindent
19225 The command to run @code{GDB} in text mode is
19226
19227 @smallexample
19228 $ ^gdb program^$ GDB PROGRAM^
19229 @end smallexample
19230
19231 @noindent
19232 where @code{^program^PROGRAM^} is the name of the executable file. This
19233 activates the debugger and results in a prompt for debugger commands.
19234 The simplest command is simply @code{run}, which causes the program to run
19235 exactly as if the debugger were not present. The following section
19236 describes some of the additional commands that can be given to @code{GDB}.
19237
19238 @c *******************************
19239 @node Introduction to GDB Commands
19240 @section Introduction to GDB Commands
19241
19242 @noindent
19243 @code{GDB} contains a large repertoire of commands. The manual
19244 @cite{Debugging with GDB}
19245 @ifset vms
19246 , located in the GNU:[DOCS] directory,
19247 @end ifset
19248 includes extensive documentation on the use
19249 of these commands, together with examples of their use. Furthermore,
19250 the command @var{help} invoked from within @code{GDB} activates a simple help
19251 facility which summarizes the available commands and their options.
19252 In this section we summarize a few of the most commonly
19253 used commands to give an idea of what @code{GDB} is about. You should create
19254 a simple program with debugging information and experiment with the use of
19255 these @code{GDB} commands on the program as you read through the
19256 following section.
19257
19258 @table @code
19259 @item set args @var{arguments}
19260 The @var{arguments} list above is a list of arguments to be passed to
19261 the program on a subsequent run command, just as though the arguments
19262 had been entered on a normal invocation of the program. The @code{set args}
19263 command is not needed if the program does not require arguments.
19264
19265 @item run
19266 The @code{run} command causes execution of the program to start from
19267 the beginning. If the program is already running, that is to say if
19268 you are currently positioned at a breakpoint, then a prompt will ask
19269 for confirmation that you want to abandon the current execution and
19270 restart.
19271
19272 @item breakpoint @var{location}
19273 The breakpoint command sets a breakpoint, that is to say a point at which
19274 execution will halt and @code{GDB} will await further
19275 commands. @var{location} is
19276 either a line number within a file, given in the format @code{file:linenumber},
19277 or it is the name of a subprogram. If you request that a breakpoint be set on
19278 a subprogram that is overloaded, a prompt will ask you to specify on which of
19279 those subprograms you want to breakpoint. You can also
19280 specify that all of them should be breakpointed. If the program is run
19281 and execution encounters the breakpoint, then the program
19282 stops and @code{GDB} signals that the breakpoint was encountered by
19283 printing the line of code before which the program is halted.
19284
19285 @item breakpoint exception @var{name}
19286 A special form of the breakpoint command which breakpoints whenever
19287 exception @var{name} is raised.
19288 If @var{name} is omitted,
19289 then a breakpoint will occur when any exception is raised.
19290
19291 @item print @var{expression}
19292 This will print the value of the given expression. Most simple
19293 Ada expression formats are properly handled by @code{GDB}, so the expression
19294 can contain function calls, variables, operators, and attribute references.
19295
19296 @item continue
19297 Continues execution following a breakpoint, until the next breakpoint or the
19298 termination of the program.
19299
19300 @item step
19301 Executes a single line after a breakpoint. If the next statement
19302 is a subprogram call, execution continues into (the first statement of)
19303 the called subprogram.
19304
19305 @item next
19306 Executes a single line. If this line is a subprogram call, executes and
19307 returns from the call.
19308
19309 @item list
19310 Lists a few lines around the current source location. In practice, it
19311 is usually more convenient to have a separate edit window open with the
19312 relevant source file displayed. Successive applications of this command
19313 print subsequent lines. The command can be given an argument which is a
19314 line number, in which case it displays a few lines around the specified one.
19315
19316 @item backtrace
19317 Displays a backtrace of the call chain. This command is typically
19318 used after a breakpoint has occurred, to examine the sequence of calls that
19319 leads to the current breakpoint. The display includes one line for each
19320 activation record (frame) corresponding to an active subprogram.
19321
19322 @item up
19323 At a breakpoint, @code{GDB} can display the values of variables local
19324 to the current frame. The command @code{up} can be used to
19325 examine the contents of other active frames, by moving the focus up
19326 the stack, that is to say from callee to caller, one frame at a time.
19327
19328 @item down
19329 Moves the focus of @code{GDB} down from the frame currently being
19330 examined to the frame of its callee (the reverse of the previous command),
19331
19332 @item frame @var{n}
19333 Inspect the frame with the given number. The value 0 denotes the frame
19334 of the current breakpoint, that is to say the top of the call stack.
19335
19336 @end table
19337
19338 The above list is a very short introduction to the commands that
19339 @code{GDB} provides. Important additional capabilities, including conditional
19340 breakpoints, the ability to execute command sequences on a breakpoint,
19341 the ability to debug at the machine instruction level and many other
19342 features are described in detail in @cite{Debugging with GDB}.
19343 Note that most commands can be abbreviated
19344 (for example, c for continue, bt for backtrace).
19345
19346 @node Using Ada Expressions
19347 @section Using Ada Expressions
19348 @cindex Ada expressions
19349
19350 @noindent
19351 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19352 extensions. The philosophy behind the design of this subset is
19353
19354 @itemize @bullet
19355 @item
19356 That @code{GDB} should provide basic literals and access to operations for
19357 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19358 leaving more sophisticated computations to subprograms written into the
19359 program (which therefore may be called from @code{GDB}).
19360
19361 @item
19362 That type safety and strict adherence to Ada language restrictions
19363 are not particularly important to the @code{GDB} user.
19364
19365 @item
19366 That brevity is important to the @code{GDB} user.
19367 @end itemize
19368
19369 Thus, for brevity, the debugger acts as if there were
19370 implicit @code{with} and @code{use} clauses in effect for all user-written
19371 packages, thus making it unnecessary to fully qualify most names with
19372 their packages, regardless of context. Where this causes ambiguity,
19373 @code{GDB} asks the user's intent.
19374
19375 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19376
19377 @node Calling User-Defined Subprograms
19378 @section Calling User-Defined Subprograms
19379
19380 @noindent
19381 An important capability of @code{GDB} is the ability to call user-defined
19382 subprograms while debugging. This is achieved simply by entering
19383 a subprogram call statement in the form:
19384
19385 @smallexample
19386 call subprogram-name (parameters)
19387 @end smallexample
19388
19389 @noindent
19390 The keyword @code{call} can be omitted in the normal case where the
19391 @code{subprogram-name} does not coincide with any of the predefined
19392 @code{GDB} commands.
19393
19394 The effect is to invoke the given subprogram, passing it the
19395 list of parameters that is supplied. The parameters can be expressions and
19396 can include variables from the program being debugged. The
19397 subprogram must be defined
19398 at the library level within your program, and @code{GDB} will call the
19399 subprogram within the environment of your program execution (which
19400 means that the subprogram is free to access or even modify variables
19401 within your program).
19402
19403 The most important use of this facility is in allowing the inclusion of
19404 debugging routines that are tailored to particular data structures
19405 in your program. Such debugging routines can be written to provide a suitably
19406 high-level description of an abstract type, rather than a low-level dump
19407 of its physical layout. After all, the standard
19408 @code{GDB print} command only knows the physical layout of your
19409 types, not their abstract meaning. Debugging routines can provide information
19410 at the desired semantic level and are thus enormously useful.
19411
19412 For example, when debugging GNAT itself, it is crucial to have access to
19413 the contents of the tree nodes used to represent the program internally.
19414 But tree nodes are represented simply by an integer value (which in turn
19415 is an index into a table of nodes).
19416 Using the @code{print} command on a tree node would simply print this integer
19417 value, which is not very useful. But the PN routine (defined in file
19418 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19419 a useful high level representation of the tree node, which includes the
19420 syntactic category of the node, its position in the source, the integers
19421 that denote descendant nodes and parent node, as well as varied
19422 semantic information. To study this example in more detail, you might want to
19423 look at the body of the PN procedure in the stated file.
19424
19425 @node Using the Next Command in a Function
19426 @section Using the Next Command in a Function
19427
19428 @noindent
19429 When you use the @code{next} command in a function, the current source
19430 location will advance to the next statement as usual. A special case
19431 arises in the case of a @code{return} statement.
19432
19433 Part of the code for a return statement is the ``epilog'' of the function.
19434 This is the code that returns to the caller. There is only one copy of
19435 this epilog code, and it is typically associated with the last return
19436 statement in the function if there is more than one return. In some
19437 implementations, this epilog is associated with the first statement
19438 of the function.
19439
19440 The result is that if you use the @code{next} command from a return
19441 statement that is not the last return statement of the function you
19442 may see a strange apparent jump to the last return statement or to
19443 the start of the function. You should simply ignore this odd jump.
19444 The value returned is always that from the first return statement
19445 that was stepped through.
19446
19447 @node Ada Exceptions
19448 @section Breaking on Ada Exceptions
19449 @cindex Exceptions
19450
19451 @noindent
19452 You can set breakpoints that trip when your program raises
19453 selected exceptions.
19454
19455 @table @code
19456 @item break exception
19457 Set a breakpoint that trips whenever (any task in the) program raises
19458 any exception.
19459
19460 @item break exception @var{name}
19461 Set a breakpoint that trips whenever (any task in the) program raises
19462 the exception @var{name}.
19463
19464 @item break exception unhandled
19465 Set a breakpoint that trips whenever (any task in the) program raises an
19466 exception for which there is no handler.
19467
19468 @item info exceptions
19469 @itemx info exceptions @var{regexp}
19470 The @code{info exceptions} command permits the user to examine all defined
19471 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19472 argument, prints out only those exceptions whose name matches @var{regexp}.
19473 @end table
19474
19475 @node Ada Tasks
19476 @section Ada Tasks
19477 @cindex Tasks
19478
19479 @noindent
19480 @code{GDB} allows the following task-related commands:
19481
19482 @table @code
19483 @item info tasks
19484 This command shows a list of current Ada tasks, as in the following example:
19485
19486 @smallexample
19487 @iftex
19488 @leftskip=0cm
19489 @end iftex
19490 (gdb) info tasks
19491   ID       TID P-ID   Thread Pri State                 Name
19492    1   8088000   0   807e000  15 Child Activation Wait main_task
19493    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19494    3   809a800   1   80a4800  15 Child Activation Wait a
19495 *  4   80ae800   3   80b8000  15 Running               c
19496 @end smallexample
19497
19498 @noindent
19499 In this listing, the asterisk before the first task indicates it to be the
19500 currently running task. The first column lists the task ID that is used
19501 to refer to tasks in the following commands.
19502
19503 @item break @var{linespec} task @var{taskid}
19504 @itemx break @var{linespec} task @var{taskid} if @dots{}
19505 @cindex Breakpoints and tasks
19506 These commands are like the @code{break @dots{} thread @dots{}}.
19507 @var{linespec} specifies source lines.
19508
19509 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19510 to specify that you only want @code{GDB} to stop the program when a
19511 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19512 numeric task identifiers assigned by @code{GDB}, shown in the first
19513 column of the @samp{info tasks} display.
19514
19515 If you do not specify @samp{task @var{taskid}} when you set a
19516 breakpoint, the breakpoint applies to @emph{all} tasks of your
19517 program.
19518
19519 You can use the @code{task} qualifier on conditional breakpoints as
19520 well; in this case, place @samp{task @var{taskid}} before the
19521 breakpoint condition (before the @code{if}).
19522
19523 @item task @var{taskno}
19524 @cindex Task switching
19525
19526 This command allows to switch to the task referred by @var{taskno}. In
19527 particular, This allows to browse the backtrace of the specified
19528 task. It is advised to switch back to the original task before
19529 continuing execution otherwise the scheduling of the program may be
19530 perturbated.
19531 @end table
19532
19533 @noindent
19534 For more detailed information on the tasking support,
19535 see @cite{Debugging with GDB}.
19536
19537 @node Debugging Generic Units
19538 @section Debugging Generic Units
19539 @cindex Debugging Generic Units
19540 @cindex Generics
19541
19542 @noindent
19543 GNAT always uses code expansion for generic instantiation. This means that
19544 each time an instantiation occurs, a complete copy of the original code is
19545 made, with appropriate substitutions of formals by actuals.
19546
19547 It is not possible to refer to the original generic entities in
19548 @code{GDB}, but it is always possible to debug a particular instance of
19549 a generic, by using the appropriate expanded names. For example, if we have
19550
19551 @smallexample @c ada
19552 @group
19553 @cartouche
19554 procedure g is
19555
19556    generic package k is
19557       procedure kp (v1 : in out integer);
19558    end k;
19559
19560    package body k is
19561       procedure kp (v1 : in out integer) is
19562       begin
19563          v1 := v1 + 1;
19564       end kp;
19565    end k;
19566
19567    package k1 is new k;
19568    package k2 is new k;
19569
19570    var : integer := 1;
19571
19572 begin
19573    k1.kp (var);
19574    k2.kp (var);
19575    k1.kp (var);
19576    k2.kp (var);
19577 end;
19578 @end cartouche
19579 @end group
19580 @end smallexample
19581
19582 @noindent
19583 Then to break on a call to procedure kp in the k2 instance, simply
19584 use the command:
19585
19586 @smallexample
19587 (gdb) break g.k2.kp
19588 @end smallexample
19589
19590 @noindent
19591 When the breakpoint occurs, you can step through the code of the
19592 instance in the normal manner and examine the values of local variables, as for
19593 other units.
19594
19595 @node GNAT Abnormal Termination or Failure to Terminate
19596 @section GNAT Abnormal Termination or Failure to Terminate
19597 @cindex GNAT Abnormal Termination or Failure to Terminate
19598
19599 @noindent
19600 When presented with programs that contain serious errors in syntax
19601 or semantics,
19602 GNAT may on rare occasions  experience problems in operation, such
19603 as aborting with a
19604 segmentation fault or illegal memory access, raising an internal
19605 exception, terminating abnormally, or failing to terminate at all.
19606 In such cases, you can activate
19607 various features of GNAT that can help you pinpoint the construct in your
19608 program that is the likely source of the problem.
19609
19610 The following strategies are presented in increasing order of
19611 difficulty, corresponding to your experience in using GNAT and your
19612 familiarity with compiler internals.
19613
19614 @enumerate
19615 @item
19616 Run @command{gcc} with the @option{-gnatf}. This first
19617 switch causes all errors on a given line to be reported. In its absence,
19618 only the first error on a line is displayed.
19619
19620 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19621 are encountered, rather than after compilation is terminated. If GNAT
19622 terminates prematurely or goes into an infinite loop, the last error
19623 message displayed may help to pinpoint the culprit.
19624
19625 @item
19626 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19627 mode, @command{gcc} produces ongoing information about the progress of the
19628 compilation and provides the name of each procedure as code is
19629 generated. This switch allows you to find which Ada procedure was being
19630 compiled when it encountered a code generation problem.
19631
19632 @item
19633 @cindex @option{-gnatdc} switch
19634 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19635 switch that does for the front-end what @option{^-v^VERBOSE^} does
19636 for the back end. The system prints the name of each unit,
19637 either a compilation unit or nested unit, as it is being analyzed.
19638 @item
19639 Finally, you can start
19640 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19641 front-end of GNAT, and can be run independently (normally it is just
19642 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19643 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19644 @code{where} command is the first line of attack; the variable
19645 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19646 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19647 which the execution stopped, and @code{input_file name} indicates the name of
19648 the source file.
19649 @end enumerate
19650
19651 @node Naming Conventions for GNAT Source Files
19652 @section Naming Conventions for GNAT Source Files
19653
19654 @noindent
19655 In order to examine the workings of the GNAT system, the following
19656 brief description of its organization may be helpful:
19657
19658 @itemize @bullet
19659 @item
19660 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19661
19662 @item
19663 All files prefixed with @file{^par^PAR^} are components of the parser. The
19664 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19665 parsing of select statements can be found in @file{par-ch9.adb}.
19666
19667 @item
19668 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19669 numbers correspond to chapters of the Ada standard. For example, all
19670 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19671 addition, some features of the language require sufficient special processing
19672 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19673 dynamic dispatching, etc.
19674
19675 @item
19676 All files prefixed with @file{^exp^EXP^} perform normalization and
19677 expansion of the intermediate representation (abstract syntax tree, or AST).
19678 these files use the same numbering scheme as the parser and semantics files.
19679 For example, the construction of record initialization procedures is done in
19680 @file{exp_ch3.adb}.
19681
19682 @item
19683 The files prefixed with @file{^bind^BIND^} implement the binder, which
19684 verifies the consistency of the compilation, determines an order of
19685 elaboration, and generates the bind file.
19686
19687 @item
19688 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19689 data structures used by the front-end.
19690
19691 @item
19692 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19693 the abstract syntax tree as produced by the parser.
19694
19695 @item
19696 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19697 all entities, computed during semantic analysis.
19698
19699 @item
19700 Library management issues are dealt with in files with prefix
19701 @file{^lib^LIB^}.
19702
19703 @item
19704 @findex Ada
19705 @cindex Annex A
19706 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19707 defined in Annex A.
19708
19709 @item
19710 @findex Interfaces
19711 @cindex Annex B
19712 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19713 defined in Annex B.
19714
19715 @item
19716 @findex System
19717 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19718 both language-defined children and GNAT run-time routines.
19719
19720 @item
19721 @findex GNAT
19722 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19723 general-purpose packages, fully documented in their specifications. All
19724 the other @file{.c} files are modifications of common @command{gcc} files.
19725 @end itemize
19726
19727 @node Getting Internal Debugging Information
19728 @section Getting Internal Debugging Information
19729
19730 @noindent
19731 Most compilers have internal debugging switches and modes. GNAT
19732 does also, except GNAT internal debugging switches and modes are not
19733 secret. A summary and full description of all the compiler and binder
19734 debug flags are in the file @file{debug.adb}. You must obtain the
19735 sources of the compiler to see the full detailed effects of these flags.
19736
19737 The switches that print the source of the program (reconstructed from
19738 the internal tree) are of general interest for user programs, as are the
19739 options to print
19740 the full internal tree, and the entity table (the symbol table
19741 information). The reconstructed source provides a readable version of the
19742 program after the front-end has completed analysis and  expansion,
19743 and is useful when studying the performance of specific constructs.
19744 For example, constraint checks are indicated, complex aggregates
19745 are replaced with loops and assignments, and tasking primitives
19746 are replaced with run-time calls.
19747
19748 @node Stack Traceback
19749 @section Stack Traceback
19750 @cindex traceback
19751 @cindex stack traceback
19752 @cindex stack unwinding
19753
19754 @noindent
19755 Traceback is a mechanism to display the sequence of subprogram calls that
19756 leads to a specified execution point in a program. Often (but not always)
19757 the execution point is an instruction at which an exception has been raised.
19758 This mechanism is also known as @i{stack unwinding} because it obtains
19759 its information by scanning the run-time stack and recovering the activation
19760 records of all active subprograms. Stack unwinding is one of the most
19761 important tools for program debugging.
19762
19763 The first entry stored in traceback corresponds to the deepest calling level,
19764 that is to say the subprogram currently executing the instruction
19765 from which we want to obtain the traceback.
19766
19767 Note that there is no runtime performance penalty when stack traceback
19768 is enabled, and no exception is raised during program execution.
19769
19770 @menu
19771 * Non-Symbolic Traceback::
19772 * Symbolic Traceback::
19773 @end menu
19774
19775 @node Non-Symbolic Traceback
19776 @subsection Non-Symbolic Traceback
19777 @cindex traceback, non-symbolic
19778
19779 @noindent
19780 Note: this feature is not supported on all platforms. See
19781 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19782 platforms.
19783
19784 @menu
19785 * Tracebacks From an Unhandled Exception::
19786 * Tracebacks From Exception Occurrences (non-symbolic)::
19787 * Tracebacks From Anywhere in a Program (non-symbolic)::
19788 @end menu
19789
19790 @node Tracebacks From an Unhandled Exception
19791 @subsubsection Tracebacks From an Unhandled Exception
19792
19793 @noindent
19794 A runtime non-symbolic traceback is a list of addresses of call instructions.
19795 To enable this feature you must use the @option{-E}
19796 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19797 of exception information. You can retrieve this information using the
19798 @code{addr2line} tool.
19799
19800 Here is a simple example:
19801
19802 @smallexample @c ada
19803 @cartouche
19804 procedure STB is
19805
19806    procedure P1 is
19807    begin
19808       raise Constraint_Error;
19809    end P1;
19810
19811    procedure P2 is
19812    begin
19813       P1;
19814    end P2;
19815
19816 begin
19817    P2;
19818 end STB;
19819 @end cartouche
19820 @end smallexample
19821
19822 @smallexample
19823 $ gnatmake stb -bargs -E
19824 $ stb
19825
19826 Execution terminated by unhandled exception
19827 Exception name: CONSTRAINT_ERROR
19828 Message: stb.adb:5
19829 Call stack traceback locations:
19830 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19831 @end smallexample
19832
19833 @noindent
19834 As we see the traceback lists a sequence of addresses for the unhandled
19835 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19836 guess that this exception come from procedure P1. To translate these
19837 addresses into the source lines where the calls appear, the
19838 @code{addr2line} tool, described below, is invaluable. The use of this tool
19839 requires the program to be compiled with debug information.
19840
19841 @smallexample
19842 $ gnatmake -g stb -bargs -E
19843 $ stb
19844
19845 Execution terminated by unhandled exception
19846 Exception name: CONSTRAINT_ERROR
19847 Message: stb.adb:5
19848 Call stack traceback locations:
19849 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19850
19851 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19852    0x4011f1 0x77e892a4
19853
19854 00401373 at d:/stb/stb.adb:5
19855 0040138B at d:/stb/stb.adb:10
19856 0040139C at d:/stb/stb.adb:14
19857 00401335 at d:/stb/b~stb.adb:104
19858 004011C4 at /build/.../crt1.c:200
19859 004011F1 at /build/.../crt1.c:222
19860 77E892A4 in ?? at ??:0
19861 @end smallexample
19862
19863 @noindent
19864 The @code{addr2line} tool has several other useful options:
19865
19866 @table @code
19867 @item --functions
19868 to get the function name corresponding to any location
19869
19870 @item --demangle=gnat
19871 to use the gnat decoding mode for the function names. Note that
19872 for binutils version 2.9.x the option is simply @option{--demangle}.
19873 @end table
19874
19875 @smallexample
19876 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19877    0x40139c 0x401335 0x4011c4 0x4011f1
19878
19879 00401373 in stb.p1 at d:/stb/stb.adb:5
19880 0040138B in stb.p2 at d:/stb/stb.adb:10
19881 0040139C in stb at d:/stb/stb.adb:14
19882 00401335 in main at d:/stb/b~stb.adb:104
19883 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19884 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19885 @end smallexample
19886
19887 @noindent
19888 From this traceback we can see that the exception was raised in
19889 @file{stb.adb} at line 5, which was reached from a procedure call in
19890 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19891 which contains the call to the main program.
19892 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19893 and the output will vary from platform to platform.
19894
19895 It is also possible to use @code{GDB} with these traceback addresses to debug
19896 the program. For example, we can break at a given code location, as reported
19897 in the stack traceback:
19898
19899 @smallexample
19900 $ gdb -nw stb
19901 @ifclear vms
19902 @noindent
19903 Furthermore, this feature is not implemented inside Windows DLL. Only
19904 the non-symbolic traceback is reported in this case.
19905 @end ifclear
19906
19907 (gdb) break *0x401373
19908 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19909 @end smallexample
19910
19911 @noindent
19912 It is important to note that the stack traceback addresses
19913 do not change when debug information is included. This is particularly useful
19914 because it makes it possible to release software without debug information (to
19915 minimize object size), get a field report that includes a stack traceback
19916 whenever an internal bug occurs, and then be able to retrieve the sequence
19917 of calls with the same program compiled with debug information.
19918
19919 @node Tracebacks From Exception Occurrences (non-symbolic)
19920 @subsubsection Tracebacks From Exception Occurrences
19921
19922 @noindent
19923 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19924 The stack traceback is attached to the exception information string, and can
19925 be retrieved in an exception handler within the Ada program, by means of the
19926 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19927
19928 @smallexample @c ada
19929 with Ada.Text_IO;
19930 with Ada.Exceptions;
19931
19932 procedure STB is
19933
19934    use Ada;
19935    use Ada.Exceptions;
19936
19937    procedure P1 is
19938       K : Positive := 1;
19939    begin
19940       K := K - 1;
19941    exception
19942       when E : others =>
19943          Text_IO.Put_Line (Exception_Information (E));
19944    end P1;
19945
19946    procedure P2 is
19947    begin
19948       P1;
19949    end P2;
19950
19951 begin
19952    P2;
19953 end STB;
19954 @end smallexample
19955
19956 @noindent
19957 This program will output:
19958
19959 @smallexample
19960 $ stb
19961
19962 Exception name: CONSTRAINT_ERROR
19963 Message: stb.adb:12
19964 Call stack traceback locations:
19965 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19966 @end smallexample
19967
19968 @node Tracebacks From Anywhere in a Program (non-symbolic)
19969 @subsubsection Tracebacks From Anywhere in a Program
19970
19971 @noindent
19972 It is also possible to retrieve a stack traceback from anywhere in a
19973 program. For this you need to
19974 use the @code{GNAT.Traceback} API. This package includes a procedure called
19975 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19976 display procedures described below. It is not necessary to use the
19977 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19978 is invoked explicitly.
19979
19980 @noindent
19981 In the following example we compute a traceback at a specific location in
19982 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19983 convert addresses to strings:
19984
19985 @smallexample @c ada
19986 with Ada.Text_IO;
19987 with GNAT.Traceback;
19988 with GNAT.Debug_Utilities;
19989
19990 procedure STB is
19991
19992    use Ada;
19993    use GNAT;
19994    use GNAT.Traceback;
19995
19996    procedure P1 is
19997       TB  : Tracebacks_Array (1 .. 10);
19998       --  We are asking for a maximum of 10 stack frames.
19999       Len : Natural;
20000       --  Len will receive the actual number of stack frames returned.
20001    begin
20002       Call_Chain (TB, Len);
20003
20004       Text_IO.Put ("In STB.P1 : ");
20005
20006       for K in 1 .. Len loop
20007          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20008          Text_IO.Put (' ');
20009       end loop;
20010
20011       Text_IO.New_Line;
20012    end P1;
20013
20014    procedure P2 is
20015    begin
20016       P1;
20017    end P2;
20018
20019 begin
20020    P2;
20021 end STB;
20022 @end smallexample
20023
20024 @smallexample
20025 $ gnatmake -g stb
20026 $ stb
20027
20028 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20029 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20030 @end smallexample
20031
20032 @noindent
20033 You can then get further information by invoking the @code{addr2line}
20034 tool as described earlier (note that the hexadecimal addresses
20035 need to be specified in C format, with a leading ``0x'').
20036
20037 @node Symbolic Traceback
20038 @subsection Symbolic Traceback
20039 @cindex traceback, symbolic
20040
20041 @noindent
20042 A symbolic traceback is a stack traceback in which procedure names are
20043 associated with each code location.
20044
20045 @noindent
20046 Note that this feature is not supported on all platforms. See
20047 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20048 list of currently supported platforms.
20049
20050 @noindent
20051 Note that the symbolic traceback requires that the program be compiled
20052 with debug information. If it is not compiled with debug information
20053 only the non-symbolic information will be valid.
20054
20055 @menu
20056 * Tracebacks From Exception Occurrences (symbolic)::
20057 * Tracebacks From Anywhere in a Program (symbolic)::
20058 @end menu
20059
20060 @node Tracebacks From Exception Occurrences (symbolic)
20061 @subsubsection Tracebacks From Exception Occurrences
20062
20063 @smallexample @c ada
20064 with Ada.Text_IO;
20065 with GNAT.Traceback.Symbolic;
20066
20067 procedure STB is
20068
20069    procedure P1 is
20070    begin
20071       raise Constraint_Error;
20072    end P1;
20073
20074    procedure P2 is
20075    begin
20076       P1;
20077    end P2;
20078
20079    procedure P3 is
20080    begin
20081       P2;
20082    end P3;
20083
20084 begin
20085    P3;
20086 exception
20087    when E : others =>
20088       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20089 end STB;
20090 @end smallexample
20091
20092 @smallexample
20093 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20094 $ stb
20095
20096 0040149F in stb.p1 at stb.adb:8
20097 004014B7 in stb.p2 at stb.adb:13
20098 004014CF in stb.p3 at stb.adb:18
20099 004015DD in ada.stb at stb.adb:22
20100 00401461 in main at b~stb.adb:168
20101 004011C4 in __mingw_CRTStartup at crt1.c:200
20102 004011F1 in mainCRTStartup at crt1.c:222
20103 77E892A4 in ?? at ??:0
20104 @end smallexample
20105
20106 @noindent
20107 In the above example the ``.\'' syntax in the @command{gnatmake} command
20108 is currently required by @command{addr2line} for files that are in
20109 the current working directory.
20110 Moreover, the exact sequence of linker options may vary from platform
20111 to platform.
20112 The above @option{-largs} section is for Windows platforms. By contrast,
20113 under Unix there is no need for the @option{-largs} section.
20114 Differences across platforms are due to details of linker implementation.
20115
20116 @node Tracebacks From Anywhere in a Program (symbolic)
20117 @subsubsection Tracebacks From Anywhere in a Program
20118
20119 @noindent
20120 It is possible to get a symbolic stack traceback
20121 from anywhere in a program, just as for non-symbolic tracebacks.
20122 The first step is to obtain a non-symbolic
20123 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20124 information. Here is an example:
20125
20126 @smallexample @c ada
20127 with Ada.Text_IO;
20128 with GNAT.Traceback;
20129 with GNAT.Traceback.Symbolic;
20130
20131 procedure STB is
20132
20133    use Ada;
20134    use GNAT.Traceback;
20135    use GNAT.Traceback.Symbolic;
20136
20137    procedure P1 is
20138       TB  : Tracebacks_Array (1 .. 10);
20139       --  We are asking for a maximum of 10 stack frames.
20140       Len : Natural;
20141       --  Len will receive the actual number of stack frames returned.
20142    begin
20143       Call_Chain (TB, Len);
20144       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20145    end P1;
20146
20147    procedure P2 is
20148    begin
20149       P1;
20150    end P2;
20151
20152 begin
20153    P2;
20154 end STB;
20155 @end smallexample
20156
20157 @ifset vms
20158 @node Compatibility with DEC Ada
20159 @chapter Compatibility with DEC Ada
20160 @cindex Compatibility
20161
20162 @noindent
20163 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
20164 OpenVMS Alpha. GNAT achieves a high level of compatibility
20165 with DEC Ada, and it should generally be straightforward to port code
20166 from the DEC Ada environment to GNAT. However, there are a few language
20167 and implementation differences of which the user must be aware. These
20168 differences are discussed in this section. In
20169 addition, the operating environment and command structure for the
20170 compiler are different, and these differences are also discussed.
20171
20172 Note that this discussion addresses specifically the implementation
20173 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
20174 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20175 GNAT always follows the Alpha implementation.
20176
20177 @menu
20178 * Ada 95 Compatibility::
20179 * Differences in the Definition of Package System::
20180 * Language-Related Features::
20181 * The Package STANDARD::
20182 * The Package SYSTEM::
20183 * Tasking and Task-Related Features::
20184 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
20185 * Pragmas and Pragma-Related Features::
20186 * Library of Predefined Units::
20187 * Bindings::
20188 * Main Program Definition::
20189 * Implementation-Defined Attributes::
20190 * Compiler and Run-Time Interfacing::
20191 * Program Compilation and Library Management::
20192 * Input-Output::
20193 * Implementation Limits::
20194 * Tools::
20195 @end menu
20196
20197 @node Ada 95 Compatibility
20198 @section Ada 95 Compatibility
20199
20200 @noindent
20201 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
20202 compiler. Ada 95 is almost completely upwards compatible
20203 with Ada 83, and therefore Ada 83 programs will compile
20204 and run under GNAT with
20205 no changes or only minor changes. The Ada 95 Reference
20206 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
20207 incompatibilities.
20208
20209 GNAT provides the switch /83 on the GNAT COMPILE command,
20210 as well as the pragma ADA_83, to force the compiler to
20211 operate in Ada 83 mode. This mode does not guarantee complete
20212 conformance to Ada 83, but in practice is sufficient to
20213 eliminate most sources of incompatibilities.
20214 In particular, it eliminates the recognition of the
20215 additional Ada 95 keywords, so that their use as identifiers
20216 in Ada83 program is legal, and handles the cases of packages
20217 with optional bodies, and generics that instantiate unconstrained
20218 types without the use of @code{(<>)}.
20219
20220 @node Differences in the Definition of Package System
20221 @section Differences in the Definition of Package System
20222
20223 @noindent
20224 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20225 implementation-dependent declarations to package System. In normal mode,
20226 GNAT does not take advantage of this permission, and the version of System
20227 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20228
20229 However, DEC Ada adds an extensive set of declarations to package System,
20230 as fully documented in the DEC Ada manuals. To minimize changes required
20231 for programs that make use of these extensions, GNAT provides the pragma
20232 Extend_System for extending the definition of package System. By using:
20233
20234 @smallexample @c ada
20235 @group
20236 @cartouche
20237 pragma Extend_System (Aux_DEC);
20238 @end cartouche
20239 @end group
20240 @end smallexample
20241
20242 @noindent
20243 The set of definitions in System is extended to include those in package
20244 @code{System.Aux_DEC}.
20245 These definitions are incorporated directly into package
20246 System, as though they had been declared there in the first place. For a
20247 list of the declarations added, see the specification of this package,
20248 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20249 The pragma Extend_System is a configuration pragma, which means that
20250 it can be placed in the file @file{gnat.adc}, so that it will automatically
20251 apply to all subsequent compilations. See the section on Configuration
20252 Pragmas for further details.
20253
20254 An alternative approach that avoids the use of the non-standard
20255 Extend_System pragma is to add a context clause to the unit that
20256 references these facilities:
20257
20258 @smallexample @c ada
20259 @group
20260 @cartouche
20261 with System.Aux_DEC;
20262 use  System.Aux_DEC;
20263 @end cartouche
20264 @end group
20265 @end smallexample
20266
20267 @noindent
20268 The effect is not quite semantically identical to incorporating
20269 the declarations directly into package @code{System},
20270 but most programs will not notice a difference
20271 unless they use prefix notation (e.g. @code{System.Integer_8})
20272 to reference the
20273 entities directly in package @code{System}.
20274 For units containing such references,
20275 the prefixes must either be removed, or the pragma @code{Extend_System}
20276 must be used.
20277
20278 @node Language-Related Features
20279 @section Language-Related Features
20280
20281 @noindent
20282 The following sections highlight differences in types,
20283 representations of types, operations, alignment, and
20284 related topics.
20285
20286 @menu
20287 * Integer Types and Representations::
20288 * Floating-Point Types and Representations::
20289 * Pragmas Float_Representation and Long_Float::
20290 * Fixed-Point Types and Representations::
20291 * Record and Array Component Alignment::
20292 * Address Clauses::
20293 * Other Representation Clauses::
20294 @end menu
20295
20296 @node Integer Types and Representations
20297 @subsection Integer Types and Representations
20298
20299 @noindent
20300 The set of predefined integer types is identical in DEC Ada and GNAT.
20301 Furthermore the representation of these integer types is also identical,
20302 including the capability of size clauses forcing biased representation.
20303
20304 In addition,
20305 DEC Ada for OpenVMS Alpha systems has defined the
20306 following additional integer types in package System:
20307
20308 @itemize @bullet
20309
20310 @item
20311 INTEGER_8
20312
20313 @item
20314 INTEGER_16
20315
20316 @item
20317 INTEGER_32
20318
20319 @item
20320 INTEGER_64
20321
20322 @item
20323 LARGEST_INTEGER
20324 @end itemize
20325
20326 @noindent
20327 When using GNAT, the first four of these types may be obtained from the
20328 standard Ada 95 package @code{Interfaces}.
20329 Alternatively, by use of the pragma
20330 @code{Extend_System}, identical
20331 declarations can be referenced directly in package @code{System}.
20332 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
20333
20334 @node Floating-Point Types and Representations
20335 @subsection Floating-Point Types and Representations
20336 @cindex Floating-Point types
20337
20338 @noindent
20339 The set of predefined floating-point types is identical in DEC Ada and GNAT.
20340 Furthermore the representation of these floating-point
20341 types is also identical. One important difference is that the default
20342 representation for DEC Ada is VAX_Float, but the default representation
20343 for GNAT is IEEE.
20344
20345 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20346 @code{Float_Representation} as described in the DEC Ada documentation.
20347 For example, the declarations:
20348
20349 @smallexample @c ada
20350 @group
20351 @cartouche
20352 type F_Float is digits 6;
20353 pragma Float_Representation (VAX_Float, F_Float);
20354 @end cartouche
20355 @end group
20356 @end smallexample
20357
20358 @noindent
20359 declare a type F_Float that will be represented in VAX_Float format.
20360 This set of declarations actually appears in System.Aux_DEC, which provides
20361 the full set of additional floating-point declarations provided in
20362 the DEC Ada version of package
20363 System. This and similar declarations may be accessed in a user program
20364 by using pragma @code{Extend_System}. The use of this
20365 pragma, and the related pragma @code{Long_Float} is described in further
20366 detail in the following section.
20367
20368 @node Pragmas Float_Representation and Long_Float
20369 @subsection Pragmas Float_Representation and Long_Float
20370
20371 @noindent
20372 DEC Ada provides the pragma @code{Float_Representation}, which
20373 acts as a program library switch to allow control over
20374 the internal representation chosen for the predefined
20375 floating-point types declared in the package @code{Standard}.
20376 The format of this pragma is as follows:
20377
20378 @smallexample
20379 @group
20380 @cartouche
20381 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20382 @end cartouche
20383 @end group
20384 @end smallexample
20385
20386 @noindent
20387 This pragma controls the representation of floating-point
20388 types as follows:
20389
20390 @itemize @bullet
20391 @item
20392 @code{VAX_Float} specifies that floating-point
20393 types are represented by default with the VAX hardware types
20394 F-floating, D-floating, G-floating. Note that the H-floating
20395 type is available only on DIGITAL Vax systems, and is not available
20396 in either DEC Ada or GNAT for Alpha systems.
20397
20398 @item
20399 @code{IEEE_Float} specifies that floating-point
20400 types are represented by default with the IEEE single and
20401 double floating-point types.
20402 @end itemize
20403
20404 @noindent
20405 GNAT provides an identical implementation of the pragma
20406 @code{Float_Representation}, except that it functions as a
20407 configuration pragma, as defined by Ada 95. Note that the
20408 notion of configuration pragma corresponds closely to the
20409 DEC Ada notion of a program library switch.
20410
20411 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20412 from DEC Ada 83, where the default is VAX_Float. In addition, the
20413 predefined libraries in GNAT are built using IEEE_Float, so it is not
20414 advisable to change the format of numbers passed to standard library
20415 routines, and if necessary explicit type conversions may be needed.
20416
20417 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20418 and (given that it conforms to an international standard) potentially more
20419 portable. The situation in which VAX_Float may be useful is in interfacing
20420 to existing code and data that expects the use of VAX_Float. There are
20421 two possibilities here. If the requirement for the use of VAX_Float is
20422 localized, then the best approach is to use the predefined VAX_Float
20423 types in package @code{System}, as extended by
20424 @code{Extend_System}. For example, use @code{System.F_Float}
20425 to specify the 32-bit @code{F-Float} format.
20426
20427 Alternatively, if an entire program depends heavily on the use of
20428 the @code{VAX_Float} and in particular assumes that the types in
20429 package @code{Standard} are in @code{Vax_Float} format, then it
20430 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20431 This is done by using the GNAT LIBRARY command to rebuild the library, and
20432 then using the general form of the @code{Float_Representation}
20433 pragma to ensure that this default format is used throughout.
20434 The form of the GNAT LIBRARY command is:
20435
20436 @smallexample
20437 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20438 @end smallexample
20439
20440 @noindent
20441 where @i{file} contains the new configuration pragmas
20442 and @i{directory} is the directory to be created to contain
20443 the new library.
20444
20445 @noindent
20446 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
20447 to allow control over the internal representation chosen
20448 for the predefined type @code{Long_Float} and for floating-point
20449 type declarations with digits specified in the range 7 .. 15.
20450 The format of this pragma is as follows:
20451
20452 @smallexample @c ada
20453 @cartouche
20454 pragma Long_Float (D_FLOAT | G_FLOAT);
20455 @end cartouche
20456 @end smallexample
20457
20458 @node Fixed-Point Types and Representations
20459 @subsection Fixed-Point Types and Representations
20460
20461 @noindent
20462 On DEC Ada for OpenVMS Alpha systems, rounding is
20463 away from zero for both positive and negative numbers.
20464 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20465
20466 On GNAT for OpenVMS Alpha, the results of operations
20467 on fixed-point types are in accordance with the Ada 95
20468 rules. In particular, results of operations on decimal
20469 fixed-point types are truncated.
20470
20471 @node Record and Array Component Alignment
20472 @subsection Record and Array Component Alignment
20473
20474 @noindent
20475 On DEC Ada for OpenVMS Alpha, all non composite components
20476 are aligned on natural boundaries. For example, 1-byte
20477 components are aligned on byte boundaries, 2-byte
20478 components on 2-byte boundaries, 4-byte components on 4-byte
20479 byte boundaries, and so on. The OpenVMS Alpha hardware
20480 runs more efficiently with naturally aligned data.
20481
20482 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20483 with DEC Ada for OpenVMS Alpha.
20484
20485 @node Address Clauses
20486 @subsection Address Clauses
20487
20488 @noindent
20489 In DEC Ada and GNAT, address clauses are supported for
20490 objects and imported subprograms.
20491 The predefined type @code{System.Address} is a private type
20492 in both compilers, with the same representation (it is simply
20493 a machine pointer). Addition, subtraction, and comparison
20494 operations are available in the standard Ada 95 package
20495 @code{System.Storage_Elements}, or in package @code{System}
20496 if it is extended to include @code{System.Aux_DEC} using a
20497 pragma @code{Extend_System} as previously described.
20498
20499 Note that code that with's both this extended package @code{System}
20500 and the package @code{System.Storage_Elements} should not @code{use}
20501 both packages, or ambiguities will result. In general it is better
20502 not to mix these two sets of facilities. The Ada 95 package was
20503 designed specifically to provide the kind of features that DEC Ada
20504 adds directly to package @code{System}.
20505
20506 GNAT is compatible with DEC Ada in its handling of address
20507 clauses, except for some limitations in
20508 the form of address clauses for composite objects with
20509 initialization. Such address clauses are easily replaced
20510 by the use of an explicitly-defined constant as described
20511 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20512 of declarations:
20513
20514 @smallexample @c ada
20515 @cartouche
20516 X, Y : Integer := Init_Func;
20517 Q : String (X .. Y) := "abc";
20518 ...
20519 for Q'Address use Compute_Address;
20520 @end cartouche
20521 @end smallexample
20522
20523 @noindent
20524 will be rejected by GNAT, since the address cannot be computed at the time
20525 that Q is declared. To achieve the intended effect, write instead:
20526
20527 @smallexample @c ada
20528 @group
20529 @cartouche
20530 X, Y : Integer := Init_Func;
20531 Q_Address : constant Address := Compute_Address;
20532 Q : String (X .. Y) := "abc";
20533 ...
20534 for Q'Address use Q_Address;
20535 @end cartouche
20536 @end group
20537 @end smallexample
20538
20539 @noindent
20540 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20541 backwards compatible with Ada 83. A fuller description of the restrictions
20542 on address specifications is found in the GNAT Reference Manual.
20543
20544 @node Other Representation Clauses
20545 @subsection Other Representation Clauses
20546
20547 @noindent
20548 GNAT supports in a compatible manner all the representation
20549 clauses supported by DEC Ada. In addition, it
20550 supports representation clause forms that are new in Ada 95
20551 including COMPONENT_SIZE and SIZE clauses for objects.
20552
20553 @node The Package STANDARD
20554 @section The Package STANDARD
20555
20556 @noindent
20557 The package STANDARD, as implemented by DEC Ada, is fully
20558 described in the Reference Manual for the Ada Programming
20559 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
20560 Language Reference Manual. As implemented by GNAT, the
20561 package STANDARD is described in the Ada 95 Reference
20562 Manual.
20563
20564 In addition, DEC Ada supports the Latin-1 character set in
20565 the type CHARACTER. GNAT supports the Latin-1 character set
20566 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20567 the type WIDE_CHARACTER.
20568
20569 The floating-point types supported by GNAT are those
20570 supported by DEC Ada, but defaults are different, and are controlled by
20571 pragmas. See @ref{Floating-Point Types and Representations} for details.
20572
20573 @node The Package SYSTEM
20574 @section The Package SYSTEM
20575
20576 @noindent
20577 DEC Ada provides a system-specific version of the package
20578 SYSTEM for each platform on which the language ships.
20579 For the complete specification of the package SYSTEM, see
20580 Appendix F of the DEC Ada Language Reference Manual.
20581
20582 On DEC Ada, the package SYSTEM includes the following conversion functions:
20583 @itemize @bullet
20584 @item TO_ADDRESS(INTEGER)
20585
20586 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
20587
20588 @item  TO_ADDRESS(universal_integer)
20589
20590 @item  TO_INTEGER(ADDRESS)
20591
20592 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
20593
20594 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20595                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20596 @end itemize
20597
20598 @noindent
20599 By default, GNAT supplies a version of SYSTEM that matches
20600 the definition given in the Ada 95 Reference Manual.
20601 This
20602 is a subset of the DIGITAL system definitions, which is as
20603 close as possible to the original definitions. The only difference
20604 is that the definition of SYSTEM_NAME is different:
20605
20606 @smallexample @c ada
20607 @group
20608 @cartouche
20609 type Name is (SYSTEM_NAME_GNAT);
20610 System_Name : constant Name := SYSTEM_NAME_GNAT;
20611 @end cartouche
20612 @end group
20613 @end smallexample
20614
20615 @noindent
20616 Also, GNAT adds the new Ada 95 declarations for
20617 BIT_ORDER and DEFAULT_BIT_ORDER.
20618
20619 However, the use of the following pragma causes GNAT
20620 to extend the definition of package SYSTEM so that it
20621 encompasses the full set of DIGITAL-specific extensions,
20622 including the functions listed above:
20623
20624 @smallexample @c ada
20625 @cartouche
20626 pragma Extend_System (Aux_DEC);
20627 @end cartouche
20628 @end smallexample
20629
20630 @noindent
20631 The pragma Extend_System is a configuration pragma that
20632 is most conveniently placed in the @file{gnat.adc} file. See the
20633 GNAT Reference Manual for further details.
20634
20635 DEC Ada does not allow the recompilation of the package
20636 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
20637 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20638 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20639 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20640 its single argument.
20641
20642 GNAT does permit the recompilation of package SYSTEM using
20643 a special switch (@option{-gnatg}) and this switch can be used if
20644 it is necessary to modify the definitions in SYSTEM. GNAT does
20645 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20646 or MEMORY_SIZE by any other means.
20647
20648 On GNAT systems, the pragma SYSTEM_NAME takes the
20649 enumeration literal SYSTEM_NAME_GNAT.
20650
20651 The definitions provided by the use of
20652
20653 @smallexample @c ada
20654 pragma Extend_System (AUX_Dec);
20655 @end smallexample
20656
20657 @noindent
20658 are virtually identical to those provided by the DEC Ada 83 package
20659 System. One important difference is that the name of the TO_ADDRESS
20660 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20661 See the GNAT Reference manual for a discussion of why this change was
20662 necessary.
20663
20664 @noindent
20665 The version of TO_ADDRESS taking a universal integer argument is in fact
20666 an extension to Ada 83 not strictly compatible with the reference manual.
20667 In GNAT, we are constrained to be exactly compatible with the standard,
20668 and this means we cannot provide this capability. In DEC Ada 83, the
20669 point of this definition is to deal with a call like:
20670
20671 @smallexample @c ada
20672 TO_ADDRESS (16#12777#);
20673 @end smallexample
20674
20675 @noindent
20676 Normally, according to the Ada 83 standard, one would expect this to be
20677 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20678 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
20679 definition using universal_integer takes precedence.
20680
20681 In GNAT, since the version with universal_integer cannot be supplied, it is
20682 not possible to be 100% compatible. Since there are many programs using
20683 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20684 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20685 declarations provided in the GNAT version of AUX_Dec are:
20686
20687 @smallexample @c ada
20688 function To_Address (X : Integer) return Address;
20689 pragma Pure_Function (To_Address);
20690
20691 function To_Address_Long (X : Unsigned_Longword) return Address;
20692 pragma Pure_Function (To_Address_Long);
20693 @end smallexample
20694
20695 @noindent
20696 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20697 change the name to TO_ADDRESS_LONG.
20698
20699 @node Tasking and Task-Related Features
20700 @section Tasking and Task-Related Features
20701
20702 @noindent
20703 The concepts relevant to a comparison of tasking on GNAT
20704 and on DEC Ada for OpenVMS Alpha systems are discussed in
20705 the following sections.
20706
20707 For detailed information on concepts related to tasking in
20708 DEC Ada, see the DEC Ada Language Reference Manual and the
20709 relevant run-time reference manual.
20710
20711 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20712 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20713
20714 @noindent
20715 On OpenVMS Alpha systems, each Ada task (except a passive
20716 task) is implemented as a single stream of execution
20717 that is created and managed by the kernel. On these
20718 systems, DEC Ada tasking support is based on DECthreads,
20719 an implementation of the POSIX standard for threads.
20720
20721 Although tasks are implemented as threads, all tasks in
20722 an Ada program are part of the same process. As a result,
20723 resources such as open files and virtual memory can be
20724 shared easily among tasks. Having all tasks in one process
20725 allows better integration with the programming environment
20726 (the shell and the debugger, for example).
20727
20728 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
20729 code that calls DECthreads routines can be used together.
20730 The interaction between Ada tasks and DECthreads routines
20731 can have some benefits. For example when on OpenVMS Alpha,
20732 DEC Ada can call C code that is already threaded.
20733 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20734 and Ada tasks are mapped to threads.
20735
20736 @menu
20737 * Assigning Task IDs::
20738 * Task IDs and Delays::
20739 * Task-Related Pragmas::
20740 * Scheduling and Task Priority::
20741 * The Task Stack::
20742 * External Interrupts::
20743 @end menu
20744
20745 @node Assigning Task IDs
20746 @subsection Assigning Task IDs
20747
20748 @noindent
20749 The DEC Ada Run-Time Library always assigns %TASK 1 to
20750 the environment task that executes the main program. On
20751 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20752 that have been created but are not yet activated.
20753
20754 On OpenVMS Alpha systems, task IDs are assigned at
20755 activation. On GNAT systems, task IDs are also assigned at
20756 task creation but do not have the same form or values as
20757 task ID values in DEC Ada. There is no null task, and the
20758 environment task does not have a specific task ID value.
20759
20760 @node Task IDs and Delays
20761 @subsection Task IDs and Delays
20762
20763 @noindent
20764 On OpenVMS Alpha systems, tasking delays are implemented
20765 using Timer System Services. The Task ID is used for the
20766 identification of the timer request (the REQIDT parameter).
20767 If Timers are used in the application take care not to use
20768 0 for the identification, because cancelling such a timer
20769 will cancel all timers and may lead to unpredictable results.
20770
20771 @node Task-Related Pragmas
20772 @subsection Task-Related Pragmas
20773
20774 @noindent
20775 Ada supplies the pragma TASK_STORAGE, which allows
20776 specification of the size of the guard area for a task
20777 stack. (The guard area forms an area of memory that has no
20778 read or write access and thus helps in the detection of
20779 stack overflow.) On OpenVMS Alpha systems, if the pragma
20780 TASK_STORAGE specifies a value of zero, a minimal guard
20781 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20782 area is created.
20783
20784 GNAT supplies the following task-related pragmas:
20785
20786 @itemize @bullet
20787 @item  TASK_INFO
20788
20789               This pragma appears within a task definition and
20790               applies to the task in which it appears. The argument
20791               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
20792
20793 @item  TASK_STORAGE
20794
20795               GNAT implements pragma TASK_STORAGE in the same way as
20796               DEC Ada.
20797               Both DEC Ada and GNAT supply the pragmas PASSIVE,
20798               SUPPRESS, and VOLATILE.
20799 @end itemize
20800 @node Scheduling and Task Priority
20801 @subsection Scheduling and Task Priority
20802
20803 @noindent
20804 DEC Ada implements the Ada language requirement that
20805 when two tasks are eligible for execution and they have
20806 different priorities, the lower priority task does not
20807 execute while the higher priority task is waiting. The DEC
20808 Ada Run-Time Library keeps a task running until either the
20809 task is suspended or a higher priority task becomes ready.
20810
20811 On OpenVMS Alpha systems, the default strategy is round-
20812 robin with preemption. Tasks of equal priority take turns
20813 at the processor. A task is run for a certain period of
20814 time and then placed at the rear of the ready queue for
20815 its priority level.
20816
20817 DEC Ada provides the implementation-defined pragma TIME_SLICE,
20818 which can be used to enable or disable round-robin
20819 scheduling of tasks with the same priority.
20820 See the relevant DEC Ada run-time reference manual for
20821 information on using the pragmas to control DEC Ada task
20822 scheduling.
20823
20824 GNAT follows the scheduling rules of Annex D (real-time
20825 Annex) of the Ada 95 Reference Manual. In general, this
20826 scheduling strategy is fully compatible with DEC Ada
20827 although it provides some additional constraints (as
20828 fully documented in Annex D).
20829 GNAT implements time slicing control in a manner compatible with
20830 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
20831 to the DEC Ada 83 pragma of the same name.
20832 Note that it is not possible to mix GNAT tasking and
20833 DEC Ada 83 tasking in the same program, since the two run times are
20834 not compatible.
20835
20836 @node The Task Stack
20837 @subsection The Task Stack
20838
20839 @noindent
20840 In DEC Ada, a task stack is allocated each time a
20841 non passive task is activated. As soon as the task is
20842 terminated, the storage for the task stack is deallocated.
20843 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20844 a default stack size is used. Also, regardless of the size
20845 specified, some additional space is allocated for task
20846 management purposes. On OpenVMS Alpha systems, at least
20847 one page is allocated.
20848
20849 GNAT handles task stacks in a similar manner. According to
20850 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20851 an alternative method for controlling the task stack size.
20852 The specification of the attribute T'STORAGE_SIZE is also
20853 supported in a manner compatible with DEC Ada.
20854
20855 @node External Interrupts
20856 @subsection External Interrupts
20857
20858 @noindent
20859 On DEC Ada, external interrupts can be associated with task entries.
20860 GNAT is compatible with DEC Ada in its handling of external interrupts.
20861
20862 @node Pragmas and Pragma-Related Features
20863 @section Pragmas and Pragma-Related Features
20864
20865 @noindent
20866 Both DEC Ada and GNAT supply all language-defined pragmas
20867 as specified by the Ada 83 standard. GNAT also supplies all
20868 language-defined pragmas specified in the Ada 95 Reference Manual.
20869 In addition, GNAT implements the implementation-defined pragmas
20870 from DEC Ada 83.
20871
20872 @itemize @bullet
20873 @item  AST_ENTRY
20874
20875 @item  COMMON_OBJECT
20876
20877 @item  COMPONENT_ALIGNMENT
20878
20879 @item  EXPORT_EXCEPTION
20880
20881 @item  EXPORT_FUNCTION
20882
20883 @item  EXPORT_OBJECT
20884
20885 @item  EXPORT_PROCEDURE
20886
20887 @item  EXPORT_VALUED_PROCEDURE
20888
20889 @item  FLOAT_REPRESENTATION
20890
20891 @item  IDENT
20892
20893 @item  IMPORT_EXCEPTION
20894
20895 @item  IMPORT_FUNCTION
20896
20897 @item  IMPORT_OBJECT
20898
20899 @item  IMPORT_PROCEDURE
20900
20901 @item  IMPORT_VALUED_PROCEDURE
20902
20903 @item  INLINE_GENERIC
20904
20905 @item  INTERFACE_NAME
20906
20907 @item  LONG_FLOAT
20908
20909 @item  MAIN_STORAGE
20910
20911 @item  PASSIVE
20912
20913 @item  PSET_OBJECT
20914
20915 @item  SHARE_GENERIC
20916
20917 @item  SUPPRESS_ALL
20918
20919 @item  TASK_STORAGE
20920
20921 @item  TIME_SLICE
20922
20923 @item  TITLE
20924 @end itemize
20925
20926 @noindent
20927 These pragmas are all fully implemented, with the exception of @code{Title},
20928 @code{Passive}, and @code{Share_Generic}, which are
20929 recognized, but which have no
20930 effect in GNAT. The effect of @code{Passive} may be obtained by the
20931 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20932
20933 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20934 a separate subprogram specification which must appear before the
20935 subprogram body.
20936
20937 GNAT also supplies a number of implementation-defined pragmas as follows:
20938 @itemize @bullet
20939 @item  C_PASS_BY_COPY
20940
20941 @item  EXTEND_SYSTEM
20942
20943 @item  SOURCE_FILE_NAME
20944
20945 @item  UNSUPPRESS
20946
20947 @item  WARNINGS
20948
20949 @item  ABORT_DEFER
20950
20951 @item  ADA_83
20952
20953 @item  ADA_95
20954
20955 @item  ADA_05
20956
20957 @item  ANNOTATE
20958
20959 @item  ASSERT
20960
20961 @item  CPP_CLASS
20962
20963 @item  CPP_CONSTRUCTOR
20964
20965 @item  CPP_DESTRUCTOR
20966
20967 @item  CPP_VIRTUAL
20968
20969 @item  CP_VTABLE
20970
20971 @item  DEBUG
20972
20973 @item  LINKER_ALIAS
20974
20975 @item  LINKER_SECTION
20976
20977 @item  MACHINE_ATTRIBUTE
20978
20979 @item  NO_RETURN
20980
20981 @item  PURE_FUNCTION
20982
20983 @item  SOURCE_REFERENCE
20984
20985 @item  TASK_INFO
20986
20987 @item  UNCHECKED_UNION
20988
20989 @item  UNIMPLEMENTED_UNIT
20990
20991 @item  UNIVERSAL_DATA
20992
20993 @item  WEAK_EXTERNAL
20994 @end itemize
20995
20996 @noindent
20997 For full details on these GNAT implementation-defined pragmas, see
20998 the GNAT Reference Manual.
20999
21000 @menu
21001 * Restrictions on the Pragma INLINE::
21002 * Restrictions on the Pragma INTERFACE::
21003 * Restrictions on the Pragma SYSTEM_NAME::
21004 @end menu
21005
21006 @node Restrictions on the Pragma INLINE
21007 @subsection Restrictions on the Pragma INLINE
21008
21009 @noindent
21010 DEC Ada applies the following restrictions to the pragma INLINE:
21011 @itemize @bullet
21012 @item  Parameters cannot be a task type.
21013
21014 @item  Function results cannot be task types, unconstrained
21015 array types, or unconstrained types with discriminants.
21016
21017 @item  Bodies cannot declare the following:
21018 @itemize @bullet
21019 @item  Subprogram body or stub (imported subprogram is allowed)
21020
21021 @item  Tasks
21022
21023 @item  Generic declarations
21024
21025 @item  Instantiations
21026
21027 @item  Exceptions
21028
21029 @item  Access types (types derived from access types allowed)
21030
21031 @item  Array or record types
21032
21033 @item  Dependent tasks
21034
21035 @item  Direct recursive calls of subprogram or containing
21036 subprogram, directly or via a renaming
21037
21038 @end itemize
21039 @end itemize
21040
21041 @noindent
21042 In GNAT, the only restriction on pragma INLINE is that the
21043 body must occur before the call if both are in the same
21044 unit, and the size must be appropriately small. There are
21045 no other specific restrictions which cause subprograms to
21046 be incapable of being inlined.
21047
21048 @node  Restrictions on the Pragma INTERFACE
21049 @subsection  Restrictions on the Pragma INTERFACE
21050
21051 @noindent
21052 The following lists and describes the restrictions on the
21053 pragma INTERFACE on DEC Ada and GNAT:
21054 @itemize @bullet
21055 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21056 Default is the default on OpenVMS Alpha systems.
21057
21058 @item  Parameter passing: Language specifies default
21059 mechanisms but can be overridden with an EXPORT pragma.
21060
21061 @itemize @bullet
21062 @item  Ada: Use internal Ada rules.
21063
21064 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21065 record or task type. Result cannot be a string, an
21066 array, or a record.
21067
21068 @item  Fortran: Parameters cannot be a task. Result cannot
21069 be a string, an array, or a record.
21070 @end itemize
21071 @end itemize
21072
21073 @noindent
21074 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
21075 record parameters for all languages.
21076
21077 @node  Restrictions on the Pragma SYSTEM_NAME
21078 @subsection  Restrictions on the Pragma SYSTEM_NAME
21079
21080 @noindent
21081 For DEC Ada for OpenVMS Alpha, the enumeration literal
21082 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
21083 literal for the type NAME is SYSTEM_NAME_GNAT.
21084
21085 @node  Library of Predefined Units
21086 @section  Library of Predefined Units
21087
21088 @noindent
21089 A library of predefined units is provided as part of the
21090 DEC Ada and GNAT implementations. DEC Ada does not provide
21091 the package MACHINE_CODE but instead recommends importing
21092 assembler code.
21093
21094 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
21095 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21096 version. During GNAT installation, the DEC Ada Predefined
21097 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
21098 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
21099 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
21100 for details.
21101
21102 The GNAT RTL is contained in
21103 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
21104 the default search path is set up to find DECLIB units in preference
21105 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
21106 for example).
21107
21108 However, it is possible to change the default so that the
21109 reverse is true, or even to mix them using child package
21110 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
21111 is the package name, and the Ada units are available in the
21112 standard manner defined for Ada 95, that is to say as Ada.xxx. To
21113 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
21114 appropriately. For example, to change the default to use the Ada95
21115 versions do:
21116
21117 @smallexample
21118 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
21119                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21120 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
21121                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21122 @end smallexample
21123
21124 @menu
21125 * Changes to DECLIB::
21126 @end menu
21127
21128 @node Changes to DECLIB
21129 @subsection Changes to DECLIB
21130
21131 @noindent
21132 The changes made to the DEC Ada predefined library for GNAT and Ada 95
21133 compatibility are minor and include the following:
21134
21135 @itemize @bullet
21136 @item  Adjusting the location of pragmas and record representation
21137 clauses to obey Ada 95 rules
21138
21139 @item  Adding the proper notation to generic formal parameters
21140 that take unconstrained types in instantiation
21141
21142 @item  Adding pragma ELABORATE_BODY to package specifications
21143 that have package bodies not otherwise allowed
21144
21145 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
21146 @code{"PROTECTD"}.
21147 Currently these are found only in the STARLET package spec.
21148 @end itemize
21149
21150 @noindent
21151 None of the above changes is visible to users.
21152
21153 @node Bindings
21154 @section Bindings
21155
21156 @noindent
21157 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
21158 @itemize @bullet
21159
21160 @item  Command Language Interpreter (CLI interface)
21161
21162 @item  DECtalk Run-Time Library (DTK interface)
21163
21164 @item  Librarian utility routines (LBR interface)
21165
21166 @item  General Purpose Run-Time Library (LIB interface)
21167
21168 @item  Math Run-Time Library (MTH interface)
21169
21170 @item  National Character Set Run-Time Library (NCS interface)
21171
21172 @item  Compiled Code Support Run-Time Library (OTS interface)
21173
21174 @item  Parallel Processing Run-Time Library (PPL interface)
21175
21176 @item  Screen Management Run-Time Library (SMG interface)
21177
21178 @item  Sort Run-Time Library (SOR interface)
21179
21180 @item  String Run-Time Library (STR interface)
21181
21182 @item STARLET System Library
21183 @findex Starlet
21184
21185 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21186
21187 @item  X Windows Toolkit (XT interface)
21188
21189 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21190 @end itemize
21191
21192 @noindent
21193 GNAT provides implementations of these DEC bindings in the DECLIB directory.
21194
21195 The X/Motif bindings used to build DECLIB are whatever versions are in the
21196 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21197 The build script will
21198 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
21199 and @code{X_Lib}
21200 causing the default X/Motif sharable image libraries to be linked in. This
21201 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21202 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21203
21204 It may be necessary to edit these options files to update or correct the
21205 library names if, for example, the newer X/Motif bindings from
21206 @file{ADA$EXAMPLES}
21207 had been (previous to installing GNAT) copied and renamed to supersede the
21208 default @file{ADA$PREDEFINED} versions.
21209
21210 @menu
21211 * Shared Libraries and Options Files::
21212 * Interfaces to C::
21213 @end menu
21214
21215 @node Shared Libraries and Options Files
21216 @subsection Shared Libraries and Options Files
21217
21218 @noindent
21219 When using the DEC Ada
21220 predefined X and Motif bindings, the linking with their sharable images is
21221 done automatically by @command{GNAT LINK}.
21222 When using other X and Motif bindings, you need
21223 to add the corresponding sharable images to the command line for
21224 @code{GNAT LINK}. When linking with shared libraries, or with
21225 @file{.OPT} files, you must
21226 also add them to the command line for @command{GNAT LINK}.
21227
21228 A shared library to be used with GNAT is built in the same way as other
21229 libraries under VMS. The VMS Link command can be used in standard fashion.
21230
21231 @node Interfaces to C
21232 @subsection Interfaces to C
21233
21234 @noindent
21235 DEC Ada
21236 provides the following Ada types and operations:
21237
21238 @itemize @bullet
21239 @item C types package (C_TYPES)
21240
21241 @item C strings (C_TYPES.NULL_TERMINATED)
21242
21243 @item Other_types (SHORT_INT)
21244 @end itemize
21245
21246 @noindent
21247 Interfacing to C with GNAT, one can use the above approach
21248 described for DEC Ada or the facilities of Annex B of
21249 the Ada 95 Reference Manual (packages INTERFACES.C,
21250 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21251 information, see the section ``Interfacing to C'' in the
21252 @cite{GNAT Reference Manual}.
21253
21254 The @option{-gnatF} qualifier forces default and explicit
21255 @code{External_Name} parameters in pragmas Import and Export
21256 to be uppercased for compatibility with the default behavior
21257 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21258
21259 @node Main Program Definition
21260 @section Main Program Definition
21261
21262 @noindent
21263 The following section discusses differences in the
21264 definition of main programs on DEC Ada and GNAT.
21265 On DEC Ada, main programs are defined to meet the
21266 following conditions:
21267 @itemize @bullet
21268 @item  Procedure with no formal parameters (returns 0 upon
21269        normal completion)
21270
21271 @item  Procedure with no formal parameters (returns 42 when
21272        unhandled exceptions are raised)
21273
21274 @item  Function with no formal parameters whose returned value
21275        is of a discrete type
21276
21277 @item  Procedure with one OUT formal of a discrete type for
21278        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21279
21280 @end itemize
21281
21282 @noindent
21283 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21284 a main function or main procedure returns a discrete
21285 value whose size is less than 64 bits (32 on VAX systems),
21286 the value is zero- or sign-extended as appropriate.
21287 On GNAT, main programs are defined as follows:
21288 @itemize @bullet
21289 @item  Must be a non-generic, parameter-less subprogram that
21290 is either a procedure or function returning an Ada
21291 STANDARD.INTEGER (the predefined type)
21292
21293 @item  Cannot be a generic subprogram or an instantiation of a
21294 generic subprogram
21295 @end itemize
21296
21297 @node Implementation-Defined Attributes
21298 @section Implementation-Defined Attributes
21299
21300 @noindent
21301 GNAT provides all DEC Ada implementation-defined
21302 attributes.
21303
21304 @node Compiler and Run-Time Interfacing
21305 @section Compiler and Run-Time Interfacing
21306
21307 @noindent
21308 DEC Ada provides the following ways to pass options to the linker
21309 (ACS LINK):
21310 @itemize @bullet
21311 @item  /WAIT and /SUBMIT qualifiers
21312
21313 @item  /COMMAND qualifier
21314
21315 @item  /[NO]MAP qualifier
21316
21317 @item  /OUTPUT=file-spec
21318
21319 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21320 @end itemize
21321
21322 @noindent
21323 To pass options to the linker, GNAT provides the following
21324 switches:
21325
21326 @itemize @bullet
21327 @item   @option{/EXECUTABLE=exec-name}
21328
21329 @item   @option{/VERBOSE qualifier}
21330
21331 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21332 @end itemize
21333
21334 @noindent
21335 For more information on these switches, see
21336 @ref{Switches for gnatlink}.
21337 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
21338 to control optimization. DEC Ada also supplies the
21339 following pragmas:
21340 @itemize @bullet
21341 @item  @code{OPTIMIZE}
21342
21343 @item  @code{INLINE}
21344
21345 @item  @code{INLINE_GENERIC}
21346
21347 @item  @code{SUPPRESS_ALL}
21348
21349 @item  @code{PASSIVE}
21350 @end itemize
21351
21352 @noindent
21353 In GNAT, optimization is controlled strictly by command
21354 line parameters, as described in the corresponding section of this guide.
21355 The DIGITAL pragmas for control of optimization are
21356 recognized but ignored.
21357
21358 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
21359 the default is that optimization is turned on.
21360
21361 @node Program Compilation and Library Management
21362 @section Program Compilation and Library Management
21363
21364 @noindent
21365 DEC Ada and GNAT provide a comparable set of commands to
21366 build programs. DEC Ada also provides a program library,
21367 which is a concept that does not exist on GNAT. Instead,
21368 GNAT provides directories of sources that are compiled as
21369 needed.
21370
21371 The following table summarizes
21372 the DEC Ada commands and provides
21373 equivalent GNAT commands. In this table, some GNAT
21374 equivalents reflect the fact that GNAT does not use the
21375 concept of a program library. Instead, it uses a model
21376 in which collections of source and object files are used
21377 in a manner consistent with other languages like C and
21378 Fortran. Therefore, standard system file commands are used
21379 to manipulate these elements. Those GNAT commands are marked with
21380 an asterisk.
21381 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
21382
21383 @need 1500
21384 @multitable @columnfractions .35 .65
21385
21386 @item @emph{DEC Ada Command}
21387 @tab @emph{GNAT Equivalent / Description}
21388
21389 @item @command{ADA}
21390 @tab @command{GNAT COMPILE}@*
21391 Invokes the compiler to compile one or more Ada source files.
21392
21393 @item @command{ACS ATTACH}@*
21394 @tab [No equivalent]@*
21395 Switches control of terminal from current process running the program
21396 library manager.
21397
21398 @item @command{ACS CHECK}
21399 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21400 Forms the execution closure of one
21401 or more compiled units and checks completeness and currency.
21402
21403 @item @command{ACS COMPILE}
21404 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21405 Forms the execution closure of one or
21406 more specified units, checks completeness and currency,
21407 identifies units that have revised source files, compiles same,
21408 and recompiles units that are or will become obsolete.
21409 Also completes incomplete generic instantiations.
21410
21411 @item @command{ACS COPY FOREIGN}
21412 @tab Copy (*)@*
21413 Copies a foreign object file into the program library as a
21414 library unit body.
21415
21416 @item @command{ACS COPY UNIT}
21417 @tab Copy (*)@*
21418 Copies a compiled unit from one program library to another.
21419
21420 @item @command{ACS CREATE LIBRARY}
21421 @tab Create /directory (*)@*
21422 Creates a program library.
21423
21424 @item @command{ACS CREATE SUBLIBRARY}
21425 @tab Create /directory (*)@*
21426 Creates a program sublibrary.
21427
21428 @item @command{ACS DELETE LIBRARY}
21429 @tab @*
21430 Deletes a program library and its contents.
21431
21432 @item @command{ACS DELETE SUBLIBRARY}
21433 @tab @*
21434 Deletes a program sublibrary and its contents.
21435
21436 @item @command{ACS DELETE UNIT}
21437 @tab Delete file (*)@*
21438 On OpenVMS systems, deletes one or more compiled units from
21439 the current program library.
21440
21441 @item @command{ACS DIRECTORY}
21442 @tab Directory (*)@*
21443 On OpenVMS systems, lists units contained in the current
21444 program library.
21445
21446 @item @command{ACS ENTER FOREIGN}
21447 @tab Copy (*)@*
21448 Allows the import of a foreign body as an Ada library
21449 specification and enters a reference to a pointer.
21450
21451 @item @command{ACS ENTER UNIT}
21452 @tab Copy (*)@*
21453 Enters a reference (pointer) from the current program library to
21454 a unit compiled into another program library.
21455
21456 @item @command{ACS EXIT}
21457 @tab [No equivalent]@*
21458 Exits from the program library manager.
21459
21460 @item @command{ACS EXPORT}
21461 @tab Copy (*)@*
21462 Creates an object file that contains system-specific object code
21463 for one or more units. With GNAT, object files can simply be copied
21464 into the desired directory.
21465
21466 @item @command{ACS EXTRACT SOURCE}
21467 @tab Copy (*)@*
21468 Allows access to the copied source file for each Ada compilation unit
21469
21470 @item @command{ACS HELP}
21471 @tab @command{HELP GNAT}@*
21472 Provides online help.
21473
21474 @item @command{ACS LINK}
21475 @tab @command{GNAT LINK}@*
21476 Links an object file containing Ada units into an executable file.
21477
21478 @item @command{ACS LOAD}
21479 @tab Copy (*)@*
21480 Loads (partially compiles) Ada units into the program library.
21481 Allows loading a program from a collection of files into a library
21482 without knowing the relationship among units.
21483
21484 @item @command{ACS MERGE}
21485 @tab Copy (*)@*
21486 Merges into the current program library, one or more units from
21487 another library where they were modified.
21488
21489 @item @command{ACS RECOMPILE}
21490 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21491 Recompiles from   external or copied source files any obsolete
21492 unit in the closure. Also, completes any incomplete generic
21493 instantiations.
21494
21495 @item @command{ACS REENTER}
21496 @tab @command{GNAT MAKE}@*
21497 Reenters current references to units compiled after last entered
21498 with the @command{ACS ENTER UNIT} command.
21499
21500 @item @command{ACS SET LIBRARY}
21501 @tab Set default (*)@*
21502 Defines a program library to be the compilation context as well
21503 as the target library for compiler output and commands in general.
21504
21505 @item @command{ACS SET PRAGMA}
21506 @tab Edit @file{gnat.adc} (*)@*
21507 Redefines specified  values of the library characteristics
21508 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21509 and @code{Float_Representation}.
21510
21511 @item @command{ACS SET SOURCE}
21512 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21513 Defines the source file search list for the @command{ACS COMPILE} command.
21514
21515 @item @command{ACS SHOW LIBRARY}
21516 @tab Directory (*)@*
21517 Lists information about one or more program libraries.
21518
21519 @item @command{ACS SHOW PROGRAM}
21520 @tab [No equivalent]@*
21521 Lists information about the execution closure of one or
21522 more units in the program library.
21523
21524 @item @command{ACS SHOW SOURCE}
21525 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21526 Shows the source file search used when compiling units.
21527
21528 @item @command{ACS SHOW VERSION}
21529 @tab Compile with @option{VERBOSE} option
21530 Displays the version number of the compiler and program library
21531 manager used.
21532
21533 @item @command{ACS SPAWN}
21534 @tab [No equivalent]@*
21535 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21536 command).
21537
21538 @item @command{ACS VERIFY}
21539 @tab [No equivalent]@*
21540 Performs a series of consistency checks on a program library to
21541 determine whether the library structure and library files are in
21542 valid form.
21543 @end multitable
21544
21545 @noindent
21546
21547 @node Input-Output
21548 @section Input-Output
21549
21550 @noindent
21551 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
21552 Management Services (RMS) to perform operations on
21553 external files.
21554
21555 @noindent
21556 DEC Ada and GNAT predefine an identical set of input-
21557 output packages. To make the use of the
21558 generic TEXT_IO operations more convenient, DEC Ada
21559 provides predefined library packages that instantiate the
21560 integer and floating-point operations for the predefined
21561 integer and floating-point types as shown in the following table.
21562
21563 @multitable @columnfractions .45 .55
21564 @item @emph{Package Name} @tab Instantiation
21565
21566 @item @code{INTEGER_TEXT_IO}
21567 @tab @code{INTEGER_IO(INTEGER)}
21568
21569 @item @code{SHORT_INTEGER_TEXT_IO}
21570 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21571
21572 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21573 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21574
21575 @item @code{FLOAT_TEXT_IO}
21576 @tab @code{FLOAT_IO(FLOAT)}
21577
21578 @item @code{LONG_FLOAT_TEXT_IO}
21579 @tab @code{FLOAT_IO(LONG_FLOAT)}
21580 @end multitable
21581
21582 @noindent
21583 The DEC Ada predefined packages and their operations
21584 are implemented using OpenVMS Alpha files and input-
21585 output facilities. DEC Ada supports asynchronous input-
21586 output on OpenVMS Alpha. Familiarity with the following is
21587 recommended:
21588 @itemize @bullet
21589 @item  RMS file organizations and access methods
21590
21591 @item  OpenVMS file specifications and directories
21592
21593 @item  OpenVMS File Definition Language (FDL)
21594 @end itemize
21595
21596 @noindent
21597 GNAT provides I/O facilities that are completely
21598 compatible with DEC Ada. The distribution includes the
21599 standard DEC Ada versions of all I/O packages, operating
21600 in a manner compatible with DEC Ada. In particular, the
21601 following packages are by default the DEC Ada (Ada 83)
21602 versions of these packages rather than the renamings
21603 suggested in annex J of the Ada 95 Reference Manual:
21604 @itemize @bullet
21605 @item  @code{TEXT_IO}
21606
21607 @item  @code{SEQUENTIAL_IO}
21608
21609 @item  @code{DIRECT_IO}
21610 @end itemize
21611
21612 @noindent
21613 The use of the standard Ada 95 syntax for child packages (for
21614 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21615 packages, as defined in the Ada 95 Reference Manual.
21616 GNAT provides DIGITAL-compatible predefined instantiations
21617 of the @code{TEXT_IO} packages, and also
21618 provides the standard predefined instantiations required
21619 by the Ada 95 Reference Manual.
21620
21621 For further information on how GNAT interfaces to the file
21622 system or how I/O is implemented in programs written in
21623 mixed languages, see the chapter ``Implementation of the
21624 Standard I/O'' in the @cite{GNAT Reference Manual}.
21625 This chapter covers the following:
21626 @itemize @bullet
21627 @item  Standard I/O packages
21628
21629 @item  @code{FORM} strings
21630
21631 @item  @code{ADA.DIRECT_IO}
21632
21633 @item  @code{ADA.SEQUENTIAL_IO}
21634
21635 @item  @code{ADA.TEXT_IO}
21636
21637 @item  Stream pointer positioning
21638
21639 @item  Reading and writing non-regular files
21640
21641 @item  @code{GET_IMMEDIATE}
21642
21643 @item  Treating @code{TEXT_IO} files as streams
21644
21645 @item  Shared files
21646
21647 @item  Open modes
21648 @end itemize
21649
21650 @node Implementation Limits
21651 @section Implementation Limits
21652
21653 @noindent
21654 The following table lists implementation limits for DEC Ada
21655 and GNAT systems.
21656 @multitable @columnfractions .60 .20 .20
21657 @sp 1
21658 @item  @emph{Compilation Parameter}
21659 @tab   @emph{DEC Ada}
21660 @tab   @emph{GNAT}
21661 @sp 1
21662
21663 @item  In a subprogram or entry  declaration, maximum number of
21664        formal parameters that are of an unconstrained record type
21665 @tab   32
21666 @tab   No set limit
21667 @sp 1
21668
21669 @item  Maximum identifier length (number of characters)
21670 @tab   255
21671 @tab   255
21672 @sp 1
21673
21674 @item  Maximum number of characters in a source line
21675 @tab   255
21676 @tab   255
21677 @sp 1
21678
21679 @item  Maximum collection size   (number of bytes)
21680 @tab   2**31-1
21681 @tab   2**31-1
21682 @sp 1
21683
21684 @item  Maximum number of discriminants for a record type
21685 @tab   245
21686 @tab   No set limit
21687 @sp 1
21688
21689 @item  Maximum number of formal parameters in an entry or
21690        subprogram declaration
21691 @tab   246
21692 @tab    No set limit
21693 @sp 1
21694
21695 @item  Maximum number of dimensions in an array type
21696 @tab   255
21697 @tab   No set limit
21698 @sp 1
21699
21700 @item  Maximum number of library  units and subunits in a compilation.
21701 @tab   4095
21702 @tab   No set limit
21703 @sp 1
21704
21705 @item  Maximum number of library units and subunits in an execution.
21706 @tab   16383
21707 @tab   No set limit
21708 @sp 1
21709
21710 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21711        or @code{PSECT_OBJECT}
21712 @tab   32757
21713 @tab   No set limit
21714 @sp 1
21715
21716 @item  Maximum number of enumeration literals in an enumeration type
21717        definition
21718 @tab   65535
21719 @tab   No set limit
21720 @sp 1
21721
21722 @item  Maximum number of lines in a source file
21723 @tab   65534
21724 @tab   No set limit
21725 @sp 1
21726
21727 @item  Maximum number of bits in any object
21728 @tab   2**31-1
21729 @tab   2**31-1
21730 @sp 1
21731
21732 @item  Maximum size of the static portion of a stack frame (approximate)
21733 @tab   2**31-1
21734 @tab   2**31-1
21735 @end multitable
21736
21737 @node  Tools
21738 @section Tools
21739
21740 @end ifset
21741
21742 @c **************************************
21743 @node Platform-Specific Information for the Run-Time Libraries
21744 @appendix Platform-Specific Information for the Run-Time Libraries
21745 @cindex Tasking and threads libraries
21746 @cindex Threads libraries and tasking
21747 @cindex Run-time libraries (platform-specific information)
21748
21749 @noindent
21750 The GNAT run-time implementation may vary with respect to both the
21751 underlying threads library and the exception handling scheme.
21752 For threads support, one or more of the following are supplied:
21753 @itemize @bullet
21754 @item @b{native threads library}, a binding to the thread package from
21755 the underlying operating system
21756
21757 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21758 POSIX thread package
21759 @end itemize
21760
21761 @noindent
21762 For exception handling, either or both of two models are supplied:
21763 @itemize @bullet
21764 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21765 Most programs should experience a substantial speed improvement by
21766 being compiled with a ZCX run-time.
21767 This is especially true for
21768 tasking applications or applications with many exception handlers.}
21769 @cindex Zero-Cost Exceptions
21770 @cindex ZCX (Zero-Cost Exceptions)
21771 which uses binder-generated tables that
21772 are interrogated at run time to locate a handler
21773
21774 @item @b{setjmp / longjmp} (``SJLJ''),
21775 @cindex setjmp/longjmp Exception Model
21776 @cindex SJLJ (setjmp/longjmp Exception Model)
21777 which uses dynamically-set data to establish
21778 the set of handlers
21779 @end itemize
21780
21781 @noindent
21782 This appendix summarizes which combinations of threads and exception support
21783 are supplied on various GNAT platforms.
21784 It then shows how to select a particular library either
21785 permanently or temporarily,
21786 explains the properties of (and tradeoffs among) the various threads
21787 libraries, and provides some additional
21788 information about several specific platforms.
21789
21790 @menu
21791 * Summary of Run-Time Configurations::
21792 * Specifying a Run-Time Library::
21793 * Choosing the Scheduling Policy::
21794 * Solaris-Specific Considerations::
21795 * IRIX-Specific Considerations::
21796 * Linux-Specific Considerations::
21797 * AIX-Specific Considerations::
21798 @end menu
21799
21800 @node Summary of Run-Time Configurations
21801 @section Summary of Run-Time Configurations
21802
21803 @multitable @columnfractions .30 .70
21804 @item @b{alpha-openvms}
21805 @item @code{@ @ }@i{rts-native (default)}
21806 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21807 @item @code{@ @ @ @ }Exceptions @tab ZCX
21808 @*
21809 @item @b{pa-hpux}
21810 @item @code{@ @ }@i{rts-native (default)}
21811 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21812 @item @code{@ @ @ @ }Exceptions @tab ZCX
21813 @*
21814 @item @code{@ @ }@i{rts-sjlj}
21815 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21816 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21817 @*
21818 @item @b{sparc-solaris}  @tab
21819 @item @code{@ @ }@i{rts-native (default)}
21820 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21821 @item @code{@ @ @ @ }Exceptions @tab ZCX
21822 @*
21823 @item @code{@ @ }@i{rts-m64}
21824 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
21825 @item @code{@ @ @ @ }Exceptions  @tab ZCX
21826 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
21827 @item    @tab Use only on Solaris 8 or later.
21828 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
21829 @*
21830 @item @code{@ @ }@i{rts-pthread}
21831 @item @code{@ @ @ @ }Tasking    @tab pthreads library
21832 @item @code{@ @ @ @ }Exceptions @tab ZCX
21833 @*
21834 @item @code{@ @ }@i{rts-sjlj}
21835 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21836 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21837 @*
21838 @item @b{x86-linux}
21839 @item @code{@ @ }@i{rts-native (default)}
21840 @item @code{@ @ @ @ }Tasking    @tab pthread library
21841 @item @code{@ @ @ @ }Exceptions @tab ZCX
21842 @*
21843 @item @code{@ @ }@i{rts-sjlj}
21844 @item @code{@ @ @ @ }Tasking    @tab pthread library
21845 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21846 @*
21847 @item @b{x86-windows}
21848 @item @code{@ @ }@i{rts-native (default)}
21849 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21850 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21851 @*
21852 @end multitable
21853
21854 @node Specifying a Run-Time Library
21855 @section Specifying a Run-Time Library
21856
21857 @noindent
21858 The @file{adainclude} subdirectory containing the sources of the GNAT
21859 run-time library, and the @file{adalib} subdirectory containing the
21860 @file{ALI} files and the static and/or shared GNAT library, are located
21861 in the gcc target-dependent area:
21862
21863 @smallexample
21864 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21865 @end smallexample
21866
21867 @noindent
21868 As indicated above, on some platforms several run-time libraries are supplied.
21869 These libraries are installed in the target dependent area and
21870 contain a complete source and binary subdirectory. The detailed description
21871 below explains the differences between the different libraries in terms of
21872 their thread support.
21873
21874 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21875 This default run time is selected by the means of soft links.
21876 For example on x86-linux:
21877
21878 @smallexample
21879 @group
21880  $(target-dir)
21881      |
21882      +--- adainclude----------+
21883      |                        |
21884      +--- adalib-----------+  |
21885      |                     |  |
21886      +--- rts-native       |  |
21887      |    |                |  |
21888      |    +--- adainclude <---+
21889      |    |                |
21890      |    +--- adalib <----+
21891      |
21892      +--- rts-sjlj
21893           |
21894           +--- adainclude
21895           |
21896           +--- adalib
21897 @end group
21898 @end smallexample
21899
21900 @noindent
21901 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21902 these soft links can be modified with the following commands:
21903
21904 @smallexample
21905 $ cd $target
21906 $ rm -f adainclude adalib
21907 $ ln -s rts-sjlj/adainclude adainclude
21908 $ ln -s rts-sjlj/adalib adalib
21909 @end smallexample
21910
21911 @noindent
21912 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21913 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21914 @file{$target/ada_object_path}.
21915
21916 Selecting another run-time library temporarily can be
21917 achieved by the regular mechanism for GNAT object or source path selection:
21918
21919 @itemize @bullet
21920 @item
21921 Set the environment variables:
21922
21923 @smallexample
21924 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
21925 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
21926 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21927 @end smallexample
21928
21929 @item
21930 Use @option{-aI$target/rts-sjlj/adainclude}
21931 and @option{-aO$target/rts-sjlj/adalib}
21932 on the @command{gnatmake} command line
21933
21934 @item
21935 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
21936 @cindex @option{--RTS} option
21937 @end itemize
21938
21939 @node Choosing the Scheduling Policy
21940 @section Choosing the Scheduling Policy
21941
21942 @noindent
21943 When using a POSIX threads implementation, you have a choice of several
21944 scheduling policies: @code{SCHED_FIFO},
21945 @cindex @code{SCHED_FIFO} scheduling policy
21946 @code{SCHED_RR}
21947 @cindex @code{SCHED_RR} scheduling policy
21948 and @code{SCHED_OTHER}.
21949 @cindex @code{SCHED_OTHER} scheduling policy
21950 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21951 or @code{SCHED_RR} requires special (e.g., root) privileges.
21952
21953 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21954 @code{SCHED_FIFO},
21955 @cindex @code{SCHED_FIFO} scheduling policy
21956 you can use one of the following:
21957
21958 @itemize @bullet
21959 @item
21960 @code{pragma Time_Slice (0.0)}
21961 @cindex pragma Time_Slice
21962 @item
21963 the corresponding binder option @option{-T0}
21964 @cindex @option{-T0} option
21965 @item
21966 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21967 @cindex pragma Task_Dispatching_Policy
21968 @end itemize
21969
21970 @noindent
21971 To specify @code{SCHED_RR},
21972 @cindex @code{SCHED_RR} scheduling policy
21973 you should use @code{pragma Time_Slice} with a
21974 value greater than @code{0.0}, or else use the corresponding @option{-T}
21975 binder option.
21976
21977 @node Solaris-Specific Considerations
21978 @section Solaris-Specific Considerations
21979 @cindex Solaris Sparc threads libraries
21980
21981 @noindent
21982 This section addresses some topics related to the various threads libraries
21983 on Sparc Solaris and then provides some information on building and
21984 debugging 64-bit applications.
21985
21986 @menu
21987 * Solaris Threads Issues::
21988 * Building and Debugging 64-bit Applications::
21989 @end menu
21990
21991 @node Solaris Threads Issues
21992 @subsection Solaris Threads Issues
21993
21994 @noindent
21995 GNAT under Solaris comes with an alternate tasking run-time library
21996 based on POSIX threads --- @emph{rts-pthread}.
21997 @cindex rts-pthread threads library
21998 This run-time library has the advantage of being mostly shared across all
21999 POSIX-compliant thread implementations, and it also provides under
22000 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22001 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22002 and @code{PTHREAD_PRIO_PROTECT}
22003 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22004 semantics that can be selected using the predefined pragma
22005 @code{Locking_Policy}
22006 @cindex pragma Locking_Policy (under rts-pthread)
22007 with respectively
22008 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22009 @cindex @code{Inheritance_Locking} (under rts-pthread)
22010 @cindex @code{Ceiling_Locking} (under rts-pthread)
22011
22012 As explained above, the native run-time library is based on the Solaris thread
22013 library (@code{libthread}) and is the default library.
22014
22015 When the Solaris threads library is used (this is the default), programs
22016 compiled with GNAT can automatically take advantage of
22017 and can thus execute on multiple processors.
22018 The user can alternatively specify a processor on which the program should run
22019 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22020 is made by
22021 setting the environment variable @code{GNAT_PROCESSOR}
22022 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22023 to one of the following:
22024
22025 @table @code
22026 @item -2
22027 Use the default configuration (run the program on all
22028          available processors) - this is the same as having
22029          @code{GNAT_PROCESSOR} unset
22030
22031 @item -1
22032 Let the run-time implementation choose one processor and run the program on
22033          that processor
22034
22035 @item 0 .. Last_Proc
22036 Run the program on the specified processor.
22037   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22038 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22039 @end table
22040
22041 @node Building and Debugging 64-bit Applications
22042 @subsection Building and Debugging 64-bit Applications
22043
22044 @noindent
22045 In a 64-bit application, all the sources involved must be compiled with the
22046 @option{-m64} command-line option, and a specific GNAT library (compiled with
22047 this option) is required.
22048 The easiest way to build a 64bit application is to add
22049 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
22050
22051 To debug these applications, a special version of gdb called @command{gdb64}
22052 needs to be used.
22053
22054 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
22055 amounts to:
22056
22057 @smallexample
22058      $ gnatmake -m64 -g --RTS=m64 hello.adb
22059      $ gdb64 hello
22060 @end smallexample
22061
22062 In addition, the following capabilities are not supported when using the
22063 @option{-m64} option:
22064
22065 @table @code
22066 @item -fstack-check does not work together with -m64.
22067 Any application combining these options crashes at startup time.
22068
22069 @item Call-chain backtrace computation does not work with -m64.
22070 Thus the gnatbind switch -E is not supported.
22071 @end table
22072
22073 @node IRIX-Specific Considerations
22074 @section IRIX-Specific Considerations
22075 @cindex IRIX thread library
22076
22077 @noindent
22078 On SGI IRIX, the thread library depends on which compiler is used.
22079 The @emph{o32 ABI} compiler comes with a run-time library based on the
22080 user-level @code{athread}
22081 library. Thus kernel-level capabilities such as nonblocking system
22082 calls or time slicing can only be achieved reliably by specifying different
22083 @code{sprocs} via the pragma @code{Task_Info}
22084 @cindex pragma Task_Info (and IRIX threads)
22085 and the
22086 @code{System.Task_Info} package.
22087 @cindex @code{System.Task_Info} package (and IRIX threads)
22088 See the @cite{GNAT Reference Manual} for further information.
22089
22090 The @emph{n32 ABI} compiler comes with a run-time library based on the
22091 kernel POSIX threads and thus does not have the limitations mentioned above.
22092
22093 @node Linux-Specific Considerations
22094 @section Linux-Specific Considerations
22095 @cindex Linux threads libraries
22096
22097 @noindent
22098 The default thread library under GNU/Linux has the following disadvantages
22099 compared to other native thread libraries:
22100
22101 @itemize @bullet
22102 @item The size of the task's stack is limited to 2 megabytes.
22103 @item  The signal model is not POSIX compliant, which means that to send a
22104   signal to the process, you need to send the signal to all threads,
22105   e.g. by using @code{killpg()}.
22106 @end itemize
22107
22108 @node AIX-Specific Considerations
22109 @section AIX-Specific Considerations
22110 @cindex AIX resolver library
22111
22112 @noindent
22113 On AIX, the resolver library initializes some internal structure on
22114 the first call to @code{get*by*} functions, which are used to implement
22115 @code{GNAT.Sockets.Get_Host_By_Name} and
22116 @code{GNAT.Sockets.Get_Host_By_Addrss}.
22117 If such initialization occurs within an Ada task, and the stack size for
22118 the task is the default size, a stack overflow may occur.
22119
22120 To avoid this overflow, the user should either ensure that the first call
22121 to @code{GNAT.Sockets.Get_Host_By_Name} or
22122 @code{GNAT.Sockets.Get_Host_By_Addrss}
22123 occurs in the environment task, or use @code{pragma Storage_Size} to
22124 specify a sufficiently large size for the stack of the task that contains
22125 this call.
22126
22127 @c *******************************
22128 @node Example of Binder Output File
22129 @appendix Example of Binder Output File
22130
22131 @noindent
22132 This Appendix displays the source code for @command{gnatbind}'s output
22133 file generated for a simple ``Hello World'' program.
22134 Comments have been added for clarification purposes.
22135
22136 @smallexample @c adanocomment
22137 @iftex
22138 @leftskip=0cm
22139 @end iftex
22140 --  The package is called Ada_Main unless this name is actually used
22141 --  as a unit name in the partition, in which case some other unique
22142 --  name is used.
22143
22144 with System;
22145 package ada_main is
22146
22147    Elab_Final_Code : Integer;
22148    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22149
22150    --  The main program saves the parameters (argument count,
22151    --  argument values, environment pointer) in global variables
22152    --  for later access by other units including
22153    --  Ada.Command_Line.
22154
22155    gnat_argc : Integer;
22156    gnat_argv : System.Address;
22157    gnat_envp : System.Address;
22158
22159    --  The actual variables are stored in a library routine. This
22160    --  is useful for some shared library situations, where there
22161    --  are problems if variables are not in the library.
22162
22163    pragma Import (C, gnat_argc);
22164    pragma Import (C, gnat_argv);
22165    pragma Import (C, gnat_envp);
22166
22167    --  The exit status is similarly an external location
22168
22169    gnat_exit_status : Integer;
22170    pragma Import (C, gnat_exit_status);
22171
22172    GNAT_Version : constant String :=
22173                     "GNAT Version: 3.15w (20010315)";
22174    pragma Export (C, GNAT_Version, "__gnat_version");
22175
22176    --  This is the generated adafinal routine that performs
22177    --  finalization at the end of execution. In the case where
22178    --  Ada is the main program, this main program makes a call
22179    --  to adafinal at program termination.
22180
22181    procedure adafinal;
22182    pragma Export (C, adafinal, "adafinal");
22183
22184    --  This is the generated adainit routine that performs
22185    --  initialization at the start of execution. In the case
22186    --  where Ada is the main program, this main program makes
22187    --  a call to adainit at program startup.
22188
22189    procedure adainit;
22190    pragma Export (C, adainit, "adainit");
22191
22192    --  This routine is called at the start of execution. It is
22193    --  a dummy routine that is used by the debugger to breakpoint
22194    --  at the start of execution.
22195
22196    procedure Break_Start;
22197    pragma Import (C, Break_Start, "__gnat_break_start");
22198
22199    --  This is the actual generated main program (it would be
22200    --  suppressed if the no main program switch were used). As
22201    --  required by standard system conventions, this program has
22202    --  the external name main.
22203
22204    function main
22205      (argc : Integer;
22206       argv : System.Address;
22207       envp : System.Address)
22208       return Integer;
22209    pragma Export (C, main, "main");
22210
22211    --  The following set of constants give the version
22212    --  identification values for every unit in the bound
22213    --  partition. This identification is computed from all
22214    --  dependent semantic units, and corresponds to the
22215    --  string that would be returned by use of the
22216    --  Body_Version or Version attributes.
22217
22218    type Version_32 is mod 2 ** 32;
22219    u00001 : constant Version_32 := 16#7880BEB3#;
22220    u00002 : constant Version_32 := 16#0D24CBD0#;
22221    u00003 : constant Version_32 := 16#3283DBEB#;
22222    u00004 : constant Version_32 := 16#2359F9ED#;
22223    u00005 : constant Version_32 := 16#664FB847#;
22224    u00006 : constant Version_32 := 16#68E803DF#;
22225    u00007 : constant Version_32 := 16#5572E604#;
22226    u00008 : constant Version_32 := 16#46B173D8#;
22227    u00009 : constant Version_32 := 16#156A40CF#;
22228    u00010 : constant Version_32 := 16#033DABE0#;
22229    u00011 : constant Version_32 := 16#6AB38FEA#;
22230    u00012 : constant Version_32 := 16#22B6217D#;
22231    u00013 : constant Version_32 := 16#68A22947#;
22232    u00014 : constant Version_32 := 16#18CC4A56#;
22233    u00015 : constant Version_32 := 16#08258E1B#;
22234    u00016 : constant Version_32 := 16#367D5222#;
22235    u00017 : constant Version_32 := 16#20C9ECA4#;
22236    u00018 : constant Version_32 := 16#50D32CB6#;
22237    u00019 : constant Version_32 := 16#39A8BB77#;
22238    u00020 : constant Version_32 := 16#5CF8FA2B#;
22239    u00021 : constant Version_32 := 16#2F1EB794#;
22240    u00022 : constant Version_32 := 16#31AB6444#;
22241    u00023 : constant Version_32 := 16#1574B6E9#;
22242    u00024 : constant Version_32 := 16#5109C189#;
22243    u00025 : constant Version_32 := 16#56D770CD#;
22244    u00026 : constant Version_32 := 16#02F9DE3D#;
22245    u00027 : constant Version_32 := 16#08AB6B2C#;
22246    u00028 : constant Version_32 := 16#3FA37670#;
22247    u00029 : constant Version_32 := 16#476457A0#;
22248    u00030 : constant Version_32 := 16#731E1B6E#;
22249    u00031 : constant Version_32 := 16#23C2E789#;
22250    u00032 : constant Version_32 := 16#0F1BD6A1#;
22251    u00033 : constant Version_32 := 16#7C25DE96#;
22252    u00034 : constant Version_32 := 16#39ADFFA2#;
22253    u00035 : constant Version_32 := 16#571DE3E7#;
22254    u00036 : constant Version_32 := 16#5EB646AB#;
22255    u00037 : constant Version_32 := 16#4249379B#;
22256    u00038 : constant Version_32 := 16#0357E00A#;
22257    u00039 : constant Version_32 := 16#3784FB72#;
22258    u00040 : constant Version_32 := 16#2E723019#;
22259    u00041 : constant Version_32 := 16#623358EA#;
22260    u00042 : constant Version_32 := 16#107F9465#;
22261    u00043 : constant Version_32 := 16#6843F68A#;
22262    u00044 : constant Version_32 := 16#63305874#;
22263    u00045 : constant Version_32 := 16#31E56CE1#;
22264    u00046 : constant Version_32 := 16#02917970#;
22265    u00047 : constant Version_32 := 16#6CCBA70E#;
22266    u00048 : constant Version_32 := 16#41CD4204#;
22267    u00049 : constant Version_32 := 16#572E3F58#;
22268    u00050 : constant Version_32 := 16#20729FF5#;
22269    u00051 : constant Version_32 := 16#1D4F93E8#;
22270    u00052 : constant Version_32 := 16#30B2EC3D#;
22271    u00053 : constant Version_32 := 16#34054F96#;
22272    u00054 : constant Version_32 := 16#5A199860#;
22273    u00055 : constant Version_32 := 16#0E7F912B#;
22274    u00056 : constant Version_32 := 16#5760634A#;
22275    u00057 : constant Version_32 := 16#5D851835#;
22276
22277    --  The following Export pragmas export the version numbers
22278    --  with symbolic names ending in B (for body) or S
22279    --  (for spec) so that they can be located in a link. The
22280    --  information provided here is sufficient to track down
22281    --  the exact versions of units used in a given build.
22282
22283    pragma Export (C, u00001, "helloB");
22284    pragma Export (C, u00002, "system__standard_libraryB");
22285    pragma Export (C, u00003, "system__standard_libraryS");
22286    pragma Export (C, u00004, "adaS");
22287    pragma Export (C, u00005, "ada__text_ioB");
22288    pragma Export (C, u00006, "ada__text_ioS");
22289    pragma Export (C, u00007, "ada__exceptionsB");
22290    pragma Export (C, u00008, "ada__exceptionsS");
22291    pragma Export (C, u00009, "gnatS");
22292    pragma Export (C, u00010, "gnat__heap_sort_aB");
22293    pragma Export (C, u00011, "gnat__heap_sort_aS");
22294    pragma Export (C, u00012, "systemS");
22295    pragma Export (C, u00013, "system__exception_tableB");
22296    pragma Export (C, u00014, "system__exception_tableS");
22297    pragma Export (C, u00015, "gnat__htableB");
22298    pragma Export (C, u00016, "gnat__htableS");
22299    pragma Export (C, u00017, "system__exceptionsS");
22300    pragma Export (C, u00018, "system__machine_state_operationsB");
22301    pragma Export (C, u00019, "system__machine_state_operationsS");
22302    pragma Export (C, u00020, "system__machine_codeS");
22303    pragma Export (C, u00021, "system__storage_elementsB");
22304    pragma Export (C, u00022, "system__storage_elementsS");
22305    pragma Export (C, u00023, "system__secondary_stackB");
22306    pragma Export (C, u00024, "system__secondary_stackS");
22307    pragma Export (C, u00025, "system__parametersB");
22308    pragma Export (C, u00026, "system__parametersS");
22309    pragma Export (C, u00027, "system__soft_linksB");
22310    pragma Export (C, u00028, "system__soft_linksS");
22311    pragma Export (C, u00029, "system__stack_checkingB");
22312    pragma Export (C, u00030, "system__stack_checkingS");
22313    pragma Export (C, u00031, "system__tracebackB");
22314    pragma Export (C, u00032, "system__tracebackS");
22315    pragma Export (C, u00033, "ada__streamsS");
22316    pragma Export (C, u00034, "ada__tagsB");
22317    pragma Export (C, u00035, "ada__tagsS");
22318    pragma Export (C, u00036, "system__string_opsB");
22319    pragma Export (C, u00037, "system__string_opsS");
22320    pragma Export (C, u00038, "interfacesS");
22321    pragma Export (C, u00039, "interfaces__c_streamsB");
22322    pragma Export (C, u00040, "interfaces__c_streamsS");
22323    pragma Export (C, u00041, "system__file_ioB");
22324    pragma Export (C, u00042, "system__file_ioS");
22325    pragma Export (C, u00043, "ada__finalizationB");
22326    pragma Export (C, u00044, "ada__finalizationS");
22327    pragma Export (C, u00045, "system__finalization_rootB");
22328    pragma Export (C, u00046, "system__finalization_rootS");
22329    pragma Export (C, u00047, "system__finalization_implementationB");
22330    pragma Export (C, u00048, "system__finalization_implementationS");
22331    pragma Export (C, u00049, "system__string_ops_concat_3B");
22332    pragma Export (C, u00050, "system__string_ops_concat_3S");
22333    pragma Export (C, u00051, "system__stream_attributesB");
22334    pragma Export (C, u00052, "system__stream_attributesS");
22335    pragma Export (C, u00053, "ada__io_exceptionsS");
22336    pragma Export (C, u00054, "system__unsigned_typesS");
22337    pragma Export (C, u00055, "system__file_control_blockS");
22338    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22339    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22340
22341    -- BEGIN ELABORATION ORDER
22342    -- ada (spec)
22343    -- gnat (spec)
22344    -- gnat.heap_sort_a (spec)
22345    -- gnat.heap_sort_a (body)
22346    -- gnat.htable (spec)
22347    -- gnat.htable (body)
22348    -- interfaces (spec)
22349    -- system (spec)
22350    -- system.machine_code (spec)
22351    -- system.parameters (spec)
22352    -- system.parameters (body)
22353    -- interfaces.c_streams (spec)
22354    -- interfaces.c_streams (body)
22355    -- system.standard_library (spec)
22356    -- ada.exceptions (spec)
22357    -- system.exception_table (spec)
22358    -- system.exception_table (body)
22359    -- ada.io_exceptions (spec)
22360    -- system.exceptions (spec)
22361    -- system.storage_elements (spec)
22362    -- system.storage_elements (body)
22363    -- system.machine_state_operations (spec)
22364    -- system.machine_state_operations (body)
22365    -- system.secondary_stack (spec)
22366    -- system.stack_checking (spec)
22367    -- system.soft_links (spec)
22368    -- system.soft_links (body)
22369    -- system.stack_checking (body)
22370    -- system.secondary_stack (body)
22371    -- system.standard_library (body)
22372    -- system.string_ops (spec)
22373    -- system.string_ops (body)
22374    -- ada.tags (spec)
22375    -- ada.tags (body)
22376    -- ada.streams (spec)
22377    -- system.finalization_root (spec)
22378    -- system.finalization_root (body)
22379    -- system.string_ops_concat_3 (spec)
22380    -- system.string_ops_concat_3 (body)
22381    -- system.traceback (spec)
22382    -- system.traceback (body)
22383    -- ada.exceptions (body)
22384    -- system.unsigned_types (spec)
22385    -- system.stream_attributes (spec)
22386    -- system.stream_attributes (body)
22387    -- system.finalization_implementation (spec)
22388    -- system.finalization_implementation (body)
22389    -- ada.finalization (spec)
22390    -- ada.finalization (body)
22391    -- ada.finalization.list_controller (spec)
22392    -- ada.finalization.list_controller (body)
22393    -- system.file_control_block (spec)
22394    -- system.file_io (spec)
22395    -- system.file_io (body)
22396    -- ada.text_io (spec)
22397    -- ada.text_io (body)
22398    -- hello (body)
22399    -- END ELABORATION ORDER
22400
22401 end ada_main;
22402
22403 --  The following source file name pragmas allow the generated file
22404 --  names to be unique for different main programs. They are needed
22405 --  since the package name will always be Ada_Main.
22406
22407 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22408 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22409
22410 --  Generated package body for Ada_Main starts here
22411
22412 package body ada_main is
22413
22414    --  The actual finalization is performed by calling the
22415    --  library routine in System.Standard_Library.Adafinal
22416
22417    procedure Do_Finalize;
22418    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22419
22420    -------------
22421    -- adainit --
22422    -------------
22423
22424 @findex adainit
22425    procedure adainit is
22426
22427       --  These booleans are set to True once the associated unit has
22428       --  been elaborated. It is also used to avoid elaborating the
22429       --  same unit twice.
22430
22431       E040 : Boolean;
22432       pragma Import (Ada, E040, "interfaces__c_streams_E");
22433
22434       E008 : Boolean;
22435       pragma Import (Ada, E008, "ada__exceptions_E");
22436
22437       E014 : Boolean;
22438       pragma Import (Ada, E014, "system__exception_table_E");
22439
22440       E053 : Boolean;
22441       pragma Import (Ada, E053, "ada__io_exceptions_E");
22442
22443       E017 : Boolean;
22444       pragma Import (Ada, E017, "system__exceptions_E");
22445
22446       E024 : Boolean;
22447       pragma Import (Ada, E024, "system__secondary_stack_E");
22448
22449       E030 : Boolean;
22450       pragma Import (Ada, E030, "system__stack_checking_E");
22451
22452       E028 : Boolean;
22453       pragma Import (Ada, E028, "system__soft_links_E");
22454
22455       E035 : Boolean;
22456       pragma Import (Ada, E035, "ada__tags_E");
22457
22458       E033 : Boolean;
22459       pragma Import (Ada, E033, "ada__streams_E");
22460
22461       E046 : Boolean;
22462       pragma Import (Ada, E046, "system__finalization_root_E");
22463
22464       E048 : Boolean;
22465       pragma Import (Ada, E048, "system__finalization_implementation_E");
22466
22467       E044 : Boolean;
22468       pragma Import (Ada, E044, "ada__finalization_E");
22469
22470       E057 : Boolean;
22471       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22472
22473       E055 : Boolean;
22474       pragma Import (Ada, E055, "system__file_control_block_E");
22475
22476       E042 : Boolean;
22477       pragma Import (Ada, E042, "system__file_io_E");
22478
22479       E006 : Boolean;
22480       pragma Import (Ada, E006, "ada__text_io_E");
22481
22482       --  Set_Globals is a library routine that stores away the
22483       --  value of the indicated set of global values in global
22484       --  variables within the library.
22485
22486       procedure Set_Globals
22487         (Main_Priority            : Integer;
22488          Time_Slice_Value         : Integer;
22489          WC_Encoding              : Character;
22490          Locking_Policy           : Character;
22491          Queuing_Policy           : Character;
22492          Task_Dispatching_Policy  : Character;
22493          Adafinal                 : System.Address;
22494          Unreserve_All_Interrupts : Integer;
22495          Exception_Tracebacks     : Integer);
22496 @findex __gnat_set_globals
22497       pragma Import (C, Set_Globals, "__gnat_set_globals");
22498
22499       --  SDP_Table_Build is a library routine used to build the
22500       --  exception tables. See unit Ada.Exceptions in files
22501       --  a-except.ads/adb for full details of how zero cost
22502       --  exception handling works. This procedure, the call to
22503       --  it, and the two following tables are all omitted if the
22504       --  build is in longjmp/setjump exception mode.
22505
22506 @findex SDP_Table_Build
22507 @findex Zero Cost Exceptions
22508       procedure SDP_Table_Build
22509         (SDP_Addresses   : System.Address;
22510          SDP_Count       : Natural;
22511          Elab_Addresses  : System.Address;
22512          Elab_Addr_Count : Natural);
22513       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22514
22515       --  Table of Unit_Exception_Table addresses. Used for zero
22516       --  cost exception handling to build the top level table.
22517
22518       ST : aliased constant array (1 .. 23) of System.Address := (
22519         Hello'UET_Address,
22520         Ada.Text_Io'UET_Address,
22521         Ada.Exceptions'UET_Address,
22522         Gnat.Heap_Sort_A'UET_Address,
22523         System.Exception_Table'UET_Address,
22524         System.Machine_State_Operations'UET_Address,
22525         System.Secondary_Stack'UET_Address,
22526         System.Parameters'UET_Address,
22527         System.Soft_Links'UET_Address,
22528         System.Stack_Checking'UET_Address,
22529         System.Traceback'UET_Address,
22530         Ada.Streams'UET_Address,
22531         Ada.Tags'UET_Address,
22532         System.String_Ops'UET_Address,
22533         Interfaces.C_Streams'UET_Address,
22534         System.File_Io'UET_Address,
22535         Ada.Finalization'UET_Address,
22536         System.Finalization_Root'UET_Address,
22537         System.Finalization_Implementation'UET_Address,
22538         System.String_Ops_Concat_3'UET_Address,
22539         System.Stream_Attributes'UET_Address,
22540         System.File_Control_Block'UET_Address,
22541         Ada.Finalization.List_Controller'UET_Address);
22542
22543       --  Table of addresses of elaboration routines. Used for
22544       --  zero cost exception handling to make sure these
22545       --  addresses are included in the top level procedure
22546       --  address table.
22547
22548       EA : aliased constant array (1 .. 23) of System.Address := (
22549         adainit'Code_Address,
22550         Do_Finalize'Code_Address,
22551         Ada.Exceptions'Elab_Spec'Address,
22552         System.Exceptions'Elab_Spec'Address,
22553         Interfaces.C_Streams'Elab_Spec'Address,
22554         System.Exception_Table'Elab_Body'Address,
22555         Ada.Io_Exceptions'Elab_Spec'Address,
22556         System.Stack_Checking'Elab_Spec'Address,
22557         System.Soft_Links'Elab_Body'Address,
22558         System.Secondary_Stack'Elab_Body'Address,
22559         Ada.Tags'Elab_Spec'Address,
22560         Ada.Tags'Elab_Body'Address,
22561         Ada.Streams'Elab_Spec'Address,
22562         System.Finalization_Root'Elab_Spec'Address,
22563         Ada.Exceptions'Elab_Body'Address,
22564         System.Finalization_Implementation'Elab_Spec'Address,
22565         System.Finalization_Implementation'Elab_Body'Address,
22566         Ada.Finalization'Elab_Spec'Address,
22567         Ada.Finalization.List_Controller'Elab_Spec'Address,
22568         System.File_Control_Block'Elab_Spec'Address,
22569         System.File_Io'Elab_Body'Address,
22570         Ada.Text_Io'Elab_Spec'Address,
22571         Ada.Text_Io'Elab_Body'Address);
22572
22573    --  Start of processing for adainit
22574
22575    begin
22576
22577       --  Call SDP_Table_Build to build the top level procedure
22578       --  table for zero cost exception handling (omitted in
22579       --  longjmp/setjump mode).
22580
22581       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22582
22583       --  Call Set_Globals to record various information for
22584       --  this partition.  The values are derived by the binder
22585       --  from information stored in the ali files by the compiler.
22586
22587 @findex __gnat_set_globals
22588       Set_Globals
22589         (Main_Priority            => -1,
22590          --  Priority of main program, -1 if no pragma Priority used
22591
22592          Time_Slice_Value         => -1,
22593          --  Time slice from Time_Slice pragma, -1 if none used
22594
22595          WC_Encoding              => 'b',
22596          --  Wide_Character encoding used, default is brackets
22597
22598          Locking_Policy           => ' ',
22599          --  Locking_Policy used, default of space means not
22600          --  specified, otherwise it is the first character of
22601          --  the policy name.
22602
22603          Queuing_Policy           => ' ',
22604          --  Queuing_Policy used, default of space means not
22605          --  specified, otherwise it is the first character of
22606          --  the policy name.
22607
22608          Task_Dispatching_Policy  => ' ',
22609          --  Task_Dispatching_Policy used, default of space means
22610          --  not specified, otherwise first character of the
22611          --  policy name.
22612
22613          Adafinal                 => System.Null_Address,
22614          --  Address of Adafinal routine, not used anymore
22615
22616          Unreserve_All_Interrupts => 0,
22617          --  Set true if pragma Unreserve_All_Interrupts was used
22618
22619          Exception_Tracebacks     => 0);
22620          --  Indicates if exception tracebacks are enabled
22621
22622       Elab_Final_Code := 1;
22623
22624       --  Now we have the elaboration calls for all units in the partition.
22625       --  The Elab_Spec and Elab_Body attributes generate references to the
22626       --  implicit elaboration procedures generated by the compiler for
22627       --  each unit that requires elaboration.
22628
22629       if not E040 then
22630          Interfaces.C_Streams'Elab_Spec;
22631       end if;
22632       E040 := True;
22633       if not E008 then
22634          Ada.Exceptions'Elab_Spec;
22635       end if;
22636       if not E014 then
22637          System.Exception_Table'Elab_Body;
22638          E014 := True;
22639       end if;
22640       if not E053 then
22641          Ada.Io_Exceptions'Elab_Spec;
22642          E053 := True;
22643       end if;
22644       if not E017 then
22645          System.Exceptions'Elab_Spec;
22646          E017 := True;
22647       end if;
22648       if not E030 then
22649          System.Stack_Checking'Elab_Spec;
22650       end if;
22651       if not E028 then
22652          System.Soft_Links'Elab_Body;
22653          E028 := True;
22654       end if;
22655       E030 := True;
22656       if not E024 then
22657          System.Secondary_Stack'Elab_Body;
22658          E024 := True;
22659       end if;
22660       if not E035 then
22661          Ada.Tags'Elab_Spec;
22662       end if;
22663       if not E035 then
22664          Ada.Tags'Elab_Body;
22665          E035 := True;
22666       end if;
22667       if not E033 then
22668          Ada.Streams'Elab_Spec;
22669          E033 := True;
22670       end if;
22671       if not E046 then
22672          System.Finalization_Root'Elab_Spec;
22673       end if;
22674       E046 := True;
22675       if not E008 then
22676          Ada.Exceptions'Elab_Body;
22677          E008 := True;
22678       end if;
22679       if not E048 then
22680          System.Finalization_Implementation'Elab_Spec;
22681       end if;
22682       if not E048 then
22683          System.Finalization_Implementation'Elab_Body;
22684          E048 := True;
22685       end if;
22686       if not E044 then
22687          Ada.Finalization'Elab_Spec;
22688       end if;
22689       E044 := True;
22690       if not E057 then
22691          Ada.Finalization.List_Controller'Elab_Spec;
22692       end if;
22693       E057 := True;
22694       if not E055 then
22695          System.File_Control_Block'Elab_Spec;
22696          E055 := True;
22697       end if;
22698       if not E042 then
22699          System.File_Io'Elab_Body;
22700          E042 := True;
22701       end if;
22702       if not E006 then
22703          Ada.Text_Io'Elab_Spec;
22704       end if;
22705       if not E006 then
22706          Ada.Text_Io'Elab_Body;
22707          E006 := True;
22708       end if;
22709
22710       Elab_Final_Code := 0;
22711    end adainit;
22712
22713    --------------
22714    -- adafinal --
22715    --------------
22716
22717 @findex adafinal
22718    procedure adafinal is
22719    begin
22720       Do_Finalize;
22721    end adafinal;
22722
22723    ----------
22724    -- main --
22725    ----------
22726
22727    --  main is actually a function, as in the ANSI C standard,
22728    --  defined to return the exit status. The three parameters
22729    --  are the argument count, argument values and environment
22730    --  pointer.
22731
22732 @findex Main Program
22733    function main
22734      (argc : Integer;
22735       argv : System.Address;
22736       envp : System.Address)
22737       return Integer
22738    is
22739       --  The initialize routine performs low level system
22740       --  initialization using a standard library routine which
22741       --  sets up signal handling and performs any other
22742       --  required setup. The routine can be found in file
22743       --  a-init.c.
22744
22745 @findex __gnat_initialize
22746       procedure initialize;
22747       pragma Import (C, initialize, "__gnat_initialize");
22748
22749       --  The finalize routine performs low level system
22750       --  finalization using a standard library routine. The
22751       --  routine is found in file a-final.c and in the standard
22752       --  distribution is a dummy routine that does nothing, so
22753       --  really this is a hook for special user finalization.
22754
22755 @findex __gnat_finalize
22756       procedure finalize;
22757       pragma Import (C, finalize, "__gnat_finalize");
22758
22759       --  We get to the main program of the partition by using
22760       --  pragma Import because if we try to with the unit and
22761       --  call it Ada style, then not only do we waste time
22762       --  recompiling it, but also, we don't really know the right
22763       --  switches (e.g. identifier character set) to be used
22764       --  to compile it.
22765
22766       procedure Ada_Main_Program;
22767       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22768
22769    --  Start of processing for main
22770
22771    begin
22772       --  Save global variables
22773
22774       gnat_argc := argc;
22775       gnat_argv := argv;
22776       gnat_envp := envp;
22777
22778       --  Call low level system initialization
22779
22780       Initialize;
22781
22782       --  Call our generated Ada initialization routine
22783
22784       adainit;
22785
22786       --  This is the point at which we want the debugger to get
22787       --  control
22788
22789       Break_Start;
22790
22791       --  Now we call the main program of the partition
22792
22793       Ada_Main_Program;
22794
22795       --  Perform Ada finalization
22796
22797       adafinal;
22798
22799       --  Perform low level system finalization
22800
22801       Finalize;
22802
22803       --  Return the proper exit status
22804       return (gnat_exit_status);
22805    end;
22806
22807 --  This section is entirely comments, so it has no effect on the
22808 --  compilation of the Ada_Main package. It provides the list of
22809 --  object files and linker options, as well as some standard
22810 --  libraries needed for the link. The gnatlink utility parses
22811 --  this b~hello.adb file to read these comment lines to generate
22812 --  the appropriate command line arguments for the call to the
22813 --  system linker. The BEGIN/END lines are used for sentinels for
22814 --  this parsing operation.
22815
22816 --  The exact file names will of course depend on the environment,
22817 --  host/target and location of files on the host system.
22818
22819 @findex Object file list
22820 -- BEGIN Object file/option list
22821    --   ./hello.o
22822    --   -L./
22823    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22824    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22825 -- END Object file/option list
22826
22827 end ada_main;
22828 @end smallexample
22829
22830 @noindent
22831 The Ada code in the above example is exactly what is generated by the
22832 binder. We have added comments to more clearly indicate the function
22833 of each part of the generated @code{Ada_Main} package.
22834
22835 The code is standard Ada in all respects, and can be processed by any
22836 tools that handle Ada. In particular, it is possible to use the debugger
22837 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22838 suppose that for reasons that you do not understand, your program is crashing
22839 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22840 you can place a breakpoint on the call:
22841
22842 @smallexample @c ada
22843 Ada.Text_Io'Elab_Body;
22844 @end smallexample
22845
22846 @noindent
22847 and trace the elaboration routine for this package to find out where
22848 the problem might be (more usually of course you would be debugging
22849 elaboration code in your own application).
22850
22851 @node Elaboration Order Handling in GNAT
22852 @appendix Elaboration Order Handling in GNAT
22853 @cindex Order of elaboration
22854 @cindex Elaboration control
22855
22856 @menu
22857 * Elaboration Code in Ada 95::
22858 * Checking the Elaboration Order in Ada 95::
22859 * Controlling the Elaboration Order in Ada 95::
22860 * Controlling Elaboration in GNAT - Internal Calls::
22861 * Controlling Elaboration in GNAT - External Calls::
22862 * Default Behavior in GNAT - Ensuring Safety::
22863 * Treatment of Pragma Elaborate::
22864 * Elaboration Issues for Library Tasks::
22865 * Mixing Elaboration Models::
22866 * What to Do If the Default Elaboration Behavior Fails::
22867 * Elaboration for Access-to-Subprogram Values::
22868 * Summary of Procedures for Elaboration Control::
22869 * Other Elaboration Order Considerations::
22870 @end menu
22871
22872 @noindent
22873 This chapter describes the handling of elaboration code in Ada 95 and
22874 in GNAT, and discusses how the order of elaboration of program units can
22875 be controlled in GNAT, either automatically or with explicit programming
22876 features.
22877
22878 @node Elaboration Code in Ada 95
22879 @section Elaboration Code in Ada 95
22880
22881 @noindent
22882 Ada 95 provides rather general mechanisms for executing code at elaboration
22883 time, that is to say before the main program starts executing. Such code arises
22884 in three contexts:
22885
22886 @table @asis
22887 @item Initializers for variables.
22888 Variables declared at the library level, in package specs or bodies, can
22889 require initialization that is performed at elaboration time, as in:
22890 @smallexample @c ada
22891 @cartouche
22892 Sqrt_Half : Float := Sqrt (0.5);
22893 @end cartouche
22894 @end smallexample
22895
22896 @item Package initialization code
22897 Code in a @code{BEGIN-END} section at the outer level of a package body is
22898 executed as part of the package body elaboration code.
22899
22900 @item Library level task allocators
22901 Tasks that are declared using task allocators at the library level
22902 start executing immediately and hence can execute at elaboration time.
22903 @end table
22904
22905 @noindent
22906 Subprogram calls are possible in any of these contexts, which means that
22907 any arbitrary part of the program may be executed as part of the elaboration
22908 code. It is even possible to write a program which does all its work at
22909 elaboration time, with a null main program, although stylistically this
22910 would usually be considered an inappropriate way to structure
22911 a program.
22912
22913 An important concern arises in the context of elaboration code:
22914 we have to be sure that it is executed in an appropriate order. What we
22915 have is a series of elaboration code sections, potentially one section
22916 for each unit in the program. It is important that these execute
22917 in the correct order. Correctness here means that, taking the above
22918 example of the declaration of @code{Sqrt_Half},
22919 if some other piece of
22920 elaboration code references @code{Sqrt_Half},
22921 then it must run after the
22922 section of elaboration code that contains the declaration of
22923 @code{Sqrt_Half}.
22924
22925 There would never be any order of elaboration problem if we made a rule
22926 that whenever you @code{with} a unit, you must elaborate both the spec and body
22927 of that unit before elaborating the unit doing the @code{with}'ing:
22928
22929 @smallexample @c ada
22930 @group
22931 @cartouche
22932 with Unit_1;
22933 package Unit_2 is ...
22934 @end cartouche
22935 @end group
22936 @end smallexample
22937
22938 @noindent
22939 would require that both the body and spec of @code{Unit_1} be elaborated
22940 before the spec of @code{Unit_2}. However, a rule like that would be far too
22941 restrictive. In particular, it would make it impossible to have routines
22942 in separate packages that were mutually recursive.
22943
22944 You might think that a clever enough compiler could look at the actual
22945 elaboration code and determine an appropriate correct order of elaboration,
22946 but in the general case, this is not possible. Consider the following
22947 example.
22948
22949 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22950 that references
22951 the variable @code{Sqrt_1}, which is declared in the elaboration code
22952 of the body of @code{Unit_1}:
22953
22954 @smallexample @c ada
22955 @cartouche
22956 Sqrt_1 : Float := Sqrt (0.1);
22957 @end cartouche
22958 @end smallexample
22959
22960 @noindent
22961 The elaboration code of the body of @code{Unit_1} also contains:
22962
22963 @smallexample @c ada
22964 @group
22965 @cartouche
22966 if expression_1 = 1 then
22967    Q := Unit_2.Func_2;
22968 end if;
22969 @end cartouche
22970 @end group
22971 @end smallexample
22972
22973 @noindent
22974 @code{Unit_2} is exactly parallel,
22975 it has a procedure @code{Func_2} that references
22976 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22977 the body @code{Unit_2}:
22978
22979 @smallexample @c ada
22980 @cartouche
22981 Sqrt_2 : Float := Sqrt (0.1);
22982 @end cartouche
22983 @end smallexample
22984
22985 @noindent
22986 The elaboration code of the body of @code{Unit_2} also contains:
22987
22988 @smallexample @c ada
22989 @group
22990 @cartouche
22991 if expression_2 = 2 then
22992    Q := Unit_1.Func_1;
22993 end if;
22994 @end cartouche
22995 @end group
22996 @end smallexample
22997
22998 @noindent
22999 Now the question is, which of the following orders of elaboration is
23000 acceptable:
23001
23002 @smallexample
23003 @group
23004 Spec of Unit_1
23005 Spec of Unit_2
23006 Body of Unit_1
23007 Body of Unit_2
23008 @end group
23009 @end smallexample
23010
23011 @noindent
23012 or
23013
23014 @smallexample
23015 @group
23016 Spec of Unit_2
23017 Spec of Unit_1
23018 Body of Unit_2
23019 Body of Unit_1
23020 @end group
23021 @end smallexample
23022
23023 @noindent
23024 If you carefully analyze the flow here, you will see that you cannot tell
23025 at compile time the answer to this question.
23026 If @code{expression_1} is not equal to 1,
23027 and @code{expression_2} is not equal to 2,
23028 then either order is acceptable, because neither of the function calls is
23029 executed. If both tests evaluate to true, then neither order is acceptable
23030 and in fact there is no correct order.
23031
23032 If one of the two expressions is true, and the other is false, then one
23033 of the above orders is correct, and the other is incorrect. For example,
23034 if @code{expression_1} = 1 and @code{expression_2} /= 2,
23035 then the call to @code{Func_2}
23036 will occur, but not the call to @code{Func_1.}
23037 This means that it is essential
23038 to elaborate the body of @code{Unit_1} before
23039 the body of @code{Unit_2}, so the first
23040 order of elaboration is correct and the second is wrong.
23041
23042 By making @code{expression_1} and @code{expression_2}
23043 depend on input data, or perhaps
23044 the time of day, we can make it impossible for the compiler or binder
23045 to figure out which of these expressions will be true, and hence it
23046 is impossible to guarantee a safe order of elaboration at run time.
23047
23048 @node Checking the Elaboration Order in Ada 95
23049 @section Checking the Elaboration Order in Ada 95
23050
23051 @noindent
23052 In some languages that involve the same kind of elaboration problems,
23053 e.g. Java and C++, the programmer is expected to worry about these
23054 ordering problems himself, and it is common to
23055 write a program in which an incorrect elaboration order  gives
23056 surprising results, because it references variables before they
23057 are initialized.
23058 Ada 95 is designed to be a safe language, and a programmer-beware approach is
23059 clearly not sufficient. Consequently, the language provides three lines
23060 of defense:
23061
23062 @table @asis
23063 @item Standard rules
23064 Some standard rules restrict the possible choice of elaboration
23065 order. In particular, if you @code{with} a unit, then its spec is always
23066 elaborated before the unit doing the @code{with}. Similarly, a parent
23067 spec is always elaborated before the child spec, and finally
23068 a spec is always elaborated before its corresponding body.
23069
23070 @item Dynamic elaboration checks
23071 @cindex Elaboration checks
23072 @cindex Checks, elaboration
23073 Dynamic checks are made at run time, so that if some entity is accessed
23074 before it is elaborated (typically  by means of a subprogram call)
23075 then the exception (@code{Program_Error}) is raised.
23076
23077 @item Elaboration control
23078 Facilities are provided for the programmer to specify the desired order
23079 of elaboration.
23080 @end table
23081
23082 Let's look at these facilities in more detail. First, the rules for
23083 dynamic checking. One possible rule would be simply to say that the
23084 exception is raised if you access a variable which has not yet been
23085 elaborated. The trouble with this approach is that it could require
23086 expensive checks on every variable reference. Instead Ada 95 has two
23087 rules which are a little more restrictive, but easier to check, and
23088 easier to state:
23089
23090 @table @asis
23091 @item Restrictions on calls
23092 A subprogram can only be called at elaboration time if its body
23093 has been elaborated. The rules for elaboration given above guarantee
23094 that the spec of the subprogram has been elaborated before the
23095 call, but not the body. If this rule is violated, then the
23096 exception @code{Program_Error} is raised.
23097
23098 @item Restrictions on instantiations
23099 A generic unit can only be instantiated if the body of the generic
23100 unit has been elaborated. Again, the rules for elaboration given above
23101 guarantee that the spec of the generic unit has been elaborated
23102 before the instantiation, but not the body. If this rule is
23103 violated, then the exception @code{Program_Error} is raised.
23104 @end table
23105
23106 @noindent
23107 The idea is that if the body has been elaborated, then any variables
23108 it references must have been elaborated; by checking for the body being
23109 elaborated we guarantee that none of its references causes any
23110 trouble. As we noted above, this is a little too restrictive, because a
23111 subprogram that has no non-local references in its body may in fact be safe
23112 to call. However, it really would be unsafe to rely on this, because
23113 it would mean that the caller was aware of details of the implementation
23114 in the body. This goes against the basic tenets of Ada.
23115
23116 A plausible implementation can be described as follows.
23117 A Boolean variable is associated with each subprogram
23118 and each generic unit. This variable is initialized to False, and is set to
23119 True at the point body is elaborated. Every call or instantiation checks the
23120 variable, and raises @code{Program_Error} if the variable is False.
23121
23122 Note that one might think that it would be good enough to have one Boolean
23123 variable for each package, but that would not deal with cases of trying
23124 to call a body in the same package as the call
23125 that has not been elaborated yet.
23126 Of course a compiler may be able to do enough analysis to optimize away
23127 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23128 does such optimizations, but still the easiest conceptual model is to
23129 think of there being one variable per subprogram.
23130
23131 @node Controlling the Elaboration Order in Ada 95
23132 @section Controlling the Elaboration Order in Ada 95
23133
23134 @noindent
23135 In the previous section we discussed the rules in Ada 95 which ensure
23136 that @code{Program_Error} is raised if an incorrect elaboration order is
23137 chosen. This prevents erroneous executions, but we need mechanisms to
23138 specify a correct execution and avoid the exception altogether.
23139 To achieve this, Ada 95 provides a number of features for controlling
23140 the order of elaboration. We discuss these features in this section.
23141
23142 First, there are several ways of indicating to the compiler that a given
23143 unit has no elaboration problems:
23144
23145 @table @asis
23146 @item packages that do not require a body
23147 In Ada 95, a library package that does not require a body does not permit
23148 a body. This means that if we have a such a package, as in:
23149
23150 @smallexample @c ada
23151 @group
23152 @cartouche
23153 package Definitions is
23154    generic
23155       type m is new integer;
23156    package Subp is
23157       type a is array (1 .. 10) of m;
23158       type b is array (1 .. 20) of m;
23159    end Subp;
23160 end Definitions;
23161 @end cartouche
23162 @end group
23163 @end smallexample
23164
23165 @noindent
23166 A package that @code{with}'s @code{Definitions} may safely instantiate
23167 @code{Definitions.Subp} because the compiler can determine that there
23168 definitely is no package body to worry about in this case
23169
23170 @item pragma Pure
23171 @cindex pragma Pure
23172 @findex Pure
23173 Places sufficient restrictions on a unit to guarantee that
23174 no call to any subprogram in the unit can result in an
23175 elaboration problem. This means that the compiler does not need
23176 to worry about the point of elaboration of such units, and in
23177 particular, does not need to check any calls to any subprograms
23178 in this unit.
23179
23180 @item pragma Preelaborate
23181 @findex Preelaborate
23182 @cindex pragma Preelaborate
23183 This pragma places slightly less stringent restrictions on a unit than
23184 does pragma Pure,
23185 but these restrictions are still sufficient to ensure that there
23186 are no elaboration problems with any calls to the unit.
23187
23188 @item pragma Elaborate_Body
23189 @findex Elaborate_Body
23190 @cindex pragma Elaborate_Body
23191 This pragma requires that the body of a unit be elaborated immediately
23192 after its spec. Suppose a unit @code{A} has such a pragma,
23193 and unit @code{B} does
23194 a @code{with} of unit @code{A}. Recall that the standard rules require
23195 the spec of unit @code{A}
23196 to be elaborated before the @code{with}'ing unit; given the pragma in
23197 @code{A}, we also know that the body of @code{A}
23198 will be elaborated before @code{B}, so
23199 that calls to @code{A} are safe and do not need a check.
23200 @end table
23201
23202 @noindent
23203 Note that,
23204 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23205 the use of
23206 @code{Elaborate_Body} does not guarantee that the program is
23207 free of elaboration problems, because it may not be possible
23208 to satisfy the requested elaboration order.
23209 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23210 If a programmer
23211 marks @code{Unit_1} as @code{Elaborate_Body},
23212 and not @code{Unit_2,} then the order of
23213 elaboration will be:
23214
23215 @smallexample
23216 @group
23217 Spec of Unit_2
23218 Spec of Unit_1
23219 Body of Unit_1
23220 Body of Unit_2
23221 @end group
23222 @end smallexample
23223
23224 @noindent
23225 Now that means that the call to @code{Func_1} in @code{Unit_2}
23226 need not be checked,
23227 it must be safe. But the call to @code{Func_2} in
23228 @code{Unit_1} may still fail if
23229 @code{Expression_1} is equal to 1,
23230 and the programmer must still take
23231 responsibility for this not being the case.
23232
23233 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23234 eliminated, except for calls entirely within a body, which are
23235 in any case fully under programmer control. However, using the pragma
23236 everywhere is not always possible.
23237 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23238 we marked both of them as having pragma @code{Elaborate_Body}, then
23239 clearly there would be no possible elaboration order.
23240
23241 The above pragmas allow a server to guarantee safe use by clients, and
23242 clearly this is the preferable approach. Consequently a good rule in
23243 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23244 and if this is not possible,
23245 mark them as @code{Elaborate_Body} if possible.
23246 As we have seen, there are situations where neither of these
23247 three pragmas can be used.
23248 So we also provide methods for clients to control the
23249 order of elaboration of the servers on which they depend:
23250
23251 @table @asis
23252 @item pragma Elaborate (unit)
23253 @findex Elaborate
23254 @cindex pragma Elaborate
23255 This pragma is placed in the context clause, after a @code{with} clause,
23256 and it requires that the body of the named unit be elaborated before
23257 the unit in which the pragma occurs. The idea is to use this pragma
23258 if the current unit calls at elaboration time, directly or indirectly,
23259 some subprogram in the named unit.
23260
23261 @item pragma Elaborate_All (unit)
23262 @findex Elaborate_All
23263 @cindex pragma Elaborate_All
23264 This is a stronger version of the Elaborate pragma. Consider the
23265 following example:
23266
23267 @smallexample
23268 Unit A @code{with}'s unit B and calls B.Func in elab code
23269 Unit B @code{with}'s unit C, and B.Func calls C.Func
23270 @end smallexample
23271
23272 @noindent
23273 Now if we put a pragma @code{Elaborate (B)}
23274 in unit @code{A}, this ensures that the
23275 body of @code{B} is elaborated before the call, but not the
23276 body of @code{C}, so
23277 the call to @code{C.Func} could still cause @code{Program_Error} to
23278 be raised.
23279
23280 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23281 not only that the body of the named unit be elaborated before the
23282 unit doing the @code{with}, but also the bodies of all units that the
23283 named unit uses, following @code{with} links transitively. For example,
23284 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23285 then it requires
23286 not only that the body of @code{B} be elaborated before @code{A},
23287 but also the
23288 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23289 @end table
23290
23291 @noindent
23292 We are now in a position to give a usage rule in Ada 95 for avoiding
23293 elaboration problems, at least if dynamic dispatching and access to
23294 subprogram values are not used. We will handle these cases separately
23295 later.
23296
23297 The rule is simple. If a unit has elaboration code that can directly or
23298 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23299 a generic unit in a @code{with}'ed unit,
23300 then if the @code{with}'ed unit does not have
23301 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23302 a pragma @code{Elaborate_All}
23303 for the @code{with}'ed unit. By following this rule a client is
23304 assured that calls can be made without risk of an exception.
23305 If this rule is not followed, then a program may be in one of four
23306 states:
23307
23308 @table @asis
23309 @item No order exists
23310 No order of elaboration exists which follows the rules, taking into
23311 account any @code{Elaborate}, @code{Elaborate_All},
23312 or @code{Elaborate_Body} pragmas. In
23313 this case, an Ada 95 compiler must diagnose the situation at bind
23314 time, and refuse to build an executable program.
23315
23316 @item One or more orders exist, all incorrect
23317 One or more acceptable elaboration orders exists, and all of them
23318 generate an elaboration order problem. In this case, the binder
23319 can build an executable program, but @code{Program_Error} will be raised
23320 when the program is run.
23321
23322 @item Several orders exist, some right, some incorrect
23323 One or more acceptable elaboration orders exists, and some of them
23324 work, and some do not. The programmer has not controlled
23325 the order of elaboration, so the binder may or may not pick one of
23326 the correct orders, and the program may or may not raise an
23327 exception when it is run. This is the worst case, because it means
23328 that the program may fail when moved to another compiler, or even
23329 another version of the same compiler.
23330
23331 @item One or more orders exists, all correct
23332 One ore more acceptable elaboration orders exist, and all of them
23333 work. In this case the program runs successfully. This state of
23334 affairs can be guaranteed by following the rule we gave above, but
23335 may be true even if the rule is not followed.
23336 @end table
23337
23338 @noindent
23339 Note that one additional advantage of following our Elaborate_All rule
23340 is that the program continues to stay in the ideal (all orders OK) state
23341 even if maintenance
23342 changes some bodies of some subprograms. Conversely, if a program that does
23343 not follow this rule happens to be safe at some point, this state of affairs
23344 may deteriorate silently as a result of maintenance changes.
23345
23346 You may have noticed that the above discussion did not mention
23347 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23348 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23349 code in the body makes calls to some other unit, so it is still necessary
23350 to use @code{Elaborate_All} on such units.
23351
23352 @node Controlling Elaboration in GNAT - Internal Calls
23353 @section Controlling Elaboration in GNAT - Internal Calls
23354
23355 @noindent
23356 In the case of internal calls, i.e. calls within a single package, the
23357 programmer has full control over the order of elaboration, and it is up
23358 to the programmer to elaborate declarations in an appropriate order. For
23359 example writing:
23360
23361 @smallexample @c ada
23362 @group
23363 @cartouche
23364 function One return Float;
23365
23366 Q : Float := One;
23367
23368 function One return Float is
23369 begin
23370      return 1.0;
23371 end One;
23372 @end cartouche
23373 @end group
23374 @end smallexample
23375
23376 @noindent
23377 will obviously raise @code{Program_Error} at run time, because function
23378 One will be called before its body is elaborated. In this case GNAT will
23379 generate a warning that the call will raise @code{Program_Error}:
23380
23381 @smallexample
23382 @group
23383 @cartouche
23384  1. procedure y is
23385  2.    function One return Float;
23386  3.
23387  4.    Q : Float := One;
23388                     |
23389     >>> warning: cannot call "One" before body is elaborated
23390     >>> warning: Program_Error will be raised at run time
23391
23392  5.
23393  6.    function One return Float is
23394  7.    begin
23395  8.         return 1.0;
23396  9.    end One;
23397 10.
23398 11. begin
23399 12.    null;
23400 13. end;
23401 @end cartouche
23402 @end group
23403 @end smallexample
23404
23405 @noindent
23406 Note that in this particular case, it is likely that the call is safe, because
23407 the function @code{One} does not access any global variables.
23408 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23409 the contents of the body (think about the separate compilation case), so this
23410 is still wrong, as we discussed in the previous sections.
23411
23412 The error is easily corrected by rearranging the declarations so that the
23413 body of One appears before the declaration containing the call
23414 (note that in Ada 95,
23415 declarations can appear in any order, so there is no restriction that
23416 would prevent this reordering, and if we write:
23417
23418 @smallexample @c ada
23419 @group
23420 @cartouche
23421 function One return Float;
23422
23423 function One return Float is
23424 begin
23425      return 1.0;
23426 end One;
23427
23428 Q : Float := One;
23429 @end cartouche
23430 @end group
23431 @end smallexample
23432
23433 @noindent
23434 then all is well, no warning is generated, and no
23435 @code{Program_Error} exception
23436 will be raised.
23437 Things are more complicated when a chain of subprograms is executed:
23438
23439 @smallexample @c ada
23440 @group
23441 @cartouche
23442 function A return Integer;
23443 function B return Integer;
23444 function C return Integer;
23445
23446 function B return Integer is begin return A; end;
23447 function C return Integer is begin return B; end;
23448
23449 X : Integer := C;
23450
23451 function A return Integer is begin return 1; end;
23452 @end cartouche
23453 @end group
23454 @end smallexample
23455
23456 @noindent
23457 Now the call to @code{C}
23458 at elaboration time in the declaration of @code{X} is correct, because
23459 the body of @code{C} is already elaborated,
23460 and the call to @code{B} within the body of
23461 @code{C} is correct, but the call
23462 to @code{A} within the body of @code{B} is incorrect, because the body
23463 of @code{A} has not been elaborated, so @code{Program_Error}
23464 will be raised on the call to @code{A}.
23465 In this case GNAT will generate a
23466 warning that @code{Program_Error} may be
23467 raised at the point of the call. Let's look at the warning:
23468
23469 @smallexample
23470 @group
23471 @cartouche
23472  1. procedure x is
23473  2.    function A return Integer;
23474  3.    function B return Integer;
23475  4.    function C return Integer;
23476  5.
23477  6.    function B return Integer is begin return A; end;
23478                                                     |
23479     >>> warning: call to "A" before body is elaborated may
23480                  raise Program_Error
23481     >>> warning: "B" called at line 7
23482     >>> warning: "C" called at line 9
23483
23484  7.    function C return Integer is begin return B; end;
23485  8.
23486  9.    X : Integer := C;
23487 10.
23488 11.    function A return Integer is begin return 1; end;
23489 12.
23490 13. begin
23491 14.    null;
23492 15. end;
23493 @end cartouche
23494 @end group
23495 @end smallexample
23496
23497 @noindent
23498 Note that the message here says ``may raise'', instead of the direct case,
23499 where the message says ``will be raised''. That's because whether
23500 @code{A} is
23501 actually called depends in general on run-time flow of control.
23502 For example, if the body of @code{B} said
23503
23504 @smallexample @c ada
23505 @group
23506 @cartouche
23507 function B return Integer is
23508 begin
23509    if some-condition-depending-on-input-data then
23510       return A;
23511    else
23512       return 1;
23513    end if;
23514 end B;
23515 @end cartouche
23516 @end group
23517 @end smallexample
23518
23519 @noindent
23520 then we could not know until run time whether the incorrect call to A would
23521 actually occur, so @code{Program_Error} might
23522 or might not be raised. It is possible for a compiler to
23523 do a better job of analyzing bodies, to
23524 determine whether or not @code{Program_Error}
23525 might be raised, but it certainly
23526 couldn't do a perfect job (that would require solving the halting problem
23527 and is provably impossible), and because this is a warning anyway, it does
23528 not seem worth the effort to do the analysis. Cases in which it
23529 would be relevant are rare.
23530
23531 In practice, warnings of either of the forms given
23532 above will usually correspond to
23533 real errors, and should be examined carefully and eliminated.
23534 In the rare case where a warning is bogus, it can be suppressed by any of
23535 the following methods:
23536
23537 @itemize @bullet
23538 @item
23539 Compile with the @option{-gnatws} switch set
23540
23541 @item
23542 Suppress @code{Elaboration_Check} for the called subprogram
23543
23544 @item
23545 Use pragma @code{Warnings_Off} to turn warnings off for the call
23546 @end itemize
23547
23548 @noindent
23549 For the internal elaboration check case,
23550 GNAT by default generates the
23551 necessary run-time checks to ensure
23552 that @code{Program_Error} is raised if any
23553 call fails an elaboration check. Of course this can only happen if a
23554 warning has been issued as described above. The use of pragma
23555 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23556 some of these checks, meaning that it may be possible (but is not
23557 guaranteed) for a program to be able to call a subprogram whose body
23558 is not yet elaborated, without raising a @code{Program_Error} exception.
23559
23560 @node Controlling Elaboration in GNAT - External Calls
23561 @section Controlling Elaboration in GNAT - External Calls
23562
23563 @noindent
23564 The previous section discussed the case in which the execution of a
23565 particular thread of elaboration code occurred entirely within a
23566 single unit. This is the easy case to handle, because a programmer
23567 has direct and total control over the order of elaboration, and
23568 furthermore, checks need only be generated in cases which are rare
23569 and which the compiler can easily detect.
23570 The situation is more complex when separate compilation is taken into account.
23571 Consider the following:
23572
23573 @smallexample @c ada
23574 @cartouche
23575 @group
23576 package Math is
23577    function Sqrt (Arg : Float) return Float;
23578 end Math;
23579
23580 package body Math is
23581    function Sqrt (Arg : Float) return Float is
23582    begin
23583          ...
23584    end Sqrt;
23585 end Math;
23586 @end group
23587 @group
23588 with Math;
23589 package Stuff is
23590    X : Float := Math.Sqrt (0.5);
23591 end Stuff;
23592
23593 with Stuff;
23594 procedure Main is
23595 begin
23596    ...
23597 end Main;
23598 @end group
23599 @end cartouche
23600 @end smallexample
23601
23602 @noindent
23603 where @code{Main} is the main program. When this program is executed, the
23604 elaboration code must first be executed, and one of the jobs of the
23605 binder is to determine the order in which the units of a program are
23606 to be elaborated. In this case we have four units: the spec and body
23607 of @code{Math},
23608 the spec of @code{Stuff} and the body of @code{Main}).
23609 In what order should the four separate sections of elaboration code
23610 be executed?
23611
23612 There are some restrictions in the order of elaboration that the binder
23613 can choose. In particular, if unit U has a @code{with}
23614 for a package @code{X}, then you
23615 are assured that the spec of @code{X}
23616 is elaborated before U , but you are
23617 not assured that the body of @code{X}
23618 is elaborated before U.
23619 This means that in the above case, the binder is allowed to choose the
23620 order:
23621
23622 @smallexample
23623 spec of Math
23624 spec of Stuff
23625 body of Math
23626 body of Main
23627 @end smallexample
23628
23629 @noindent
23630 but that's not good, because now the call to @code{Math.Sqrt}
23631 that happens during
23632 the elaboration of the @code{Stuff}
23633 spec happens before the body of @code{Math.Sqrt} is
23634 elaborated, and hence causes @code{Program_Error} exception to be raised.
23635 At first glance, one might say that the binder is misbehaving, because
23636 obviously you want to elaborate the body of something you @code{with}
23637 first, but
23638 that is not a general rule that can be followed in all cases. Consider
23639
23640 @smallexample @c ada
23641 @group
23642 @cartouche
23643 package X is ...
23644
23645 package Y is ...
23646
23647 with X;
23648 package body Y is ...
23649
23650 with Y;
23651 package body X is ...
23652 @end cartouche
23653 @end group
23654 @end smallexample
23655
23656 @noindent
23657 This is a common arrangement, and, apart from the order of elaboration
23658 problems that might arise in connection with elaboration code, this works fine.
23659 A rule that says that you must first elaborate the body of anything you
23660 @code{with} cannot work in this case:
23661 the body of @code{X} @code{with}'s @code{Y},
23662 which means you would have to
23663 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23664 which means
23665 you have to elaborate the body of @code{X} first, but ... and we have a
23666 loop that cannot be broken.
23667
23668 It is true that the binder can in many cases guess an order of elaboration
23669 that is unlikely to cause a @code{Program_Error}
23670 exception to be raised, and it tries to do so (in the
23671 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23672 by default
23673 elaborate the body of @code{Math} right after its spec, so all will be well).
23674
23675 However, a program that blindly relies on the binder to be helpful can
23676 get into trouble, as we discussed in the previous sections, so
23677 GNAT
23678 provides a number of facilities for assisting the programmer in
23679 developing programs that are robust with respect to elaboration order.
23680
23681 @node Default Behavior in GNAT - Ensuring Safety
23682 @section Default Behavior in GNAT - Ensuring Safety
23683
23684 @noindent
23685 The default behavior in GNAT ensures elaboration safety. In its
23686 default mode GNAT implements the
23687 rule we previously described as the right approach. Let's restate it:
23688
23689 @itemize
23690 @item
23691 @emph{If a unit has elaboration code that can directly or indirectly make a
23692 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
23693 in a @code{with}'ed unit, then if the @code{with}'ed unit
23694 does not have pragma @code{Pure} or
23695 @code{Preelaborate}, then the client should have an
23696 @code{Elaborate_All} for the @code{with}'ed unit.}
23697 @end itemize
23698
23699 @noindent
23700 By following this rule a client is assured that calls and instantiations
23701 can be made without risk of an exception.
23702
23703 In this mode GNAT traces all calls that are potentially made from
23704 elaboration code, and puts in any missing implicit @code{Elaborate_All}
23705 pragmas.
23706 The advantage of this approach is that no elaboration problems
23707 are possible if the binder can find an elaboration order that is
23708 consistent with these implicit @code{Elaborate_All} pragmas. The
23709 disadvantage of this approach is that no such order may exist.
23710
23711 If the binder does not generate any diagnostics, then it means that it
23712 has found an elaboration order that is guaranteed to be safe. However,
23713 the binder may still be relying on implicitly generated
23714 @code{Elaborate_All} pragmas so portability to other compilers than
23715 GNAT is not guaranteed.
23716
23717 If it is important to guarantee portability, then the compilations should
23718 use the
23719 @option{-gnatwl}
23720 (warn on elaboration problems) switch. This will cause warning messages
23721 to be generated indicating the missing @code{Elaborate_All} pragmas.
23722 Consider the following source program:
23723
23724 @smallexample @c ada
23725 @group
23726 @cartouche
23727 with k;
23728 package j is
23729   m : integer := k.r;
23730 end;
23731 @end cartouche
23732 @end group
23733 @end smallexample
23734
23735 @noindent
23736 where it is clear that there
23737 should be a pragma @code{Elaborate_All}
23738 for unit @code{k}. An implicit pragma will be generated, and it is
23739 likely that the binder will be able to honor it. However, if you want
23740 to port this program to some other Ada compiler than GNAT.
23741 it is safer to include the pragma explicitly in the source. If this
23742 unit is compiled with the
23743 @option{-gnatwl}
23744 switch, then the compiler outputs a warning:
23745
23746 @smallexample
23747 @group
23748 @cartouche
23749 1. with k;
23750 2. package j is
23751 3.   m : integer := k.r;
23752                      |
23753    >>> warning: call to "r" may raise Program_Error
23754    >>> warning: missing pragma Elaborate_All for "k"
23755
23756 4. end;
23757 @end cartouche
23758 @end group
23759 @end smallexample
23760
23761 @noindent
23762 and these warnings can be used as a guide for supplying manually
23763 the missing pragmas. It is usually a bad idea to use this warning
23764 option during development. That's because it will warn you when
23765 you need to put in a pragma, but cannot warn you when it is time
23766 to take it out. So the use of pragma Elaborate_All may lead to
23767 unnecessary dependencies and even false circularities.
23768
23769 This default mode is more restrictive than the Ada Reference
23770 Manual, and it is possible to construct programs which will compile
23771 using the dynamic model described there, but will run into a
23772 circularity using the safer static model we have described.
23773
23774 Of course any Ada compiler must be able to operate in a mode
23775 consistent with the requirements of the Ada Reference Manual,
23776 and in particular must have the capability of implementing the
23777 standard dynamic model of elaboration with run-time checks.
23778
23779 In GNAT, this standard mode can be achieved either by the use of
23780 the @option{-gnatE} switch on the compiler (@command{gcc} or
23781 @command{gnatmake}) command, or by the use of the configuration pragma:
23782
23783 @smallexample @c ada
23784 pragma Elaboration_Checks (RM);
23785 @end smallexample
23786
23787 @noindent
23788 Either approach will cause the unit affected to be compiled using the
23789 standard dynamic run-time elaboration checks described in the Ada
23790 Reference Manual. The static model is generally preferable, since it
23791 is clearly safer to rely on compile and link time checks rather than
23792 run-time checks. However, in the case of legacy code, it may be
23793 difficult to meet the requirements of the static model. This
23794 issue is further discussed in
23795 @ref{What to Do If the Default Elaboration Behavior Fails}.
23796
23797 Note that the static model provides a strict subset of the allowed
23798 behavior and programs of the Ada Reference Manual, so if you do
23799 adhere to the static model and no circularities exist,
23800 then you are assured that your program will
23801 work using the dynamic model, providing that you remove any
23802 pragma Elaborate statements from the source.
23803
23804 @node Treatment of Pragma Elaborate
23805 @section Treatment of Pragma Elaborate
23806 @cindex Pragma Elaborate
23807
23808 @noindent
23809 The use of @code{pragma Elaborate}
23810 should generally be avoided in Ada 95 programs.
23811 The reason for this is that there is no guarantee that transitive calls
23812 will be properly handled. Indeed at one point, this pragma was placed
23813 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23814
23815 Now that's a bit restrictive. In practice, the case in which
23816 @code{pragma Elaborate} is useful is when the caller knows that there
23817 are no transitive calls, or that the called unit contains all necessary
23818 transitive @code{pragma Elaborate} statements, and legacy code often
23819 contains such uses.
23820
23821 Strictly speaking the static mode in GNAT should ignore such pragmas,
23822 since there is no assurance at compile time that the necessary safety
23823 conditions are met. In practice, this would cause GNAT to be incompatible
23824 with correctly written Ada 83 code that had all necessary
23825 @code{pragma Elaborate} statements in place. Consequently, we made the
23826 decision that GNAT in its default mode will believe that if it encounters
23827 a @code{pragma Elaborate} then the programmer knows what they are doing,
23828 and it will trust that no elaboration errors can occur.
23829
23830 The result of this decision is two-fold. First to be safe using the
23831 static mode, you should remove all @code{pragma Elaborate} statements.
23832 Second, when fixing circularities in existing code, you can selectively
23833 use @code{pragma Elaborate} statements to convince the static mode of
23834 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23835 statement.
23836
23837 When using the static mode with @option{-gnatwl}, any use of
23838 @code{pragma Elaborate} will generate a warning about possible
23839 problems.
23840
23841 @node Elaboration Issues for Library Tasks
23842 @section Elaboration Issues for Library Tasks
23843 @cindex Library tasks, elaboration issues
23844 @cindex Elaboration of library tasks
23845
23846 @noindent
23847 In this section we examine special elaboration issues that arise for
23848 programs that declare library level tasks.
23849
23850 Generally the model of execution of an Ada program is that all units are
23851 elaborated, and then execution of the program starts. However, the
23852 declaration of library tasks definitely does not fit this model. The
23853 reason for this is that library tasks start as soon as they are declared
23854 (more precisely, as soon as the statement part of the enclosing package
23855 body is reached), that is to say before elaboration
23856 of the program is complete. This means that if such a task calls a
23857 subprogram, or an entry in another task, the callee may or may not be
23858 elaborated yet, and in the standard
23859 Reference Manual model of dynamic elaboration checks, you can even
23860 get timing dependent Program_Error exceptions, since there can be
23861 a race between the elaboration code and the task code.
23862
23863 The static model of elaboration in GNAT seeks to avoid all such
23864 dynamic behavior, by being conservative, and the conservative
23865 approach in this particular case is to assume that all the code
23866 in a task body is potentially executed at elaboration time if
23867 a task is declared at the library level.
23868
23869 This can definitely result in unexpected circularities. Consider
23870 the following example
23871
23872 @smallexample @c ada
23873 package Decls is
23874   task Lib_Task is
23875      entry Start;
23876   end Lib_Task;
23877
23878   type My_Int is new Integer;
23879
23880   function Ident (M : My_Int) return My_Int;
23881 end Decls;
23882
23883 with Utils;
23884 package body Decls is
23885   task body Lib_Task is
23886   begin
23887      accept Start;
23888      Utils.Put_Val (2);
23889   end Lib_Task;
23890
23891   function Ident (M : My_Int) return My_Int is
23892   begin
23893      return M;
23894   end Ident;
23895 end Decls;
23896
23897 with Decls;
23898 package Utils is
23899   procedure Put_Val (Arg : Decls.My_Int);
23900 end Utils;
23901
23902 with Text_IO;
23903 package body Utils is
23904   procedure Put_Val (Arg : Decls.My_Int) is
23905   begin
23906      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23907   end Put_Val;
23908 end Utils;
23909
23910 with Decls;
23911 procedure Main is
23912 begin
23913    Decls.Lib_Task.Start;
23914 end;
23915 @end smallexample
23916
23917 @noindent
23918 If the above example is compiled in the default static elaboration
23919 mode, then a circularity occurs. The circularity comes from the call
23920 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23921 this call occurs in elaboration code, we need an implicit pragma
23922 @code{Elaborate_All} for @code{Utils}. This means that not only must
23923 the spec and body of @code{Utils} be elaborated before the body
23924 of @code{Decls}, but also the spec and body of any unit that is
23925 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23926 the body of @code{Decls}. This is the transitive implication of
23927 pragma @code{Elaborate_All} and it makes sense, because in general
23928 the body of @code{Put_Val} might have a call to something in a
23929 @code{with'ed} unit.
23930
23931 In this case, the body of Utils (actually its spec) @code{with's}
23932 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23933 must be elaborated before itself, in case there is a call from the
23934 body of @code{Utils}.
23935
23936 Here is the exact chain of events we are worrying about:
23937
23938 @enumerate
23939 @item
23940 In the body of @code{Decls} a call is made from within the body of a library
23941 task to a subprogram in the package @code{Utils}. Since this call may
23942 occur at elaboration time (given that the task is activated at elaboration
23943 time), we have to assume the worst, i.e. that the
23944 call does happen at elaboration time.
23945
23946 @item
23947 This means that the body and spec of @code{Util} must be elaborated before
23948 the body of @code{Decls} so that this call does not cause an access before
23949 elaboration.
23950
23951 @item
23952 Within the body of @code{Util}, specifically within the body of
23953 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23954 by this package.
23955
23956 @item
23957 One such @code{with}'ed package is package @code{Decls}, so there
23958 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23959 In fact there is such a call in this example, but we would have to
23960 assume that there was such a call even if it were not there, since
23961 we are not supposed to write the body of @code{Decls} knowing what
23962 is in the body of @code{Utils}; certainly in the case of the
23963 static elaboration model, the compiler does not know what is in
23964 other bodies and must assume the worst.
23965
23966 @item
23967 This means that the spec and body of @code{Decls} must also be
23968 elaborated before we elaborate the unit containing the call, but
23969 that unit is @code{Decls}! This means that the body of @code{Decls}
23970 must be elaborated before itself, and that's a circularity.
23971 @end enumerate
23972
23973 @noindent
23974 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23975 the body of @code{Decls} you will get a true Ada Reference Manual
23976 circularity that makes the program illegal.
23977
23978 In practice, we have found that problems with the static model of
23979 elaboration in existing code often arise from library tasks, so
23980 we must address this particular situation.
23981
23982 Note that if we compile and run the program above, using the dynamic model of
23983 elaboration (that is to say use the @option{-gnatE} switch),
23984 then it compiles, binds,
23985 links, and runs, printing the expected result of 2. Therefore in some sense
23986 the circularity here is only apparent, and we need to capture
23987 the properties of this program that  distinguish it from other library-level
23988 tasks that have real elaboration problems.
23989
23990 We have four possible answers to this question:
23991
23992 @itemize @bullet
23993
23994 @item
23995 Use the dynamic model of elaboration.
23996
23997 If we use the @option{-gnatE} switch, then as noted above, the program works.
23998 Why is this? If we examine the task body, it is apparent that the task cannot
23999 proceed past the
24000 @code{accept} statement until after elaboration has been completed, because
24001 the corresponding entry call comes from the main program, not earlier.
24002 This is why the dynamic model works here. But that's really giving
24003 up on a precise analysis, and we prefer to take this approach only if we cannot
24004 solve the
24005 problem in any other manner. So let us examine two ways to reorganize
24006 the program to avoid the potential elaboration problem.
24007
24008 @item
24009 Split library tasks into separate packages.
24010
24011 Write separate packages, so that library tasks are isolated from
24012 other declarations as much as possible. Let us look at a variation on
24013 the above program.
24014
24015 @smallexample @c ada
24016 package Decls1 is
24017   task Lib_Task is
24018      entry Start;
24019   end Lib_Task;
24020 end Decls1;
24021
24022 with Utils;
24023 package body Decls1 is
24024   task body Lib_Task is
24025   begin
24026      accept Start;
24027      Utils.Put_Val (2);
24028   end Lib_Task;
24029 end Decls1;
24030
24031 package Decls2 is
24032   type My_Int is new Integer;
24033   function Ident (M : My_Int) return My_Int;
24034 end Decls2;
24035
24036 with Utils;
24037 package body Decls2 is
24038   function Ident (M : My_Int) return My_Int is
24039   begin
24040      return M;
24041   end Ident;
24042 end Decls2;
24043
24044 with Decls2;
24045 package Utils is
24046   procedure Put_Val (Arg : Decls2.My_Int);
24047 end Utils;
24048
24049 with Text_IO;
24050 package body Utils is
24051   procedure Put_Val (Arg : Decls2.My_Int) is
24052   begin
24053      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24054   end Put_Val;
24055 end Utils;
24056
24057 with Decls1;
24058 procedure Main is
24059 begin
24060    Decls1.Lib_Task.Start;
24061 end;
24062 @end smallexample
24063
24064 @noindent
24065 All we have done is to split @code{Decls} into two packages, one
24066 containing the library task, and one containing everything else. Now
24067 there is no cycle, and the program compiles, binds, links and executes
24068 using the default static model of elaboration.
24069
24070 @item
24071 Declare separate task types.
24072
24073 A significant part of the problem arises because of the use of the
24074 single task declaration form. This means that the elaboration of
24075 the task type, and the elaboration of the task itself (i.e. the
24076 creation of the task) happen at the same time. A good rule
24077 of style in Ada 95 is to always create explicit task types. By
24078 following the additional step of placing task objects in separate
24079 packages from the task type declaration, many elaboration problems
24080 are avoided. Here is another modified example of the example program:
24081
24082 @smallexample @c ada
24083 package Decls is
24084   task type Lib_Task_Type is
24085      entry Start;
24086   end Lib_Task_Type;
24087
24088   type My_Int is new Integer;
24089
24090   function Ident (M : My_Int) return My_Int;
24091 end Decls;
24092
24093 with Utils;
24094 package body Decls is
24095   task body Lib_Task_Type is
24096   begin
24097      accept Start;
24098      Utils.Put_Val (2);
24099   end Lib_Task_Type;
24100
24101   function Ident (M : My_Int) return My_Int is
24102   begin
24103      return M;
24104   end Ident;
24105 end Decls;
24106
24107 with Decls;
24108 package Utils is
24109   procedure Put_Val (Arg : Decls.My_Int);
24110 end Utils;
24111
24112 with Text_IO;
24113 package body Utils is
24114   procedure Put_Val (Arg : Decls.My_Int) is
24115   begin
24116      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24117   end Put_Val;
24118 end Utils;
24119
24120 with Decls;
24121 package Declst is
24122    Lib_Task : Decls.Lib_Task_Type;
24123 end Declst;
24124
24125 with Declst;
24126 procedure Main is
24127 begin
24128    Declst.Lib_Task.Start;
24129 end;
24130 @end smallexample
24131
24132 @noindent
24133 What we have done here is to replace the @code{task} declaration in
24134 package @code{Decls} with a @code{task type} declaration. Then we
24135 introduce a separate package @code{Declst} to contain the actual
24136 task object. This separates the elaboration issues for
24137 the @code{task type}
24138 declaration, which causes no trouble, from the elaboration issues
24139 of the task object, which is also unproblematic, since it is now independent
24140 of the elaboration of  @code{Utils}.
24141 This separation of concerns also corresponds to
24142 a generally sound engineering principle of separating declarations
24143 from instances. This version of the program also compiles, binds, links,
24144 and executes, generating the expected output.
24145
24146 @item
24147 Use No_Entry_Calls_In_Elaboration_Code restriction.
24148 @cindex No_Entry_Calls_In_Elaboration_Code
24149
24150 The previous two approaches described how a program can be restructured
24151 to avoid the special problems caused by library task bodies. in practice,
24152 however, such restructuring may be difficult to apply to existing legacy code,
24153 so we must consider solutions that do not require massive rewriting.
24154
24155 Let us consider more carefully why our original sample program works
24156 under the dynamic model of elaboration. The reason is that the code
24157 in the task body blocks immediately on the @code{accept}
24158 statement. Now of course there is nothing to prohibit elaboration
24159 code from making entry calls (for example from another library level task),
24160 so we cannot tell in isolation that
24161 the task will not execute the accept statement  during elaboration.
24162
24163 However, in practice it is very unusual to see elaboration code
24164 make any entry calls, and the pattern of tasks starting
24165 at elaboration time and then immediately blocking on @code{accept} or
24166 @code{select} statements is very common. What this means is that
24167 the compiler is being too pessimistic when it analyzes the
24168 whole package body as though it might be executed at elaboration
24169 time.
24170
24171 If we know that the elaboration code contains no entry calls, (a very safe
24172 assumption most of the time, that could almost be made the default
24173 behavior), then we can compile all units of the program under control
24174 of the following configuration pragma:
24175
24176 @smallexample
24177 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24178 @end smallexample
24179
24180 @noindent
24181 This pragma can be placed in the @file{gnat.adc} file in the usual
24182 manner. If we take our original unmodified program and compile it
24183 in the presence of a @file{gnat.adc} containing the above pragma,
24184 then once again, we can compile, bind, link, and execute, obtaining
24185 the expected result. In the presence of this pragma, the compiler does
24186 not trace calls in a task body, that appear after the first @code{accept}
24187 or @code{select} statement, and therefore does not report a potential
24188 circularity in the original program.
24189
24190 The compiler will check to the extent it can that the above
24191 restriction is not violated, but it is not always possible to do a
24192 complete check at compile time, so it is important to use this
24193 pragma only if the stated restriction is in fact met, that is to say
24194 no task receives an entry call before elaboration of all units is completed.
24195
24196 @end itemize
24197
24198 @node Mixing Elaboration Models
24199 @section Mixing Elaboration Models
24200 @noindent
24201 So far, we have assumed that the entire program is either compiled
24202 using the dynamic model or static model, ensuring consistency. It
24203 is possible to mix the two models, but rules have to be followed
24204 if this mixing is done to ensure that elaboration checks are not
24205 omitted.
24206
24207 The basic rule is that @emph{a unit compiled with the static model cannot
24208 be @code{with'ed} by a unit compiled with the dynamic model}. The
24209 reason for this is that in the static model, a unit assumes that
24210 its clients guarantee to use (the equivalent of) pragma
24211 @code{Elaborate_All} so that no elaboration checks are required
24212 in inner subprograms, and this assumption is violated if the
24213 client is compiled with dynamic checks.
24214
24215 The precise rule is as follows. A unit that is compiled with dynamic
24216 checks can only @code{with} a unit that meets at least one of the
24217 following criteria:
24218
24219 @itemize @bullet
24220
24221 @item
24222 The @code{with'ed} unit is itself compiled with dynamic elaboration
24223 checks (that is with the @option{-gnatE} switch.
24224
24225 @item
24226 The @code{with'ed} unit is an internal GNAT implementation unit from
24227 the System, Interfaces, Ada, or GNAT hierarchies.
24228
24229 @item
24230 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24231
24232 @item
24233 The @code{with'ing} unit (that is the client) has an explicit pragma
24234 @code{Elaborate_All} for the @code{with'ed} unit.
24235
24236 @end itemize
24237
24238 @noindent
24239 If this rule is violated, that is if a unit with dynamic elaboration
24240 checks @code{with's} a unit that does not meet one of the above four
24241 criteria, then the binder (@code{gnatbind}) will issue a warning
24242 similar to that in the following example:
24243
24244 @smallexample
24245 warning: "x.ads" has dynamic elaboration checks and with's
24246 warning:   "y.ads" which has static elaboration checks
24247 @end smallexample
24248
24249 @noindent
24250 These warnings indicate that the rule has been violated, and that as a result
24251 elaboration checks may be missed in the resulting executable file.
24252 This warning may be suppressed using the @option{-ws} binder switch
24253 in the usual manner.
24254
24255 One useful application of this mixing rule is in the case of a subsystem
24256 which does not itself @code{with} units from the remainder of the
24257 application. In this case, the entire subsystem can be compiled with
24258 dynamic checks to resolve a circularity in the subsystem, while
24259 allowing the main application that uses this subsystem to be compiled
24260 using the more reliable default static model.
24261
24262 @node What to Do If the Default Elaboration Behavior Fails
24263 @section What to Do If the Default Elaboration Behavior Fails
24264
24265 @noindent
24266 If the binder cannot find an acceptable order, it outputs detailed
24267 diagnostics. For example:
24268 @smallexample
24269 @group
24270 @iftex
24271 @leftskip=0cm
24272 @end iftex
24273 error: elaboration circularity detected
24274 info:   "proc (body)" must be elaborated before "pack (body)"
24275 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24276 info:     recompile "pack (body)" with -gnatwl
24277 info:                             for full details
24278 info:       "proc (body)"
24279 info:         is needed by its spec:
24280 info:       "proc (spec)"
24281 info:         which is withed by:
24282 info:       "pack (body)"
24283 info:  "pack (body)" must be elaborated before "proc (body)"
24284 info:     reason: pragma Elaborate in unit "proc (body)"
24285 @end group
24286
24287 @end smallexample
24288
24289 @noindent
24290 In this case we have a cycle that the binder cannot break. On the one
24291 hand, there is an explicit pragma Elaborate in @code{proc} for
24292 @code{pack}. This means that the body of @code{pack} must be elaborated
24293 before the body of @code{proc}. On the other hand, there is elaboration
24294 code in @code{pack} that calls a subprogram in @code{proc}. This means
24295 that for maximum safety, there should really be a pragma
24296 Elaborate_All in @code{pack} for @code{proc} which would require that
24297 the body of @code{proc} be elaborated before the body of
24298 @code{pack}. Clearly both requirements cannot be satisfied.
24299 Faced with a circularity of this kind, you have three different options.
24300
24301 @table @asis
24302 @item Fix the program
24303 The most desirable option from the point of view of long-term maintenance
24304 is to rearrange the program so that the elaboration problems are avoided.
24305 One useful technique is to place the elaboration code into separate
24306 child packages. Another is to move some of the initialization code to
24307 explicitly called subprograms, where the program controls the order
24308 of initialization explicitly. Although this is the most desirable option,
24309 it may be impractical and involve too much modification, especially in
24310 the case of complex legacy code.
24311
24312 @item Perform dynamic checks
24313 If the compilations are done using the
24314 @option{-gnatE}
24315 (dynamic elaboration check) switch, then GNAT behaves in
24316 a quite different manner. Dynamic checks are generated for all calls
24317 that could possibly result in raising an exception. With this switch,
24318 the compiler does not generate implicit @code{Elaborate_All} pragmas.
24319 The behavior then is exactly as specified in the Ada 95 Reference Manual.
24320 The binder will generate an executable program that may or may not
24321 raise @code{Program_Error}, and then it is the programmer's job to ensure
24322 that it does not raise an exception. Note that it is important to
24323 compile all units with the switch, it cannot be used selectively.
24324
24325 @item Suppress checks
24326 The drawback of dynamic checks is that they generate a
24327 significant overhead at run time, both in space and time. If you
24328 are absolutely sure that your program cannot raise any elaboration
24329 exceptions, and you still want to use the dynamic elaboration model,
24330 then you can use the configuration pragma
24331 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24332 example this pragma could be placed in the @file{gnat.adc} file.
24333
24334 @item Suppress checks selectively
24335 When you know that certain calls in elaboration code cannot possibly
24336 lead to an elaboration error, and the binder nevertheless generates warnings
24337 on those calls and inserts Elaborate_All pragmas that lead to elaboration
24338 circularities, it is possible to remove those warnings locally and obtain
24339 a program that will bind. Clearly this can be unsafe, and it is the
24340 responsibility of the programmer to make sure that the resulting program has
24341 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
24342 be used with different granularity to suppress warnings and break
24343 elaboration circularities:
24344
24345 @itemize @bullet
24346 @item
24347 Place the pragma that names the called subprogram in the declarative part
24348 that contains the call.
24349
24350 @item
24351 Place the pragma in the declarative part, without naming an entity. This
24352 disables warnings on all calls in the corresponding  declarative region.
24353
24354 @item
24355 Place the pragma in the package spec that declares the called subprogram,
24356 and name the subprogram. This disables warnings on all elaboration calls to
24357 that subprogram.
24358
24359 @item
24360 Place the pragma in the package spec that declares the called subprogram,
24361 without naming any entity. This disables warnings on all elaboration calls to
24362 all subprograms declared in this spec.
24363
24364 @item Use Pragma Elaborate
24365 As previously described in section @xref{Treatment of Pragma Elaborate},
24366 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24367 that no elaboration checks are required on calls to the designated unit.
24368 There may be cases in which the caller knows that no transitive calls
24369 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24370 case where @code{pragma Elaborate_All} would cause a circularity.
24371 @end itemize
24372
24373 @noindent
24374 These five cases are listed in order of decreasing safety, and therefore
24375 require increasing programmer care in their application. Consider the
24376 following program:
24377
24378 @smallexample @c adanocomment
24379 package Pack1 is
24380   function F1 return Integer;
24381   X1 : Integer;
24382 end Pack1;
24383
24384 package Pack2 is
24385   function F2 return Integer;
24386   function Pure (x : integer) return integer;
24387   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24388   --  pragma Suppress (Elaboration_Check);              -- (4)
24389 end Pack2;
24390
24391 with Pack2;
24392 package body Pack1 is
24393   function F1 return Integer is
24394   begin
24395     return 100;
24396   end F1;
24397   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24398 begin
24399   declare
24400     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24401     --  pragma Suppress(Elaboration_Check);             -- (2)
24402   begin
24403     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24404   end;
24405 end Pack1;
24406
24407 with Pack1;
24408 package body Pack2 is
24409   function F2 return Integer is
24410   begin
24411      return Pack1.F1;
24412   end F2;
24413   function Pure (x : integer) return integer is
24414   begin
24415      return x ** 3 - 3 * x;
24416   end;
24417 end Pack2;
24418
24419 with Pack1, Ada.Text_IO;
24420 procedure Proc3 is
24421 begin
24422   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24423 end Proc3;
24424 @end smallexample
24425 In the absence of any pragmas, an attempt to bind this program produces
24426 the following diagnostics:
24427 @smallexample
24428 @group
24429 @iftex
24430 @leftskip=.5cm
24431 @end iftex
24432 error: elaboration circularity detected
24433 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24434 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24435 info:       recompile "pack1 (body)" with -gnatwl for full details
24436 info:          "pack1 (body)"
24437 info:             must be elaborated along with its spec:
24438 info:          "pack1 (spec)"
24439 info:             which is withed by:
24440 info:          "pack2 (body)"
24441 info:             which must be elaborated along with its spec:
24442 info:          "pack2 (spec)"
24443 info:             which is withed by:
24444 info:          "pack1 (body)"
24445 @end group
24446 @end smallexample
24447 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24448 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24449 F2 is safe, even though F2 calls F1, because the call appears after the
24450 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24451 remove the warning on the call. It is also possible to use pragma (2)
24452 because there are no other potentially unsafe calls in the block.
24453
24454 @noindent
24455 The call to @code{Pure} is safe because this function does not depend on the
24456 state of @code{Pack2}. Therefore any call to this function is safe, and it
24457 is correct to place pragma (3) in the corresponding package spec.
24458
24459 @noindent
24460 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24461 warnings on all calls to functions declared therein. Note that this is not
24462 necessarily safe, and requires more detailed examination of the subprogram
24463 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24464 be already elaborated.
24465 @end table
24466
24467 @noindent
24468 It is hard to generalize on which of these four approaches should be
24469 taken. Obviously if it is possible to fix the program so that the default
24470 treatment works, this is preferable, but this may not always be practical.
24471 It is certainly simple enough to use
24472 @option{-gnatE}
24473 but the danger in this case is that, even if the GNAT binder
24474 finds a correct elaboration order, it may not always do so,
24475 and certainly a binder from another Ada compiler might not. A
24476 combination of testing and analysis (for which the warnings generated
24477 with the
24478 @option{-gnatwl}
24479 switch can be useful) must be used to ensure that the program is free
24480 of errors. One switch that is useful in this testing is the
24481 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24482 switch for
24483 @code{gnatbind}.
24484 Normally the binder tries to find an order that has the best chance of
24485 of avoiding elaboration problems. With this switch, the binder
24486 plays a devil's advocate role, and tries to choose the order that
24487 has the best chance of failing. If your program works even with this
24488 switch, then it has a better chance of being error free, but this is still
24489 not a guarantee.
24490
24491 For an example of this approach in action, consider the C-tests (executable
24492 tests) from the ACVC suite. If these are compiled and run with the default
24493 treatment, then all but one of them succeed without generating any error
24494 diagnostics from the binder. However, there is one test that fails, and
24495 this is not surprising, because the whole point of this test is to ensure
24496 that the compiler can handle cases where it is impossible to determine
24497 a correct order statically, and it checks that an exception is indeed
24498 raised at run time.
24499
24500 This one test must be compiled and run using the
24501 @option{-gnatE}
24502 switch, and then it passes. Alternatively, the entire suite can
24503 be run using this switch. It is never wrong to run with the dynamic
24504 elaboration switch if your code is correct, and we assume that the
24505 C-tests are indeed correct (it is less efficient, but efficiency is
24506 not a factor in running the ACVC tests.)
24507
24508 @node Elaboration for Access-to-Subprogram Values
24509 @section Elaboration for Access-to-Subprogram Values
24510 @cindex Access-to-subprogram
24511
24512 @noindent
24513 The introduction of access-to-subprogram types in Ada 95 complicates
24514 the handling of elaboration. The trouble is that it becomes
24515 impossible to tell at compile time which procedure
24516 is being called. This means that it is not possible for the binder
24517 to analyze the elaboration requirements in this case.
24518
24519 If at the point at which the access value is created
24520 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24521 the body of the subprogram is
24522 known to have been elaborated, then the access value is safe, and its use
24523 does not require a check. This may be achieved by appropriate arrangement
24524 of the order of declarations if the subprogram is in the current unit,
24525 or, if the subprogram is in another unit, by using pragma
24526 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24527 on the referenced unit.
24528
24529 If the referenced body is not known to have been elaborated at the point
24530 the access value is created, then any use of the access value must do a
24531 dynamic check, and this dynamic check will fail and raise a
24532 @code{Program_Error} exception if the body has not been elaborated yet.
24533 GNAT will generate the necessary checks, and in addition, if the
24534 @option{-gnatwl}
24535 switch is set, will generate warnings that such checks are required.
24536
24537 The use of dynamic dispatching for tagged types similarly generates
24538 a requirement for dynamic checks, and premature calls to any primitive
24539 operation of a tagged type before the body of the operation has been
24540 elaborated, will result in the raising of @code{Program_Error}.
24541
24542 @node Summary of Procedures for Elaboration Control
24543 @section Summary of Procedures for Elaboration Control
24544 @cindex Elaboration control
24545
24546 @noindent
24547 First, compile your program with the default options, using none of
24548 the special elaboration control switches. If the binder successfully
24549 binds your program, then you can be confident that, apart from issues
24550 raised by the use of access-to-subprogram types and dynamic dispatching,
24551 the program is free of elaboration errors. If it is important that the
24552 program be portable, then use the
24553 @option{-gnatwl}
24554 switch to generate warnings about missing @code{Elaborate_All}
24555 pragmas, and supply the missing pragmas.
24556
24557 If the program fails to bind using the default static elaboration
24558 handling, then you can fix the program to eliminate the binder
24559 message, or recompile the entire program with the
24560 @option{-gnatE} switch to generate dynamic elaboration checks,
24561 and, if you are sure there really are no elaboration problems,
24562 use a global pragma @code{Suppress (Elaboration_Check)}.
24563
24564 @node Other Elaboration Order Considerations
24565 @section Other Elaboration Order Considerations
24566 @noindent
24567 This section has been entirely concerned with the issue of finding a valid
24568 elaboration order, as defined by the Ada Reference Manual. In a case
24569 where several elaboration orders are valid, the task is to find one
24570 of the possible valid elaboration orders (and the static model in GNAT
24571 will ensure that this is achieved).
24572
24573 The purpose of the elaboration rules in the Ada Reference Manual is to
24574 make sure that no entity is accessed before it has been elaborated. For
24575 a subprogram, this means that the spec and body must have been elaborated
24576 before the subprogram is called. For an object, this means that the object
24577 must have been elaborated before its value is read or written. A violation
24578 of either of these two requirements is an access before elaboration order,
24579 and this section has been all about avoiding such errors.
24580
24581 In the case where more than one order of elaboration is possible, in the
24582 sense that access before elaboration errors are avoided, then any one of
24583 the orders is ``correct'' in the sense that it meets the requirements of
24584 the Ada Reference Manual, and no such error occurs.
24585
24586 However, it may be the case for a given program, that there are
24587 constraints on the order of elaboration that come not from consideration
24588 of avoiding elaboration errors, but rather from extra-lingual logic
24589 requirements. Consider this example:
24590
24591 @smallexample @c ada
24592 with Init_Constants;
24593 package Constants is
24594    X : Integer := 0;
24595    Y : Integer := 0;
24596 end Constants;
24597
24598 package Init_Constants is
24599    procedure P; -- require a body
24600 end Init_Constants;
24601
24602 with Constants;
24603 package body Init_Constants is
24604    procedure P is begin null; end;
24605 begin
24606    Constants.X := 3;
24607    Constants.Y := 4;
24608 end Init_Constants;
24609
24610 with Constants;
24611 package Calc is
24612    Z : Integer := Constants.X + Constants.Y;
24613 end Calc;
24614
24615 with Calc;
24616 with Text_IO; use Text_IO;
24617 procedure Main is
24618 begin
24619    Put_Line (Calc.Z'Img);
24620 end Main;
24621 @end smallexample
24622
24623 @noindent
24624 In this example, there is more than one valid order of elaboration. For
24625 example both the following are correct orders:
24626
24627 @smallexample
24628 Init_Constants spec
24629 Constants spec
24630 Calc spec
24631 Init_Constants body
24632 Main body
24633
24634   and
24635
24636 Init_Constants spec
24637 Init_Constants body
24638 Constants spec
24639 Calc spec
24640 Main body
24641 @end smallexample
24642
24643 @noindent
24644 There is no language rule to prefer one or the other, both are correct
24645 from an order of elaboration point of view. But the programmatic effects
24646 of the two orders are very different. In the first, the elaboration routine
24647 of @code{Calc} initializes @code{Z} to zero, and then the main program
24648 runs with this value of zero. But in the second order, the elaboration
24649 routine of @code{Calc} runs after the body of Init_Constants has set
24650 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24651 runs.
24652
24653 One could perhaps by applying pretty clever non-artificial intelligence
24654 to the situation guess that it is more likely that the second order of
24655 elaboration is the one desired, but there is no formal linguistic reason
24656 to prefer one over the other. In fact in this particular case, GNAT will
24657 prefer the second order, because of the rule that bodies are elaborated
24658 as soon as possible, but it's just luck that this is what was wanted
24659 (if indeed the second order was preferred).
24660
24661 If the program cares about the order of elaboration routines in a case like
24662 this, it is important to specify the order required. In this particular
24663 case, that could have been achieved by adding to the spec of Calc:
24664
24665 @smallexample @c ada
24666 pragma Elaborate_All (Constants);
24667 @end smallexample
24668
24669 @noindent
24670 which requires that the body (if any) and spec of @code{Constants},
24671 as well as the body and spec of any unit @code{with}'ed by
24672 @code{Constants} be elaborated before @code{Calc} is elaborated.
24673
24674 Clearly no automatic method can always guess which alternative you require,
24675 and if you are working with legacy code that had constraints of this kind
24676 which were not properly specified by adding @code{Elaborate} or
24677 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24678 compilers can choose different orders.
24679
24680 The @code{gnatbind}
24681 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24682 out problems. This switch causes bodies to be elaborated as late as possible
24683 instead of as early as possible. In the example above, it would have forced
24684 the choice of the first elaboration order. If you get different results
24685 when using this switch, and particularly if one set of results is right,
24686 and one is wrong as far as you are concerned, it shows that you have some
24687 missing @code{Elaborate} pragmas. For the example above, we have the
24688 following output:
24689
24690 @smallexample
24691 gnatmake -f -q main
24692 main
24693  7
24694 gnatmake -f -q main -bargs -p
24695 main
24696  0
24697 @end smallexample
24698
24699 @noindent
24700 It is of course quite unlikely that both these results are correct, so
24701 it is up to you in a case like this to investigate the source of the
24702 difference, by looking at the two elaboration orders that are chosen,
24703 and figuring out which is correct, and then adding the necessary
24704 @code{Elaborate_All} pragmas to ensure the desired order.
24705
24706 @node Inline Assembler
24707 @appendix Inline Assembler
24708
24709 @noindent
24710 If you need to write low-level software that interacts directly
24711 with the hardware, Ada provides two ways to incorporate assembly
24712 language code into your program.  First, you can import and invoke
24713 external routines written in assembly language, an Ada feature fully
24714 supported by GNAT.  However, for small sections of code it may be simpler
24715 or more efficient to include assembly language statements directly
24716 in your Ada source program, using the facilities of the implementation-defined
24717 package @code{System.Machine_Code}, which incorporates the gcc
24718 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24719 including the following:
24720
24721 @itemize @bullet
24722 @item No need to use non-Ada tools
24723 @item Consistent interface over different targets
24724 @item Automatic usage of the proper calling conventions
24725 @item Access to Ada constants and variables
24726 @item Definition of intrinsic routines
24727 @item Possibility of inlining a subprogram comprising assembler code
24728 @item Code optimizer can take Inline Assembler code into account
24729 @end itemize
24730
24731 This chapter presents a series of examples to show you how to use
24732 the Inline Assembler.  Although it focuses on the Intel x86,
24733 the general approach applies also to other processors.
24734 It is assumed that you are familiar with Ada
24735 and with assembly language programming.
24736
24737 @menu
24738 * Basic Assembler Syntax::
24739 * A Simple Example of Inline Assembler::
24740 * Output Variables in Inline Assembler::
24741 * Input Variables in Inline Assembler::
24742 * Inlining Inline Assembler Code::
24743 * Other Asm Functionality::
24744 @end menu
24745
24746 @c ---------------------------------------------------------------------------
24747 @node Basic Assembler Syntax
24748 @section Basic Assembler Syntax
24749
24750 @noindent
24751 The assembler used by GNAT and gcc is based not on the Intel assembly
24752 language, but rather on a language that descends from the AT&T Unix
24753 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24754 The following table summarizes the main features of @emph{as} syntax
24755 and points out the differences from the Intel conventions.
24756 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24757 pre-processor) documentation for further information.
24758
24759 @table @asis
24760 @item Register names
24761 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24762 @*
24763 Intel: No extra punctuation; for example @code{eax}
24764
24765 @item Immediate operand
24766 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24767 @*
24768 Intel: No extra punctuation; for example @code{4}
24769
24770 @item Address
24771 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24772 @*
24773 Intel: No extra punctuation; for example @code{loc}
24774
24775 @item Memory contents
24776 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24777 @*
24778 Intel: Square brackets; for example @code{[loc]}
24779
24780 @item Register contents
24781 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24782 @*
24783 Intel: Square brackets; for example @code{[eax]}
24784
24785 @item Hexadecimal numbers
24786 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24787 @*
24788 Intel: Trailing ``h''; for example @code{A0h}
24789
24790 @item Operand size
24791 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24792 a 16-bit word
24793 @*
24794 Intel: Implicit, deduced by assembler; for example @code{mov}
24795
24796 @item Instruction repetition
24797 gcc / @emph{as}: Split into two lines; for example
24798 @*
24799 @code{rep}
24800 @*
24801 @code{stosl}
24802 @*
24803 Intel: Keep on one line; for example @code{rep stosl}
24804
24805 @item Order of operands
24806 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24807 @*
24808 Intel: Destination first; for example @code{mov eax, 4}
24809 @end table
24810
24811 @c ---------------------------------------------------------------------------
24812 @node A Simple Example of Inline Assembler
24813 @section A Simple Example of Inline Assembler
24814
24815 @noindent
24816 The following example will generate a single assembly language statement,
24817 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24818 the example will be useful in illustrating the basics of
24819 the Inline Assembler facility.
24820
24821 @smallexample @c ada
24822 @group
24823 with System.Machine_Code; use System.Machine_Code;
24824 procedure Nothing is
24825 begin
24826    Asm ("nop");
24827 end Nothing;
24828 @end group
24829 @end smallexample
24830
24831 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24832 here it takes one parameter, a @emph{template string} that must be a static
24833 expression and that will form the generated instruction.
24834 @code{Asm} may be regarded as a compile-time procedure that parses
24835 the template string and additional parameters (none here),
24836 from which it generates a sequence of assembly language instructions.
24837
24838 The examples in this chapter will illustrate several of the forms
24839 for invoking @code{Asm}; a complete specification of the syntax
24840 is found in the @cite{GNAT Reference Manual}.
24841
24842 Under the standard GNAT conventions, the @code{Nothing} procedure
24843 should be in a file named @file{nothing.adb}.
24844 You can build the executable in the usual way:
24845 @smallexample
24846 gnatmake nothing
24847 @end smallexample
24848 However, the interesting aspect of this example is not its run-time behavior
24849 but rather the generated assembly code.
24850 To see this output, invoke the compiler as follows:
24851 @smallexample
24852    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24853 @end smallexample
24854 where the options are:
24855
24856 @table @code
24857 @item -c
24858 compile only (no bind or link)
24859 @item -S
24860 generate assembler listing
24861 @item -fomit-frame-pointer
24862 do not set up separate stack frames
24863 @item -gnatp
24864 do not add runtime checks
24865 @end table
24866
24867 This gives a human-readable assembler version of the code. The resulting
24868 file will have the same name as the Ada source file, but with a @code{.s}
24869 extension. In our example, the file @file{nothing.s} has the following
24870 contents:
24871
24872 @smallexample
24873 @group
24874 .file "nothing.adb"
24875 gcc2_compiled.:
24876 ___gnu_compiled_ada:
24877 .text
24878    .align 4
24879 .globl __ada_nothing
24880 __ada_nothing:
24881 #APP
24882    nop
24883 #NO_APP
24884    jmp L1
24885    .align 2,0x90
24886 L1:
24887    ret
24888 @end group
24889 @end smallexample
24890
24891 The assembly code you included is clearly indicated by
24892 the compiler, between the @code{#APP} and @code{#NO_APP}
24893 delimiters. The character before the 'APP' and 'NOAPP'
24894 can differ on different targets. For example, GNU/Linux uses '#APP' while
24895 on NT you will see '/APP'.
24896
24897 If you make a mistake in your assembler code (such as using the
24898 wrong size modifier, or using a wrong operand for the instruction) GNAT
24899 will report this error in a temporary file, which will be deleted when
24900 the compilation is finished.  Generating an assembler file will help
24901 in such cases, since you can assemble this file separately using the
24902 @emph{as} assembler that comes with gcc.
24903
24904 Assembling the file using the command
24905
24906 @smallexample
24907 as @file{nothing.s}
24908 @end smallexample
24909 @noindent
24910 will give you error messages whose lines correspond to the assembler
24911 input file, so you can easily find and correct any mistakes you made.
24912 If there are no errors, @emph{as} will generate an object file
24913 @file{nothing.out}.
24914
24915 @c ---------------------------------------------------------------------------
24916 @node Output Variables in Inline Assembler
24917 @section Output Variables in Inline Assembler
24918
24919 @noindent
24920 The examples in this section, showing how to access the processor flags,
24921 illustrate how to specify the destination operands for assembly language
24922 statements.
24923
24924 @smallexample @c ada
24925 @group
24926 with Interfaces; use Interfaces;
24927 with Ada.Text_IO; use Ada.Text_IO;
24928 with System.Machine_Code; use System.Machine_Code;
24929 procedure Get_Flags is
24930    Flags : Unsigned_32;
24931    use ASCII;
24932 begin
24933    Asm ("pushfl"          & LF & HT & -- push flags on stack
24934         "popl %%eax"      & LF & HT & -- load eax with flags
24935         "movl %%eax, %0",             -- store flags in variable
24936         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24937    Put_Line ("Flags register:" & Flags'Img);
24938 end Get_Flags;
24939 @end group
24940 @end smallexample
24941
24942 In order to have a nicely aligned assembly listing, we have separated
24943 multiple assembler statements in the Asm template string with linefeed
24944 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24945 The resulting section of the assembly output file is:
24946
24947 @smallexample
24948 @group
24949 #APP
24950    pushfl
24951    popl %eax
24952    movl %eax, -40(%ebp)
24953 #NO_APP
24954 @end group
24955 @end smallexample
24956
24957 It would have been legal to write the Asm invocation as:
24958
24959 @smallexample
24960 Asm ("pushfl popl %%eax movl %%eax, %0")
24961 @end smallexample
24962
24963 but in the generated assembler file, this would come out as:
24964
24965 @smallexample
24966 #APP
24967    pushfl popl %eax movl %eax, -40(%ebp)
24968 #NO_APP
24969 @end smallexample
24970
24971 which is not so convenient for the human reader.
24972
24973 We use Ada comments
24974 at the end of each line to explain what the assembler instructions
24975 actually do.  This is a useful convention.
24976
24977 When writing Inline Assembler instructions, you need to precede each register
24978 and variable name with a percent sign.  Since the assembler already requires
24979 a percent sign at the beginning of a register name, you need two consecutive
24980 percent signs for such names in the Asm template string, thus @code{%%eax}.
24981 In the generated assembly code, one of the percent signs will be stripped off.
24982
24983 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24984 variables: operands you later define using @code{Input} or @code{Output}
24985 parameters to @code{Asm}.
24986 An output variable is illustrated in
24987 the third statement in the Asm template string:
24988 @smallexample
24989 movl %%eax, %0
24990 @end smallexample
24991 The intent is to store the contents of the eax register in a variable that can
24992 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24993 necessarily work, since the compiler might optimize by using a register
24994 to hold Flags, and the expansion of the @code{movl} instruction would not be
24995 aware of this optimization.  The solution is not to store the result directly
24996 but rather to advise the compiler to choose the correct operand form;
24997 that is the purpose of the @code{%0} output variable.
24998
24999 Information about the output variable is supplied in the @code{Outputs}
25000 parameter to @code{Asm}:
25001 @smallexample
25002 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25003 @end smallexample
25004
25005 The output is defined by the @code{Asm_Output} attribute of the target type;
25006 the general format is
25007 @smallexample
25008 Type'Asm_Output (constraint_string, variable_name)
25009 @end smallexample
25010
25011 The constraint string directs the compiler how
25012 to store/access the associated variable.  In the example
25013 @smallexample
25014 Unsigned_32'Asm_Output ("=m", Flags);
25015 @end smallexample
25016 the @code{"m"} (memory) constraint tells the compiler that the variable
25017 @code{Flags} should be stored in a memory variable, thus preventing
25018 the optimizer from keeping it in a register.  In contrast,
25019 @smallexample
25020 Unsigned_32'Asm_Output ("=r", Flags);
25021 @end smallexample
25022 uses the @code{"r"} (register) constraint, telling the compiler to
25023 store the variable in a register.
25024
25025 If the constraint is preceded by the equal character (@strong{=}), it tells
25026 the compiler that the variable will be used to store data into it.
25027
25028 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25029 allowing the optimizer to choose whatever it deems best.
25030
25031 There are a fairly large number of constraints, but the ones that are
25032 most useful (for the Intel x86 processor) are the following:
25033
25034 @table @code
25035 @item =
25036 output constraint
25037 @item g
25038 global (i.e. can be stored anywhere)
25039 @item m
25040 in memory
25041 @item I
25042 a constant
25043 @item a
25044 use eax
25045 @item b
25046 use ebx
25047 @item c
25048 use ecx
25049 @item d
25050 use edx
25051 @item S
25052 use esi
25053 @item D
25054 use edi
25055 @item r
25056 use one of eax, ebx, ecx or edx
25057 @item q
25058 use one of eax, ebx, ecx, edx, esi or edi
25059 @end table
25060
25061 The full set of constraints is described in the gcc and @emph{as}
25062 documentation; note that it is possible to combine certain constraints
25063 in one constraint string.
25064
25065 You specify the association of an output variable with an assembler operand
25066 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25067 integer.  Thus in
25068 @smallexample @c ada
25069 @group
25070 Asm ("pushfl"          & LF & HT & -- push flags on stack
25071      "popl %%eax"      & LF & HT & -- load eax with flags
25072      "movl %%eax, %0",             -- store flags in variable
25073      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25074 @end group
25075 @end smallexample
25076 @noindent
25077 @code{%0} will be replaced in the expanded code by the appropriate operand,
25078 whatever
25079 the compiler decided for the @code{Flags} variable.
25080
25081 In general, you may have any number of output variables:
25082 @itemize @bullet
25083 @item
25084 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25085 @item
25086 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25087 of @code{Asm_Output} attributes
25088 @end itemize
25089
25090 For example:
25091 @smallexample @c ada
25092 @group
25093 Asm ("movl %%eax, %0" & LF & HT &
25094      "movl %%ebx, %1" & LF & HT &
25095      "movl %%ecx, %2",
25096      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25097                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25098                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25099 @end group
25100 @end smallexample
25101 @noindent
25102 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25103 in the Ada program.
25104
25105 As a variation on the @code{Get_Flags} example, we can use the constraints
25106 string to direct the compiler to store the eax register into the @code{Flags}
25107 variable, instead of including the store instruction explicitly in the
25108 @code{Asm} template string:
25109
25110 @smallexample @c ada
25111 @group
25112 with Interfaces; use Interfaces;
25113 with Ada.Text_IO; use Ada.Text_IO;
25114 with System.Machine_Code; use System.Machine_Code;
25115 procedure Get_Flags_2 is
25116    Flags : Unsigned_32;
25117    use ASCII;
25118 begin
25119    Asm ("pushfl"      & LF & HT & -- push flags on stack
25120         "popl %%eax",             -- save flags in eax
25121         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25122    Put_Line ("Flags register:" & Flags'Img);
25123 end Get_Flags_2;
25124 @end group
25125 @end smallexample
25126
25127 @noindent
25128 The @code{"a"} constraint tells the compiler that the @code{Flags}
25129 variable will come from the eax register. Here is the resulting code:
25130
25131 @smallexample
25132 @group
25133 #APP
25134    pushfl
25135    popl %eax
25136 #NO_APP
25137    movl %eax,-40(%ebp)
25138 @end group
25139 @end smallexample
25140
25141 @noindent
25142 The compiler generated the store of eax into Flags after
25143 expanding the assembler code.
25144
25145 Actually, there was no need to pop the flags into the eax register;
25146 more simply, we could just pop the flags directly into the program variable:
25147
25148 @smallexample @c ada
25149 @group
25150 with Interfaces; use Interfaces;
25151 with Ada.Text_IO; use Ada.Text_IO;
25152 with System.Machine_Code; use System.Machine_Code;
25153 procedure Get_Flags_3 is
25154    Flags : Unsigned_32;
25155    use ASCII;
25156 begin
25157    Asm ("pushfl"  & LF & HT & -- push flags on stack
25158         "pop %0",             -- save flags in Flags
25159         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25160    Put_Line ("Flags register:" & Flags'Img);
25161 end Get_Flags_3;
25162 @end group
25163 @end smallexample
25164
25165 @c ---------------------------------------------------------------------------
25166 @node Input Variables in Inline Assembler
25167 @section Input Variables in Inline Assembler
25168
25169 @noindent
25170 The example in this section illustrates how to specify the source operands
25171 for assembly language statements.
25172 The program simply increments its input value by 1:
25173
25174 @smallexample @c ada
25175 @group
25176 with Interfaces; use Interfaces;
25177 with Ada.Text_IO; use Ada.Text_IO;
25178 with System.Machine_Code; use System.Machine_Code;
25179 procedure Increment is
25180
25181    function Incr (Value : Unsigned_32) return Unsigned_32 is
25182       Result : Unsigned_32;
25183    begin
25184       Asm ("incl %0",
25185            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25186            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25187       return Result;
25188    end Incr;
25189
25190    Value : Unsigned_32;
25191
25192 begin
25193    Value := 5;
25194    Put_Line ("Value before is" & Value'Img);
25195    Value := Incr (Value);
25196    Put_Line ("Value after is" & Value'Img);
25197 end Increment;
25198 @end group
25199 @end smallexample
25200
25201 The @code{Outputs} parameter to @code{Asm} specifies
25202 that the result will be in the eax register and that it is to be stored
25203 in the @code{Result} variable.
25204
25205 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25206 but with an @code{Asm_Input} attribute.
25207 The @code{"="} constraint, indicating an output value, is not present.
25208
25209 You can have multiple input variables, in the same way that you can have more
25210 than one output variable.
25211
25212 The parameter count (%0, %1) etc, now starts at the first input
25213 statement, and continues with the output statements.
25214 When both parameters use the same variable, the
25215 compiler will treat them as the same %n operand, which is the case here.
25216
25217 Just as the @code{Outputs} parameter causes the register to be stored into the
25218 target variable after execution of the assembler statements, so does the
25219 @code{Inputs} parameter cause its variable to be loaded into the register
25220 before execution of the assembler statements.
25221
25222 Thus the effect of the @code{Asm} invocation is:
25223 @enumerate
25224 @item load the 32-bit value of @code{Value} into eax
25225 @item execute the @code{incl %eax} instruction
25226 @item store the contents of eax into the @code{Result} variable
25227 @end enumerate
25228
25229 The resulting assembler file (with @option{-O2} optimization) contains:
25230 @smallexample
25231 @group
25232 _increment__incr.1:
25233    subl $4,%esp
25234    movl 8(%esp),%eax
25235 #APP
25236    incl %eax
25237 #NO_APP
25238    movl %eax,%edx
25239    movl %ecx,(%esp)
25240    addl $4,%esp
25241    ret
25242 @end group
25243 @end smallexample
25244
25245 @c ---------------------------------------------------------------------------
25246 @node Inlining Inline Assembler Code
25247 @section Inlining Inline Assembler Code
25248
25249 @noindent
25250 For a short subprogram such as the @code{Incr} function in the previous
25251 section, the overhead of the call and return (creating / deleting the stack
25252 frame) can be significant, compared to the amount of code in the subprogram
25253 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25254 which directs the compiler to expand invocations of the subprogram at the
25255 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25256 Here is the resulting program:
25257
25258 @smallexample @c ada
25259 @group
25260 with Interfaces; use Interfaces;
25261 with Ada.Text_IO; use Ada.Text_IO;
25262 with System.Machine_Code; use System.Machine_Code;
25263 procedure Increment_2 is
25264
25265    function Incr (Value : Unsigned_32) return Unsigned_32 is
25266       Result : Unsigned_32;
25267    begin
25268       Asm ("incl %0",
25269            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25270            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25271       return Result;
25272    end Incr;
25273    pragma Inline (Increment);
25274
25275    Value : Unsigned_32;
25276
25277 begin
25278    Value := 5;
25279    Put_Line ("Value before is" & Value'Img);
25280    Value := Increment (Value);
25281    Put_Line ("Value after is" & Value'Img);
25282 end Increment_2;
25283 @end group
25284 @end smallexample
25285
25286 Compile the program with both optimization (@option{-O2}) and inlining
25287 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25288
25289 The @code{Incr} function is still compiled as usual, but at the
25290 point in @code{Increment} where our function used to be called:
25291
25292 @smallexample
25293 @group
25294 pushl %edi
25295 call _increment__incr.1
25296 @end group
25297 @end smallexample
25298
25299 @noindent
25300 the code for the function body directly appears:
25301
25302 @smallexample
25303 @group
25304 movl %esi,%eax
25305 #APP
25306    incl %eax
25307 #NO_APP
25308    movl %eax,%edx
25309 @end group
25310 @end smallexample
25311
25312 @noindent
25313 thus saving the overhead of stack frame setup and an out-of-line call.
25314
25315 @c ---------------------------------------------------------------------------
25316 @node Other Asm Functionality
25317 @section Other @code{Asm} Functionality
25318
25319 @noindent
25320 This section describes two important parameters to the @code{Asm}
25321 procedure: @code{Clobber}, which identifies register usage;
25322 and @code{Volatile}, which inhibits unwanted optimizations.
25323
25324 @menu
25325 * The Clobber Parameter::
25326 * The Volatile Parameter::
25327 @end menu
25328
25329 @c ---------------------------------------------------------------------------
25330 @node The Clobber Parameter
25331 @subsection The @code{Clobber} Parameter
25332
25333 @noindent
25334 One of the dangers of intermixing assembly language and a compiled language
25335 such as Ada is that the compiler needs to be aware of which registers are
25336 being used by the assembly code.  In some cases, such as the earlier examples,
25337 the constraint string is sufficient to indicate register usage (e.g.,
25338 @code{"a"} for
25339 the eax register).  But more generally, the compiler needs an explicit
25340 identification of the registers that are used by the Inline Assembly
25341 statements.
25342
25343 Using a register that the compiler doesn't know about
25344 could be a side effect of an instruction (like @code{mull}
25345 storing its result in both eax and edx).
25346 It can also arise from explicit register usage in your
25347 assembly code; for example:
25348 @smallexample
25349 @group
25350 Asm ("movl %0, %%ebx" & LF & HT &
25351      "movl %%ebx, %1",
25352      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25353      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25354 @end group
25355 @end smallexample
25356 @noindent
25357 where the compiler (since it does not analyze the @code{Asm} template string)
25358 does not know you are using the ebx register.
25359
25360 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25361 to identify the registers that will be used by your assembly code:
25362
25363 @smallexample
25364 @group
25365 Asm ("movl %0, %%ebx" & LF & HT &
25366      "movl %%ebx, %1",
25367      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25368      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25369      Clobber => "ebx");
25370 @end group
25371 @end smallexample
25372
25373 The Clobber parameter is a static string expression specifying the
25374 register(s) you are using.  Note that register names are @emph{not} prefixed
25375 by a percent sign. Also, if more than one register is used then their names
25376 are separated by commas; e.g., @code{"eax, ebx"}
25377
25378 The @code{Clobber} parameter has several additional uses:
25379 @enumerate
25380 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25381 @item Use ``register'' name @code{memory} if you changed a memory location
25382 @end enumerate
25383
25384 @c ---------------------------------------------------------------------------
25385 @node The Volatile Parameter
25386 @subsection The @code{Volatile} Parameter
25387 @cindex Volatile parameter
25388
25389 @noindent
25390 Compiler optimizations in the presence of Inline Assembler may sometimes have
25391 unwanted effects.  For example, when an @code{Asm} invocation with an input
25392 variable is inside a loop, the compiler might move the loading of the input
25393 variable outside the loop, regarding it as a one-time initialization.
25394
25395 If this effect is not desired, you can disable such optimizations by setting
25396 the @code{Volatile} parameter to @code{True}; for example:
25397
25398 @smallexample @c ada
25399 @group
25400 Asm ("movl %0, %%ebx" & LF & HT &
25401      "movl %%ebx, %1",
25402      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25403      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25404      Clobber  => "ebx",
25405      Volatile => True);
25406 @end group
25407 @end smallexample
25408
25409 By default, @code{Volatile} is set to @code{False} unless there is no
25410 @code{Outputs} parameter.
25411
25412 Although setting @code{Volatile} to @code{True} prevents unwanted
25413 optimizations, it will also disable other optimizations that might be
25414 important for efficiency. In general, you should set @code{Volatile}
25415 to @code{True} only if the compiler's optimizations have created
25416 problems.
25417 @c END OF INLINE ASSEMBLER CHAPTER
25418 @c ===============================
25419
25420 @c ***********************************
25421 @c * Compatibility and Porting Guide *
25422 @c ***********************************
25423 @node Compatibility and Porting Guide
25424 @appendix Compatibility and Porting Guide
25425
25426 @noindent
25427 This chapter describes the compatibility issues that may arise between
25428 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25429 can expedite porting
25430 applications developed in other Ada environments.
25431
25432 @menu
25433 * Compatibility with Ada 83::
25434 * Implementation-dependent characteristics::
25435 * Compatibility with Other Ada 95 Systems::
25436 * Representation Clauses::
25437 * Compatibility with DEC Ada 83::
25438 @ifset vms
25439 * Transitioning from Alpha to Integrity OpenVMS::
25440 @end ifset
25441 @end menu
25442
25443 @node Compatibility with Ada 83
25444 @section Compatibility with Ada 83
25445 @cindex Compatibility (between Ada 83 and Ada 95)
25446
25447 @noindent
25448 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25449 particular, the design intention is that the difficulties associated
25450 with moving from Ada 83 to Ada 95 should be no greater than those
25451 that occur when moving from one Ada 83 system to another.
25452
25453 However, there are a number of points at which there are minor
25454 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25455 full details of these issues,
25456 and should be consulted for a complete treatment.
25457 In practice the
25458 following subsections treat the most likely issues to be encountered.
25459
25460 @menu
25461 * Legal Ada 83 programs that are illegal in Ada 95::
25462 * More deterministic semantics::
25463 * Changed semantics::
25464 * Other language compatibility issues::
25465 @end menu
25466
25467 @node Legal Ada 83 programs that are illegal in Ada 95
25468 @subsection Legal Ada 83 programs that are illegal in Ada 95
25469
25470 @table @asis
25471 @item Character literals
25472 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25473 @code{Wide_Character} as a new predefined character type, some uses of
25474 character literals that were legal in Ada 83 are illegal in Ada 95.
25475 For example:
25476 @smallexample @c ada
25477    for Char in 'A' .. 'Z' loop ... end loop;
25478 @end smallexample
25479 @noindent
25480 The problem is that @code{'A'} and @code{'Z'} could be from either
25481 @code{Character} or @code{Wide_Character}.  The simplest correction
25482 is to make the type explicit; e.g.:
25483 @smallexample @c ada
25484    for Char in Character range 'A' .. 'Z' loop ... end loop;
25485 @end smallexample
25486
25487 @item New reserved words
25488 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25489 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25490 Existing Ada 83 code using any of these identifiers must be edited to
25491 use some alternative name.
25492
25493 @item Freezing rules
25494 The rules in Ada 95 are slightly different with regard to the point at
25495 which entities are frozen, and representation pragmas and clauses are
25496 not permitted past the freeze point.  This shows up most typically in
25497 the form of an error message complaining that a representation item
25498 appears too late, and the appropriate corrective action is to move
25499 the item nearer to the declaration of the entity to which it refers.
25500
25501 A particular case is that representation pragmas
25502 @ifset vms
25503 (including the
25504 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25505 @end ifset
25506 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25507 declaration must be introduced to which the pragma can be applied.
25508
25509 @item Optional bodies for library packages
25510 In Ada 83, a package that did not require a package body was nevertheless
25511 allowed to have one.  This lead to certain surprises in compiling large
25512 systems (situations in which the body could be unexpectedly ignored by the
25513 binder).  In Ada 95, if a package does not require a body then it is not
25514 permitted to have a body.  To fix this problem, simply remove a redundant
25515 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25516 into the spec that makes the body required.  One approach is to add a private
25517 part to the package declaration (if necessary), and define a parameterless
25518 procedure called @code{Requires_Body}, which must then be given a dummy
25519 procedure body in the package body, which then becomes required.
25520 Another approach (assuming that this does not introduce elaboration
25521 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25522 since one effect of this pragma is to require the presence of a package body.
25523
25524 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25525 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25526 @code{Constraint_Error}.
25527 This means that it is illegal to have separate exception handlers for
25528 the two exceptions.  The fix is simply to remove the handler for the
25529 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25530 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25531
25532 @item Indefinite subtypes in generics
25533 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25534 as the actual for a generic formal private type, but then the instantiation
25535 would be illegal if there were any instances of declarations of variables
25536 of this type in the generic body.  In Ada 95, to avoid this clear violation
25537 of the methodological principle known as the ``contract model'',
25538 the generic declaration explicitly indicates whether
25539 or not such instantiations are permitted.  If a generic formal parameter
25540 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25541 type name, then it can be instantiated with indefinite types, but no
25542 stand-alone variables can be declared of this type.  Any attempt to declare
25543 such a variable will result in an illegality at the time the generic is
25544 declared.  If the @code{(<>)} notation is not used, then it is illegal
25545 to instantiate the generic with an indefinite type.
25546 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25547 It will show up as a compile time error, and
25548 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25549 @end table
25550
25551 @node More deterministic semantics
25552 @subsection More deterministic semantics
25553
25554 @table @asis
25555 @item Conversions
25556 Conversions from real types to integer types round away from 0.  In Ada 83
25557 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25558 implementation freedom was intended to support unbiased rounding in
25559 statistical applications, but in practice it interfered with portability.
25560 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25561 is required.  Numeric code may be affected by this change in semantics.
25562 Note, though, that this issue is no worse than already existed in Ada 83
25563 when porting code from one vendor to another.
25564
25565 @item Tasking
25566 The Real-Time Annex introduces a set of policies that define the behavior of
25567 features that were implementation dependent in Ada 83, such as the order in
25568 which open select branches are executed.
25569 @end table
25570
25571 @node Changed semantics
25572 @subsection Changed semantics
25573
25574 @noindent
25575 The worst kind of incompatibility is one where a program that is legal in
25576 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25577 possible in Ada 83.  Fortunately this is extremely rare, but the one
25578 situation that you should be alert to is the change in the predefined type
25579 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25580
25581 @table @asis
25582 @item range of @code{Character}
25583 The range of @code{Standard.Character} is now the full 256 characters
25584 of Latin-1, whereas in most Ada 83 implementations it was restricted
25585 to 128 characters. Although some of the effects of
25586 this change will be manifest in compile-time rejection of legal
25587 Ada 83 programs it is possible for a working Ada 83 program to have
25588 a different effect in Ada 95, one that was not permitted in Ada 83.
25589 As an example, the expression
25590 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25591 delivers @code{255} as its value.
25592 In general, you should look at the logic of any
25593 character-processing Ada 83 program and see whether it needs to be adapted
25594 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25595 character handling package that may be relevant if code needs to be adapted
25596 to account for the additional Latin-1 elements.
25597 The desirable fix is to
25598 modify the program to accommodate the full character set, but in some cases
25599 it may be convenient to define a subtype or derived type of Character that
25600 covers only the restricted range.
25601 @cindex Latin-1
25602 @end table
25603
25604 @node Other language compatibility issues
25605 @subsection Other language compatibility issues
25606 @table @asis
25607 @item @option{-gnat83 switch}
25608 All implementations of GNAT provide a switch that causes GNAT to operate
25609 in Ada 83 mode.  In this mode, some but not all compatibility problems
25610 of the type described above are handled automatically.  For example, the
25611 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25612 However,
25613 in practice, it is usually advisable to make the necessary modifications
25614 to the program to remove the need for using this switch.
25615 See @ref{Compiling Different Versions of Ada}.
25616
25617 @item Support for removed Ada 83 pragmas and attributes
25618 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25619 generally because they have been replaced by other mechanisms.  Ada 95
25620 compilers are allowed, but not required, to implement these missing
25621 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25622 such pragmas and attributes, eliminating this compatibility concern.  These
25623 include @code{pragma Interface} and the floating point type attributes
25624 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25625 @end table
25626
25627 @node Implementation-dependent characteristics
25628 @section Implementation-dependent characteristics
25629 @noindent
25630 Although the Ada language defines the semantics of each construct as
25631 precisely as practical, in some situations (for example for reasons of
25632 efficiency, or where the effect is heavily dependent on the host or target
25633 platform) the implementation is allowed some freedom.  In porting Ada 83
25634 code to GNAT, you need to be aware of whether / how the existing code
25635 exercised such implementation dependencies.  Such characteristics fall into
25636 several categories, and GNAT offers specific support in assisting the
25637 transition from certain Ada 83 compilers.
25638
25639 @menu
25640 * Implementation-defined pragmas::
25641 * Implementation-defined attributes::
25642 * Libraries::
25643 * Elaboration order::
25644 * Target-specific aspects::
25645 @end menu
25646
25647 @node Implementation-defined pragmas
25648 @subsection Implementation-defined pragmas
25649
25650 @noindent
25651 Ada compilers are allowed to supplement the language-defined pragmas, and
25652 these are a potential source of non-portability.  All GNAT-defined pragmas
25653 are described in the GNAT Reference Manual, and these include several that
25654 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25655 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25656 For
25657 compatibility with DEC Ada 83, GNAT supplies the pragmas
25658 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25659 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25660 and @code{Volatile}.
25661 Other relevant pragmas include @code{External} and @code{Link_With}.
25662 Some vendor-specific
25663 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25664 recognized, thus
25665 avoiding compiler rejection of units that contain such pragmas; they are not
25666 relevant in a GNAT context and hence are not otherwise implemented.
25667
25668 @node Implementation-defined attributes
25669 @subsection Implementation-defined attributes
25670
25671 Analogous to pragmas, the set of attributes may be extended by an
25672 implementation.  All GNAT-defined attributes are described in the
25673 @cite{GNAT Reference Manual}, and these include several that are specifically
25674 intended
25675 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25676 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25677 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25678 @code{Type_Class}.
25679
25680 @node Libraries
25681 @subsection Libraries
25682 @noindent
25683 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25684 code uses vendor-specific libraries then there are several ways to manage
25685 this in Ada 95:
25686 @enumerate
25687 @item
25688 If the source code for the libraries (specifications and bodies) are
25689 available, then the libraries can be migrated in the same way as the
25690 application.
25691 @item
25692 If the source code for the specifications but not the bodies are
25693 available, then you can reimplement the bodies.
25694 @item
25695 Some new Ada 95 features obviate the need for library support.  For
25696 example most Ada 83 vendors supplied a package for unsigned integers.  The
25697 Ada 95 modular type feature is the preferred way to handle this need, so
25698 instead of migrating or reimplementing the unsigned integer package it may
25699 be preferable to retrofit the application using modular types.
25700 @end enumerate
25701
25702 @node Elaboration order
25703 @subsection Elaboration order
25704 @noindent
25705 The implementation can choose any elaboration order consistent with the unit
25706 dependency relationship.  This freedom means that some orders can result in
25707 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25708 to invoke a subprogram its body has been elaborated, or to instantiate a
25709 generic before the generic body has been elaborated.  By default GNAT
25710 attempts to choose a safe order (one that will not encounter access before
25711 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25712 needed.  However, this can lead to the creation of elaboration circularities
25713 and a resulting rejection of the program by gnatbind.  This issue is
25714 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25715 In brief, there are several
25716 ways to deal with this situation:
25717
25718 @itemize @bullet
25719 @item
25720 Modify the program to eliminate the circularities, e.g. by moving
25721 elaboration-time code into explicitly-invoked procedures
25722 @item
25723 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25724 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25725 @code{Elaborate_All}
25726 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25727 (by selectively suppressing elaboration checks via pragma
25728 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25729 @end itemize
25730
25731 @node Target-specific aspects
25732 @subsection Target-specific aspects
25733 @noindent
25734 Low-level applications need to deal with machine addresses, data
25735 representations, interfacing with assembler code, and similar issues.  If
25736 such an Ada 83 application is being ported to different target hardware (for
25737 example where the byte endianness has changed) then you will need to
25738 carefully examine the program logic; the porting effort will heavily depend
25739 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25740 incompatible with typical Ada 83 compiler practices regarding implicit
25741 packing, the meaning of the Size attribute, and the size of access values.
25742 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25743
25744 @node Compatibility with Other Ada 95 Systems
25745 @section Compatibility with Other Ada 95 Systems
25746
25747 @noindent
25748 Providing that programs avoid the use of implementation dependent and
25749 implementation defined features of Ada 95, as documented in the Ada 95
25750 reference manual, there should be a high degree of portability between
25751 GNAT and other Ada 95 systems.  The following are specific items which
25752 have proved troublesome in moving GNAT programs to other Ada 95
25753 compilers, but do not affect porting code to GNAT@.
25754
25755 @table @asis
25756 @item Ada 83 Pragmas and Attributes
25757 Ada 95 compilers are allowed, but not required, to implement the missing
25758 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25759 GNAT implements all such pragmas and attributes, eliminating this as
25760 a compatibility concern, but some other Ada 95 compilers reject these
25761 pragmas and attributes.
25762
25763 @item Special-needs Annexes
25764 GNAT implements the full set of special needs annexes.  At the
25765 current time, it is the only Ada 95 compiler to do so.  This means that
25766 programs making use of these features may not be portable to other Ada
25767 95 compilation systems.
25768
25769 @item Representation Clauses
25770 Some other Ada 95 compilers implement only the minimal set of
25771 representation clauses required by the Ada 95 reference manual.  GNAT goes
25772 far beyond this minimal set, as described in the next section.
25773 @end table
25774
25775 @node Representation Clauses
25776 @section Representation Clauses
25777
25778 @noindent
25779 The Ada 83 reference manual was quite vague in describing both the minimal
25780 required implementation of representation clauses, and also their precise
25781 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25782 set of capabilities required in Ada 95 is quite limited.
25783
25784 GNAT implements the full required set of capabilities described in the
25785 Ada 95 reference manual, but also goes much beyond this, and in particular
25786 an effort has been made to be compatible with existing Ada 83 usage to the
25787 greatest extent possible.
25788
25789 A few cases exist in which Ada 83 compiler behavior is incompatible with
25790 requirements in the Ada 95 reference manual.  These are instances of
25791 intentional or accidental dependence on specific implementation dependent
25792 characteristics of these Ada 83 compilers.  The following is a list of
25793 the cases most likely to arise in existing legacy Ada 83 code.
25794
25795 @table @asis
25796 @item Implicit Packing
25797 Some Ada 83 compilers allowed a Size specification to cause implicit
25798 packing of an array or record.  This could cause expensive implicit
25799 conversions for change of representation in the presence of derived
25800 types, and the Ada design intends to avoid this possibility.
25801 Subsequent AI's were issued to make it clear that such implicit
25802 change of representation in response to a Size clause is inadvisable,
25803 and this recommendation is represented explicitly in the Ada 95 RM
25804 as implementation advice that is followed by GNAT@.
25805 The problem will show up as an error
25806 message rejecting the size clause.  The fix is simply to provide
25807 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25808 a Component_Size clause.
25809
25810 @item Meaning of Size Attribute
25811 The Size attribute in Ada 95 for discrete types is defined as being the
25812 minimal number of bits required to hold values of the type.  For example,
25813 on a 32-bit machine, the size of Natural will typically be 31 and not
25814 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25815 some 32 in this situation.  This problem will usually show up as a compile
25816 time error, but not always.  It is a good idea to check all uses of the
25817 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25818 Object_Size can provide a useful way of duplicating the behavior of
25819 some Ada 83 compiler systems.
25820
25821 @item Size of Access Types
25822 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25823 and that therefore it will be the same size as a System.Address value.  This
25824 assumption is true for GNAT in most cases with one exception.  For the case of
25825 a pointer to an unconstrained array type (where the bounds may vary from one
25826 value of the access type to another), the default is to use a ``fat pointer'',
25827 which is represented as two separate pointers, one to the bounds, and one to
25828 the array.  This representation has a number of advantages, including improved
25829 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25830 code which makes the assumption that, for example, pointers fit in 32 bits on
25831 a machine with 32-bit addressing.
25832
25833 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25834 access types in this case (where the designated type is an unconstrained array
25835 type).  These thin pointers are indeed the same size as a System.Address value.
25836 To specify a thin pointer, use a size clause for the type, for example:
25837
25838 @smallexample @c ada
25839 type X is access all String;
25840 for X'Size use Standard'Address_Size;
25841 @end smallexample
25842
25843 @noindent
25844 which will cause the type X to be represented using a single pointer.
25845 When using this representation, the bounds are right behind the array.
25846 This representation is slightly less efficient, and does not allow quite
25847 such flexibility in the use of foreign pointers or in using the
25848 Unrestricted_Access attribute to create pointers to non-aliased objects.
25849 But for any standard portable use of the access type it will work in
25850 a functionally correct manner and allow porting of existing code.
25851 Note that another way of forcing a thin pointer representation
25852 is to use a component size clause for the element size in an array,
25853 or a record representation clause for an access field in a record.
25854 @end table
25855
25856 @node Compatibility with DEC Ada 83
25857 @section Compatibility with DEC Ada 83
25858
25859 @noindent
25860 The VMS version of GNAT fully implements all the pragmas and attributes
25861 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25862 libraries, including Starlet.  In addition, data layouts and parameter
25863 passing conventions are highly compatible.  This means that porting
25864 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25865 most other porting efforts.  The following are some of the most
25866 significant differences between GNAT and DEC Ada 83.
25867
25868 @table @asis
25869 @item Default floating-point representation
25870 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25871 it is VMS format.  GNAT does implement the necessary pragmas
25872 (Long_Float, Float_Representation) for changing this default.
25873
25874 @item System
25875 The package System in GNAT exactly corresponds to the definition in the
25876 Ada 95 reference manual, which means that it excludes many of the
25877 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25878 that contains the additional definitions, and a special pragma,
25879 Extend_System allows this package to be treated transparently as an
25880 extension of package System.
25881
25882 @item To_Address
25883 The definitions provided by Aux_DEC are exactly compatible with those
25884 in the DEC Ada 83 version of System, with one exception.
25885 DEC Ada provides the following declarations:
25886
25887 @smallexample @c ada
25888 TO_ADDRESS (INTEGER)
25889 TO_ADDRESS (UNSIGNED_LONGWORD)
25890 TO_ADDRESS (universal_integer)
25891 @end smallexample
25892
25893 @noindent
25894 The version of TO_ADDRESS taking a universal integer argument is in fact
25895 an extension to Ada 83 not strictly compatible with the reference manual.
25896 In GNAT, we are constrained to be exactly compatible with the standard,
25897 and this means we cannot provide this capability.  In DEC Ada 83, the
25898 point of this definition is to deal with a call like:
25899
25900 @smallexample @c ada
25901 TO_ADDRESS (16#12777#);
25902 @end smallexample
25903
25904 @noindent
25905 Normally, according to the Ada 83 standard, one would expect this to be
25906 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25907 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25908 definition using universal_integer takes precedence.
25909
25910 In GNAT, since the version with universal_integer cannot be supplied, it is
25911 not possible to be 100% compatible.  Since there are many programs using
25912 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25913 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25914 declarations provided in the GNAT version of AUX_Dec are:
25915
25916 @smallexample @c ada
25917 function To_Address (X : Integer) return Address;
25918 pragma Pure_Function (To_Address);
25919
25920 function To_Address_Long (X : Unsigned_Longword)
25921  return Address;
25922 pragma Pure_Function (To_Address_Long);
25923 @end smallexample
25924
25925 @noindent
25926 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25927 change the name to TO_ADDRESS_LONG@.
25928
25929 @item Task_Id values
25930 The Task_Id values assigned will be different in the two systems, and GNAT
25931 does not provide a specified value for the Task_Id of the environment task,
25932 which in GNAT is treated like any other declared task.
25933 @end table
25934
25935 For full details on these and other less significant compatibility issues,
25936 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25937 Overview and Comparison on DIGITAL Platforms}.
25938
25939 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25940 attributes are recognized, although only a subset of them can sensibly
25941 be implemented.  The description of pragmas in this reference manual
25942 indicates whether or not they are applicable to non-VMS systems.
25943
25944
25945 @ifset vms
25946 @node Transitioning from Alpha to Integrity OpenVMS
25947 @section Transitioning from Alpha to Integrity OpenVMS
25948
25949 @menu
25950 * Introduction to transitioning::
25951 * Migration of 32 bit code::
25952 * Taking advantage of 64 bit addressing::
25953 * Technical details::
25954 @end menu
25955
25956 @node Introduction to transitioning
25957 @subsection Introduction to transitioning
25958
25959 @noindent
25960 This guide is meant to assist users of GNAT Pro
25961 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
25962 GNAT Pro for Open VMS Integrity has been designed to meet
25963 three main goals:
25964
25965 @enumerate
25966 @item
25967 Providing a full conforming implementation of the Ada 95 language
25968
25969 @item
25970 Allowing maximum backward compatibility, thus easing migration of existing
25971 Ada source code
25972
25973 @item
25974 Supplying a path for exploiting the full IA64 address range
25975 @end enumerate
25976
25977 @noindent
25978 Ada's strong typing semantics has made it
25979 impractical to have different 32-bit and 64-bit modes. As soon as
25980 one object could possibly be outside the 32-bit address space, this
25981 would make it necessary for the @code{System.Address} type to be 64 bits.
25982 In particular, this would cause inconsistencies if 32-bit code is
25983 called from 64-bit code that raises an exception.
25984
25985 This issue has been resolved by always using 64-bit addressing
25986 at the system level, but allowing for automatic conversions between
25987 32-bit and 64-bit addresses where required. Thus users who
25988 do not currently require 64-bit addressing capabilities, can
25989 recompile their code with only minimal changes (and indeed
25990 if the code is written in portable Ada, with no assumptions about
25991 the size of the @code{Address} type, then no changes at all are necessary).
25992 At the same time,
25993 this approach provides a simple, gradual upgrade path to future
25994 use of larger memories than available for 32-bit systems.
25995 Also, newly written applications or libraries will by default
25996 be fully compatible with future systems exploiting 64-bit
25997 addressing capabilities present in IA64.
25998
25999 @ref{Migration of 32 bit code}, will focus on porting applications
26000 that do not require more than 2 GB of
26001 addressable memory. This code will be referred to as
26002 @emph{32-bit code}.
26003 For applications intending to exploit the full ia64 address space,
26004 @ref{Taking advantage of 64 bit addressing},
26005 will consider further changes that may be required.
26006 Such code is called @emph{64-bit code} in the
26007 remainder of this guide.
26008
26009
26010 @node Migration of 32 bit code
26011 @subsection Migration of 32-bit code
26012
26013 @menu
26014 * Address types::
26015 * Access types::
26016 * Unchecked conversions::
26017 * Predefined constants::
26018 * Single source compatibility::
26019 * Experience with source compatibility::
26020 @end menu
26021
26022 @node Address types
26023 @subsubsection Address types
26024
26025 @noindent
26026 To solve the problem of mixing 64-bit and 32-bit addressing,
26027 while maintaining maximum backward compatibility, the following
26028 approach has been taken:
26029
26030 @itemize @bullet
26031 @item
26032 @code{System.Address} always has a size of 64 bits
26033
26034 @item
26035 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26036 @end itemize
26037
26038
26039 @noindent
26040 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26041 a @code{Short_Address}
26042 may be used where an @code{Address} is required, and vice versa, without
26043 needing explicit type conversions.
26044 By virtue of the Open VMS Integrity parameter passing conventions,
26045 even imported
26046 and exported subprograms that have 32-bit address parameters are
26047 compatible with those that have 64-bit address parameters.
26048 (See @ref{Making code 64 bit clean} for details.)
26049
26050 The areas that may need attention are those where record types have
26051 been defined that contain components of the type @code{System.Address}, and
26052 where objects of this type are passed to code expecting a record layout with
26053 32-bit addresses.
26054
26055 Different compilers on different platforms cannot be
26056 expected to represent the same type in the same way,
26057 since alignment constraints
26058 and other system-dependent properties affect the compiler's decision.
26059 For that reason, Ada code
26060 generally uses representation clauses to specify the expected
26061 layout where required.
26062
26063 If such a representation clause uses 32 bits for a component having
26064 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
26065 that error and produce a specific diagnostic message.
26066 The developer should then determine whether the representation
26067 should be 64 bits or not and make either of two changes:
26068 change the size to 64 bits and leave the type as @code{System.Address}, or
26069 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26070 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26071 required in any code setting or accessing the field; the compiler will
26072 automatically perform any needed conversions between address
26073 formats.
26074
26075 @node Access types
26076 @subsubsection Access types
26077
26078 @noindent
26079 By default, objects designated by access values are always
26080 allocated in the 32-bit
26081 address space. Thus legacy code will never contain
26082 any objects that are not addressable with 32-bit addresses, and
26083 the compiler will never raise exceptions as result of mixing
26084 32-bit and 64-bit addresses.
26085
26086 However, the access values themselves are represented in 64 bits, for optimum
26087 performance and future compatibility with 64-bit code. As was
26088 the case with @code{System.Address}, the compiler will give an error message
26089 if an object or record component has a representation clause that
26090 requires the access value to fit in 32 bits. In such a situation,
26091 an explicit size clause for the access type, specifying 32 bits,
26092 will have the desired effect.
26093
26094 General access types (declared with @code{access all}) can never be
26095 32 bits, as values of such types must be able to refer to any object
26096 of the  designated type,
26097 including objects residing outside the 32-bit address range.
26098 Existing Ada 83 code will not contain such type definitions,
26099 however, since general access types were introduced in Ada 95.
26100
26101 @node Unchecked conversions
26102 @subsubsection Unchecked conversions
26103
26104 @noindent
26105 In the case of an @code{Unchecked_Conversion} where the source type is a
26106 64-bit access type or the type @code{System.Address}, and the target
26107 type is a 32-bit type, the compiler will generate a warning.
26108 Even though the generated code will still perform the required
26109 conversions, it is highly recommended in these cases to use
26110 respectively a 32-bit access type or @code{System.Short_Address}
26111 as the source type.
26112
26113 @node Predefined constants
26114 @subsubsection Predefined constants
26115
26116 @noindent
26117 The following predefined constants have changed:
26118
26119 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26120 @item   @b{Constant}               @tab @b{Old} @tab @b{New}
26121 @item   @code{System.Word_Size}    @tab 32      @tab 64
26122 @item   @code{System.Memory_Size}  @tab 2**32   @tab 2**64
26123 @item   @code{System.Address_Size} @tab 32      @tab 64
26124 @end multitable
26125
26126 @noindent
26127 If you need to refer to the specific
26128 memory size of a 32-bit implementation, instead of the
26129 actual memory size, use @code{System.Short_Memory_Size}
26130 rather than @code{System.Memory_Size}.
26131 Similarly, references to @code{System.Address_Size} may need
26132 to be replaced by @code{System.Short_Address'Size}.
26133 The program @command{gnatfind} may be useful for locating
26134 references to the above constants, so that you can verify that they
26135 are still correct.
26136
26137 @node Single source compatibility
26138 @subsubsection Single source compatibility
26139
26140 @noindent
26141 In order to allow the same source code to be compiled on
26142 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26143 defines @code{System.Short_Address} and System.Short_Memory_Size
26144 as aliases of respectively @code{System.Address} and
26145 @code{System.Memory_Size}.
26146 (These aliases also leave the door open for a possible
26147 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26148
26149 @node Experience with source compatibility
26150 @subsubsection Experience with source compatibility
26151
26152 @noindent
26153 The Security Server and STARLET provide an interesting ``test case''
26154 for source compatibility issues, since it is in such system code
26155 where assumptions about @code{Address} size might be expected to occur.
26156 Indeed, there were a small number of occasions in the Security Server
26157 file @file{jibdef.ads}
26158 where a representation clause for a record type specified
26159 32 bits for a component of type @code{Address}.
26160 All of these errors were detected by the compiler.
26161 The repair was obvious and immediate; to simply replace @code{Address} by
26162 @code{Short_Address}.
26163
26164 In the case of STARLET, there were several record types that should
26165 have had representation clauses but did not.  In these record types
26166 there was an implicit assumption that an @code{Address} value occupied
26167 32 bits.
26168 These compiled without error, but their usage resulted in run-time error
26169 returns from STARLET system calls.
26170 To assist in the compile-time detection of such situations, we
26171 plan to include a switch to generate a warning message when a
26172 record component is of type @code{Address}.
26173
26174
26175 @c ****************************************
26176 @node Taking advantage of 64 bit addressing
26177 @subsection Taking advantage of 64-bit addressing
26178
26179 @menu
26180 * Making code 64 bit clean::
26181 * Allocating memory from the 64 bit storage pool::
26182 * Restrictions on use of 64 bit objects::
26183 * Using 64 bit storage pools by default::
26184 * General access types::
26185 * STARLET and other predefined libraries::
26186 @end menu
26187
26188 @node Making code 64 bit clean
26189 @subsubsection Making code 64-bit clean
26190
26191 @noindent
26192 In order to prevent problems that may occur when (parts of) a
26193 system start using memory outside the 32-bit address range,
26194 we recommend some additional guidelines:
26195
26196 @itemize @bullet
26197 @item
26198 For imported subprograms that take parameters of the
26199 type @code{System.Address}, ensure that these subprograms can
26200 indeed handle 64-bit addresses. If not, or when in doubt,
26201 change the subprogram declaration to specify
26202 @code{System.Short_Address} instead.
26203
26204 @item
26205 Resolve all warnings related to size mismatches in
26206 unchecked conversions. Failing to do so causes
26207 erroneous execution if the source object is outside
26208 the 32-bit address space.
26209
26210 @item
26211 (optional) Explicitly use the 32-bit storage pool
26212 for access types used in a 32-bit context, or use
26213 generic access types where possible
26214 (@pxref{Restrictions on use of 64 bit objects}).
26215 @end itemize
26216
26217 @noindent
26218 If these rules are followed, the compiler will automatically insert
26219 any necessary checks to ensure that no addresses or access values
26220 passed to 32-bit code ever refer to objects outside the 32-bit
26221 address range.
26222 Any attempt to do this will raise @code{Constraint_Error}.
26223
26224 @node Allocating memory from the 64 bit storage pool
26225 @subsubsection Allocating memory from the 64-bit storage pool
26226
26227 @noindent
26228 For any access type @code{T} that potentially requires memory allocations
26229 beyond the 32-bit address space,
26230 use the following representation clause:
26231
26232 @smallexample @c ada
26233    for T'Storage_Pool use System.Pool_64;
26234 @end smallexample
26235
26236
26237 @node Restrictions on use of 64 bit objects
26238 @subsubsection Restrictions on use of 64-bit objects
26239
26240 @noindent
26241 Taking the address of an object allocated from a 64-bit storage pool,
26242 and then passing this address to a subprogram expecting
26243 @code{System.Short_Address},
26244 or assigning it to a variable of type @code{Short_Address}, will cause
26245 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26246 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26247 no exception is raised and execution
26248 will become erroneous.
26249
26250 @node Using 64 bit storage pools by default
26251 @subsubsection Using 64-bit storage pools by default
26252
26253 @noindent
26254 In some cases it may be desirable to have the compiler allocate
26255 from 64-bit storage pools by default. This may be the case for
26256 libraries that are 64-bit clean, but may be used in both 32-bit
26257 and 64-bit contexts. For these cases the following configuration
26258 pragma may be specified:
26259
26260 @smallexample @c ada
26261   pragma Pool_64_Default;
26262 @end smallexample
26263
26264 @noindent
26265 Any code compiled in the context of this pragma will by default
26266 use the @code{System.Pool_64} storage pool. This default may be overridden
26267 for a specific access type @code{T} by the representation clause:
26268
26269 @smallexample @c ada
26270    for T'Storage_Pool use System.Pool_32;
26271 @end smallexample
26272
26273 @noindent
26274 Any object whose address may be passed to a subprogram with a
26275 @code{Short_Address} argument, or assigned to a variable of type
26276 @code{Short_Address}, needs to be allocated from this pool.
26277
26278 @node General access types
26279 @subsubsection General access types
26280
26281 @noindent
26282 Objects designated by access values from a
26283 general access type (declared with @code{access all}) are never allocated
26284 from a 64-bit storage pool. Code that uses general access types will
26285 accept objects allocated in either 32-bit or 64-bit address spaces,
26286 but never allocate objects outside the 32-bit address space.
26287 Using general access types ensures maximum compatibility with both
26288 32-bit and 64-bit code.
26289
26290
26291 @node STARLET and other predefined libraries
26292 @subsubsection STARLET and other predefined libraries
26293
26294 @noindent
26295 All code that comes as part of GNAT is 64-bit clean, but the
26296 restrictions given in @ref{Restrictions on use of 64 bit objects},
26297 still apply. Look at the package
26298 specifications to see in which contexts objects allocated
26299 in 64-bit address space are acceptable.
26300
26301 @node Technical details
26302 @subsection Technical details
26303
26304 @noindent
26305 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
26306 standard with respect to the type of @code{System.Address}. Previous versions
26307 of GNAT Pro have defined this type as private and implemented it as
26308 a modular type.
26309
26310 In order to allow defining @code{System.Short_Address} as a proper subtype,
26311 and to match the implicit sign extension in parameter passing,
26312 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
26313 visible (i.e., non-private) integer type.
26314 Standard operations on the type, such as the binary operators ``+'', ``-'',
26315 etc., that take @code{Address} operands and return an @code{Address} result,
26316 have been hidden by declaring these
26317 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
26318 that would otherwise result from overloading.
26319 (Note that, although @code{Address} is a visible integer type,
26320 good programming practice dictates against exploiting the type's
26321 integer properties such as literals, since this will compromise
26322 code portability.)
26323
26324 Defining @code{Address} as a visible integer type helps achieve
26325 maximum compatibility for existing Ada code,
26326 without sacrificing the capabilities of the IA64 architecture.
26327 @end ifset
26328
26329
26330 @c ************************************************
26331 @ifset unw
26332 @node Microsoft Windows Topics
26333 @appendix Microsoft Windows Topics
26334 @cindex Windows NT
26335 @cindex Windows 95
26336 @cindex Windows 98
26337
26338 @noindent
26339 This chapter describes topics that are specific to the Microsoft Windows
26340 platforms (NT, 2000, and XP Professional).
26341
26342 @menu
26343 * Using GNAT on Windows::
26344 * Using a network installation of GNAT::
26345 * CONSOLE and WINDOWS subsystems::
26346 * Temporary Files::
26347 * Mixed-Language Programming on Windows::
26348 * Windows Calling Conventions::
26349 * Introduction to Dynamic Link Libraries (DLLs)::
26350 * Using DLLs with GNAT::
26351 * Building DLLs with GNAT::
26352 * Building DLLs with GNAT Project files::
26353 * Building DLLs with gnatdll::
26354 * GNAT and Windows Resources::
26355 * Debugging a DLL::
26356 * GNAT and COM/DCOM Objects::
26357 @end menu
26358
26359 @node Using GNAT on Windows
26360 @section Using GNAT on Windows
26361
26362 @noindent
26363 One of the strengths of the GNAT technology is that its tool set
26364 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26365 @code{gdb} debugger, etc.) is used in the same way regardless of the
26366 platform.
26367
26368 On Windows this tool set is complemented by a number of Microsoft-specific
26369 tools that have been provided to facilitate interoperability with Windows
26370 when this is required. With these tools:
26371
26372 @itemize @bullet
26373
26374 @item
26375 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26376 subsystems.
26377
26378 @item
26379 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26380 relocatable and non-relocatable DLLs are supported).
26381
26382 @item
26383 You can build Ada DLLs for use in other applications. These applications
26384 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26385 relocatable and non-relocatable Ada DLLs are supported.
26386
26387 @item
26388 You can include Windows resources in your Ada application.
26389
26390 @item
26391 You can use or create COM/DCOM objects.
26392 @end itemize
26393
26394 @noindent
26395 Immediately below are listed all known general GNAT-for-Windows restrictions.
26396 Other restrictions about specific features like Windows Resources and DLLs
26397 are listed in separate sections below.
26398
26399 @itemize @bullet
26400
26401 @item
26402 It is not possible to use @code{GetLastError} and @code{SetLastError}
26403 when tasking, protected records, or exceptions are used. In these
26404 cases, in order to implement Ada semantics, the GNAT run-time system
26405 calls certain Win32 routines that set the last error variable to 0 upon
26406 success. It should be possible to use @code{GetLastError} and
26407 @code{SetLastError} when tasking, protected record, and exception
26408 features are not used, but it is not guaranteed to work.
26409
26410 @item
26411 It is not possible to link against Microsoft libraries except for
26412 import libraries. The library must be built to be compatible with
26413 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26414 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26415 not be compatible with the GNAT runtime. Even if the library is
26416 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26417
26418 @item
26419 When the compilation environment is located on FAT32 drives, users may
26420 experience recompilations of the source files that have not changed if
26421 Daylight Saving Time (DST) state has changed since the last time files
26422 were compiled. NTFS drives do not have this problem.
26423
26424 @item
26425 No components of the GNAT toolset use any entries in the Windows
26426 registry. The only entries that can be created are file associations and
26427 PATH settings, provided the user has chosen to create them at installation
26428 time, as well as some minimal book-keeping information needed to correctly
26429 uninstall or integrate different GNAT products.
26430 @end itemize
26431
26432 @node Using a network installation of GNAT
26433 @section Using a network installation of GNAT
26434
26435 @noindent
26436 Make sure the system on which GNAT is installed is accessible from the
26437 current machine, i.e. the install location is shared over the network.
26438 Shared resources are accessed on Windows by means of UNC paths, which
26439 have the format @code{\\server\sharename\path}
26440
26441 In order to use such a network installation, simply add the UNC path of the
26442 @file{bin} directory of your GNAT installation in front of your PATH. For
26443 example, if GNAT is installed in @file{\GNAT} directory of a share location
26444 called @file{c-drive} on a machine @file{LOKI}, the following command will
26445 make it available:
26446
26447 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26448
26449 Be aware that every compilation using the network installation results in the
26450 transfer of large amounts of data across the network and will likely cause
26451 serious performance penalty.
26452
26453 @node CONSOLE and WINDOWS subsystems
26454 @section CONSOLE and WINDOWS subsystems
26455 @cindex CONSOLE Subsystem
26456 @cindex WINDOWS Subsystem
26457 @cindex -mwindows
26458
26459 @noindent
26460 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26461 (which is the default subsystem) will always create a console when
26462 launching the application. This is not something desirable when the
26463 application has a Windows GUI. To get rid of this console the
26464 application must be using the @code{WINDOWS} subsystem. To do so
26465 the @option{-mwindows} linker option must be specified.
26466
26467 @smallexample
26468 $ gnatmake winprog -largs -mwindows
26469 @end smallexample
26470
26471 @node Temporary Files
26472 @section Temporary Files
26473 @cindex Temporary files
26474
26475 @noindent
26476 It is possible to control where temporary files gets created by setting
26477 the TMP environment variable. The file will be created:
26478
26479 @itemize
26480 @item Under the directory pointed to by the TMP environment variable if
26481 this directory exists.
26482
26483 @item Under c:\temp, if the TMP environment variable is not set (or not
26484 pointing to a directory) and if this directory exists.
26485
26486 @item Under the current working directory otherwise.
26487 @end itemize
26488
26489 @noindent
26490 This allows you to determine exactly where the temporary
26491 file will be created. This is particularly useful in networked
26492 environments where you may not have write access to some
26493 directories.
26494
26495 @node Mixed-Language Programming on Windows
26496 @section Mixed-Language Programming on Windows
26497
26498 @noindent
26499 Developing pure Ada applications on Windows is no different than on
26500 other GNAT-supported platforms. However, when developing or porting an
26501 application that contains a mix of Ada and C/C++, the choice of your
26502 Windows C/C++ development environment conditions your overall
26503 interoperability strategy.
26504
26505 If you use @command{gcc} to compile the non-Ada part of your application,
26506 there are no Windows-specific restrictions that affect the overall
26507 interoperability with your Ada code. If you plan to use
26508 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26509 the following limitations:
26510
26511 @itemize @bullet
26512 @item
26513 You cannot link your Ada code with an object or library generated with
26514 Microsoft tools if these use the @code{.tls} section (Thread Local
26515 Storage section) since the GNAT linker does not yet support this section.
26516
26517 @item
26518 You cannot link your Ada code with an object or library generated with
26519 Microsoft tools if these use I/O routines other than those provided in
26520 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26521 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26522 libraries can cause a conflict with @code{msvcrt.dll} services. For
26523 instance Visual C++ I/O stream routines conflict with those in
26524 @code{msvcrt.dll}.
26525 @end itemize
26526
26527 @noindent
26528 If you do want to use the Microsoft tools for your non-Ada code and hit one
26529 of the above limitations, you have two choices:
26530
26531 @enumerate
26532 @item
26533 Encapsulate your non Ada code in a DLL to be linked with your Ada
26534 application. In this case, use the Microsoft or whatever environment to
26535 build the DLL and use GNAT to build your executable
26536 (@pxref{Using DLLs with GNAT}).
26537
26538 @item
26539 Or you can encapsulate your Ada code in a DLL to be linked with the
26540 other part of your application. In this case, use GNAT to build the DLL
26541 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26542 environment to build your executable.
26543 @end enumerate
26544
26545 @node Windows Calling Conventions
26546 @section Windows Calling Conventions
26547 @findex Stdcall
26548 @findex APIENTRY
26549
26550 @menu
26551 * C Calling Convention::
26552 * Stdcall Calling Convention::
26553 * DLL Calling Convention::
26554 @end menu
26555
26556 @noindent
26557 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26558 (callee), there are several ways to push @code{G}'s parameters on the
26559 stack and there are several possible scenarios to clean up the stack
26560 upon @code{G}'s return. A calling convention is an agreed upon software
26561 protocol whereby the responsibilities between the caller (@code{F}) and
26562 the callee (@code{G}) are clearly defined. Several calling conventions
26563 are available for Windows:
26564
26565 @itemize @bullet
26566 @item
26567 @code{C} (Microsoft defined)
26568
26569 @item
26570 @code{Stdcall} (Microsoft defined)
26571
26572 @item
26573 @code{DLL} (GNAT specific)
26574 @end itemize
26575
26576 @node C Calling Convention
26577 @subsection @code{C} Calling Convention
26578
26579 @noindent
26580 This is the default calling convention used when interfacing to C/C++
26581 routines compiled with either @command{gcc} or Microsoft Visual C++.
26582
26583 In the @code{C} calling convention subprogram parameters are pushed on the
26584 stack by the caller from right to left. The caller itself is in charge of
26585 cleaning up the stack after the call. In addition, the name of a routine
26586 with @code{C} calling convention is mangled by adding a leading underscore.
26587
26588 The name to use on the Ada side when importing (or exporting) a routine
26589 with @code{C} calling convention is the name of the routine. For
26590 instance the C function:
26591
26592 @smallexample
26593 int get_val (long);
26594 @end smallexample
26595
26596 @noindent
26597 should be imported from Ada as follows:
26598
26599 @smallexample @c ada
26600 @group
26601 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26602 pragma Import (C, Get_Val, External_Name => "get_val");
26603 @end group
26604 @end smallexample
26605
26606 @noindent
26607 Note that in this particular case the @code{External_Name} parameter could
26608 have been omitted since, when missing, this parameter is taken to be the
26609 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26610 is missing, as in the above example, this parameter is set to be the
26611 @code{External_Name} with a leading underscore.
26612
26613 When importing a variable defined in C, you should always use the @code{C}
26614 calling convention unless the object containing the variable is part of a
26615 DLL (in which case you should use the @code{DLL} calling convention,
26616 @pxref{DLL Calling Convention}).
26617
26618 @node Stdcall Calling Convention
26619 @subsection @code{Stdcall} Calling Convention
26620
26621 @noindent
26622 This convention, which was the calling convention used for Pascal
26623 programs, is used by Microsoft for all the routines in the Win32 API for
26624 efficiency reasons. It must be used to import any routine for which this
26625 convention was specified.
26626
26627 In the @code{Stdcall} calling convention subprogram parameters are pushed
26628 on the stack by the caller from right to left. The callee (and not the
26629 caller) is in charge of cleaning the stack on routine exit. In addition,
26630 the name of a routine with @code{Stdcall} calling convention is mangled by
26631 adding a leading underscore (as for the @code{C} calling convention) and a
26632 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26633 bytes) of the parameters passed to the routine.
26634
26635 The name to use on the Ada side when importing a C routine with a
26636 @code{Stdcall} calling convention is the name of the C routine. The leading
26637 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26638 the compiler. For instance the Win32 function:
26639
26640 @smallexample
26641 @b{APIENTRY} int get_val (long);
26642 @end smallexample
26643
26644 @noindent
26645 should be imported from Ada as follows:
26646
26647 @smallexample @c ada
26648 @group
26649 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26650 pragma Import (Stdcall, Get_Val);
26651 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26652 @end group
26653 @end smallexample
26654
26655 @noindent
26656 As for the @code{C} calling convention, when the @code{External_Name}
26657 parameter is missing, it is taken to be the name of the Ada entity in lower
26658 case. If instead of writing the above import pragma you write:
26659
26660 @smallexample @c ada
26661 @group
26662 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26663 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26664 @end group
26665 @end smallexample
26666
26667 @noindent
26668 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26669 of specifying the @code{External_Name} parameter you specify the
26670 @code{Link_Name} as in the following example:
26671
26672 @smallexample @c ada
26673 @group
26674 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26675 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26676 @end group
26677 @end smallexample
26678
26679 @noindent
26680 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26681 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26682 added at the end of the @code{Link_Name} by the compiler.
26683
26684 @noindent
26685 Note, that in some special cases a DLL's entry point name lacks a trailing
26686 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26687 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26688 to handle those cases (@pxref{Using gnatdll} for the description of
26689 the switches).
26690
26691 @node DLL Calling Convention
26692 @subsection @code{DLL} Calling Convention
26693
26694 @noindent
26695 This convention, which is GNAT-specific, must be used when you want to
26696 import in Ada a variables defined in a DLL. For functions and procedures
26697 this convention is equivalent to the @code{Stdcall} convention. As an
26698 example, if a DLL contains a variable defined as:
26699
26700 @smallexample
26701 int my_var;
26702 @end smallexample
26703
26704 @noindent
26705 then, to access this variable from Ada you should write:
26706
26707 @smallexample @c ada
26708 @group
26709 My_Var : Interfaces.C.int;
26710 pragma Import (DLL, My_Var);
26711 @end group
26712 @end smallexample
26713
26714 The remarks concerning the @code{External_Name} and @code{Link_Name}
26715 parameters given in the previous sections equally apply to the @code{DLL}
26716 calling convention.
26717
26718 @node Introduction to Dynamic Link Libraries (DLLs)
26719 @section Introduction to Dynamic Link Libraries (DLLs)
26720 @findex DLL
26721
26722 @noindent
26723 A Dynamically Linked Library (DLL) is a library that can be shared by
26724 several applications running under Windows. A DLL can contain any number of
26725 routines and variables.
26726
26727 One advantage of DLLs is that you can change and enhance them without
26728 forcing all the applications that depend on them to be relinked or
26729 recompiled. However, you should be aware than all calls to DLL routines are
26730 slower since, as you will understand below, such calls are indirect.
26731
26732 To illustrate the remainder of this section, suppose that an application
26733 wants to use the services of a DLL @file{API.dll}. To use the services
26734 provided by @file{API.dll} you must statically link against the DLL or
26735 an import library which contains a jump table with an entry for each
26736 routine and variable exported by the DLL. In the Microsoft world this
26737 import library is called @file{API.lib}. When using GNAT this import
26738 library is called either @file{libAPI.a} or @file{libapi.a} (names are
26739 case insensitive).
26740
26741 After you have linked your application with the DLL or the import library
26742 and you run your application, here is what happens:
26743
26744 @enumerate
26745 @item
26746 Your application is loaded into memory.
26747
26748 @item
26749 The DLL @file{API.dll} is mapped into the address space of your
26750 application. This means that:
26751
26752 @itemize @bullet
26753 @item
26754 The DLL will use the stack of the calling thread.
26755
26756 @item
26757 The DLL will use the virtual address space of the calling process.
26758
26759 @item
26760 The DLL will allocate memory from the virtual address space of the calling
26761 process.
26762
26763 @item
26764 Handles (pointers) can be safely exchanged between routines in the DLL
26765 routines and routines in the application using the DLL.
26766 @end itemize
26767
26768 @item
26769 The entries in the jump table (from the import library @file{libAPI.a}
26770 or @file{API.lib} or automatically created when linking against a DLL)
26771 which is part of your application are initialized with the addresses
26772 of the routines and variables in @file{API.dll}.
26773
26774 @item
26775 If present in @file{API.dll}, routines @code{DllMain} or
26776 @code{DllMainCRTStartup} are invoked. These routines typically contain
26777 the initialization code needed for the well-being of the routines and
26778 variables exported by the DLL.
26779 @end enumerate
26780
26781 @noindent
26782 There is an additional point which is worth mentioning. In the Windows
26783 world there are two kind of DLLs: relocatable and non-relocatable
26784 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26785 in the target application address space. If the addresses of two
26786 non-relocatable DLLs overlap and these happen to be used by the same
26787 application, a conflict will occur and the application will run
26788 incorrectly. Hence, when possible, it is always preferable to use and
26789 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26790 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26791 User's Guide) removes the debugging symbols from the DLL but the DLL can
26792 still be relocated.
26793
26794 As a side note, an interesting difference between Microsoft DLLs and
26795 Unix shared libraries, is the fact that on most Unix systems all public
26796 routines are exported by default in a Unix shared library, while under
26797 Windows it is possible (but not required) to list exported routines in
26798 a definition file (@pxref{The Definition File}).
26799
26800 @node Using DLLs with GNAT
26801 @section Using DLLs with GNAT
26802
26803 @menu
26804 * Creating an Ada Spec for the DLL Services::
26805 * Creating an Import Library::
26806 @end menu
26807
26808 @noindent
26809 To use the services of a DLL, say @file{API.dll}, in your Ada application
26810 you must have:
26811
26812 @enumerate
26813 @item
26814 The Ada spec for the routines and/or variables you want to access in
26815 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26816 header files provided with the DLL.
26817
26818 @item
26819 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26820 mentioned an import library is a statically linked library containing the
26821 import table which will be filled at load time to point to the actual
26822 @file{API.dll} routines. Sometimes you don't have an import library for the
26823 DLL you want to use. The following sections will explain how to build
26824 one. Note that this is optional.
26825
26826 @item
26827 The actual DLL, @file{API.dll}.
26828 @end enumerate
26829
26830 @noindent
26831 Once you have all the above, to compile an Ada application that uses the
26832 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26833 you simply issue the command
26834
26835 @smallexample
26836 $ gnatmake my_ada_app -largs -lAPI
26837 @end smallexample
26838
26839 @noindent
26840 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26841 tells the GNAT linker to look first for a library named @file{API.lib}
26842 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26843 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26844 contains the following pragma
26845
26846 @smallexample @c ada
26847 pragma Linker_Options ("-lAPI");
26848 @end smallexample
26849
26850 @noindent
26851 you do not have to add @option{-largs -lAPI} at the end of the
26852 @command{gnatmake} command.
26853
26854 If any one of the items above is missing you will have to create it
26855 yourself. The following sections explain how to do so using as an
26856 example a fictitious DLL called @file{API.dll}.
26857
26858 @node Creating an Ada Spec for the DLL Services
26859 @subsection Creating an Ada Spec for the DLL Services
26860
26861 @noindent
26862 A DLL typically comes with a C/C++ header file which provides the
26863 definitions of the routines and variables exported by the DLL. The Ada
26864 equivalent of this header file is a package spec that contains definitions
26865 for the imported entities. If the DLL you intend to use does not come with
26866 an Ada spec you have to generate one such spec yourself. For example if
26867 the header file of @file{API.dll} is a file @file{api.h} containing the
26868 following two definitions:
26869
26870 @smallexample
26871 @group
26872 @cartouche
26873 int some_var;
26874 int get (char *);
26875 @end cartouche
26876 @end group
26877 @end smallexample
26878
26879 @noindent
26880 then the equivalent Ada spec could be:
26881
26882 @smallexample @c ada
26883 @group
26884 @cartouche
26885 with Interfaces.C.Strings;
26886 package API is
26887    use Interfaces;
26888
26889    Some_Var : C.int;
26890    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26891
26892 private
26893    pragma Import (C, Get);
26894    pragma Import (DLL, Some_Var);
26895 end API;
26896 @end cartouche
26897 @end group
26898 @end smallexample
26899
26900 @noindent
26901 Note that a variable is @strong{always imported with a DLL convention}. A
26902 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26903 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26904 (@pxref{Windows Calling Conventions}).
26905
26906 @node Creating an Import Library
26907 @subsection Creating an Import Library
26908 @cindex Import library
26909
26910 @menu
26911 * The Definition File::
26912 * GNAT-Style Import Library::
26913 * Microsoft-Style Import Library::
26914 @end menu
26915
26916 @noindent
26917 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26918 import library @file{libAPI.a} is available with @file{API.dll} you
26919 can skip this section. You can also skip this section if
26920 @file{API.dll} is built with GNU tools as in this case it is possible
26921 to link directly against the DLL. Otherwise read on.
26922
26923 @node The Definition File
26924 @subsubsection The Definition File
26925 @cindex Definition file
26926 @findex .def
26927
26928 @noindent
26929 As previously mentioned, and unlike Unix systems, the list of symbols
26930 that are exported from a DLL must be provided explicitly in Windows.
26931 The main goal of a definition file is precisely that: list the symbols
26932 exported by a DLL. A definition file (usually a file with a @code{.def}
26933 suffix) has the following structure:
26934
26935 @smallexample
26936 @group
26937 @cartouche
26938 [LIBRARY @i{name}]
26939 [DESCRIPTION @i{string}]
26940 EXPORTS
26941    @i{symbol1}
26942    @i{symbol2}
26943    ...
26944 @end cartouche
26945 @end group
26946 @end smallexample
26947
26948 @table @code
26949 @item LIBRARY @i{name}
26950 This section, which is optional, gives the name of the DLL.
26951
26952 @item DESCRIPTION @i{string}
26953 This section, which is optional, gives a description string that will be
26954 embedded in the import library.
26955
26956 @item EXPORTS
26957 This section gives the list of exported symbols (procedures, functions or
26958 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26959 section of @file{API.def} looks like:
26960
26961 @smallexample
26962 @group
26963 @cartouche
26964 EXPORTS
26965    some_var
26966    get
26967 @end cartouche
26968 @end group
26969 @end smallexample
26970 @end table
26971
26972 @noindent
26973 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26974 (@pxref{Windows Calling Conventions}) for a Stdcall
26975 calling convention function in the exported symbols list.
26976
26977 @noindent
26978 There can actually be other sections in a definition file, but these
26979 sections are not relevant to the discussion at hand.
26980
26981 @node GNAT-Style Import Library
26982 @subsubsection GNAT-Style Import Library
26983
26984 @noindent
26985 To create a static import library from @file{API.dll} with the GNAT tools
26986 you should proceed as follows:
26987
26988 @enumerate
26989 @item
26990 Create the definition file @file{API.def} (@pxref{The Definition File}).
26991 For that use the @code{dll2def} tool as follows:
26992
26993 @smallexample
26994 $ dll2def API.dll > API.def
26995 @end smallexample
26996
26997 @noindent
26998 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26999 to standard output the list of entry points in the DLL. Note that if
27000 some routines in the DLL have the @code{Stdcall} convention
27001 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27002 suffix then you'll have to edit @file{api.def} to add it, and specify
27003 @code{-k} to @code{gnatdll} when creating the import library.
27004
27005 @noindent
27006 Here are some hints to find the right @code{@@}@i{nn} suffix.
27007
27008 @enumerate
27009 @item
27010 If you have the Microsoft import library (.lib), it is possible to get
27011 the right symbols by using Microsoft @code{dumpbin} tool (see the
27012 corresponding Microsoft documentation for further details).
27013
27014 @smallexample
27015 $ dumpbin /exports api.lib
27016 @end smallexample
27017
27018 @item
27019 If you have a message about a missing symbol at link time the compiler
27020 tells you what symbol is expected. You just have to go back to the
27021 definition file and add the right suffix.
27022 @end enumerate
27023
27024 @item
27025 Build the import library @code{libAPI.a}, using @code{gnatdll}
27026 (@pxref{Using gnatdll}) as follows:
27027
27028 @smallexample
27029 $ gnatdll -e API.def -d API.dll
27030 @end smallexample
27031
27032 @noindent
27033 @code{gnatdll} takes as input a definition file @file{API.def} and the
27034 name of the DLL containing the services listed in the definition file
27035 @file{API.dll}. The name of the static import library generated is
27036 computed from the name of the definition file as follows: if the
27037 definition file name is @i{xyz}@code{.def}, the import library name will
27038 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27039 @option{-e} could have been removed because the name of the definition
27040 file (before the ``@code{.def}'' suffix) is the same as the name of the
27041 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27042 @end enumerate
27043
27044 @node Microsoft-Style Import Library
27045 @subsubsection Microsoft-Style Import Library
27046
27047 @noindent
27048 With GNAT you can either use a GNAT-style or Microsoft-style import
27049 library. A Microsoft import library is needed only if you plan to make an
27050 Ada DLL available to applications developed with Microsoft
27051 tools (@pxref{Mixed-Language Programming on Windows}).
27052
27053 To create a Microsoft-style import library for @file{API.dll} you
27054 should proceed as follows:
27055
27056 @enumerate
27057 @item
27058 Create the definition file @file{API.def} from the DLL. For this use either
27059 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27060 tool (see the corresponding Microsoft documentation for further details).
27061
27062 @item
27063 Build the actual import library using Microsoft's @code{lib} utility:
27064
27065 @smallexample
27066 $ lib -machine:IX86 -def:API.def -out:API.lib
27067 @end smallexample
27068
27069 @noindent
27070 If you use the above command the definition file @file{API.def} must
27071 contain a line giving the name of the DLL:
27072
27073 @smallexample
27074 LIBRARY      "API"
27075 @end smallexample
27076
27077 @noindent
27078 See the Microsoft documentation for further details about the usage of
27079 @code{lib}.
27080 @end enumerate
27081
27082 @node Building DLLs with GNAT
27083 @section Building DLLs with GNAT
27084 @cindex DLLs, building
27085
27086 @noindent
27087 This section explain how to build DLLs using the GNAT built-in DLL
27088 support. With the following procedure it is straight forward to build
27089 and use DLLs with GNAT.
27090
27091 @enumerate
27092
27093 @item building object files
27094
27095 The first step is to build all objects files that are to be included
27096 into the DLL. This is done by using the standard @command{gnatmake} tool.
27097
27098 @item building the DLL
27099
27100 To build the DLL you must use @command{gcc}'s @code{-shared}
27101 option. It is quite simple to use this method:
27102
27103 @smallexample
27104 $ gcc -shared -o api.dll obj1.o obj2.o ...
27105 @end smallexample
27106
27107 It is important to note that in this case all symbols found in the
27108 object files are automatically exported. It is possible to restrict
27109 the set of symbols to export by passing to @command{gcc} a definition
27110 file, @pxref{The Definition File}. For example:
27111
27112 @smallexample
27113 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27114 @end smallexample
27115
27116 If you use a definition file you must export the elaboration procedures
27117 for every package that required one. Elaboration procedures are named
27118 using the package name followed by "_E".
27119
27120 @item preparing DLL to be used
27121
27122 For the DLL to be used by client programs the bodies must be hidden
27123 from it and the .ali set with read-only attribute. This is very important
27124 otherwise GNAT will recompile all packages and will not actually use
27125 the code in the DLL. For example:
27126
27127 @smallexample
27128 $ mkdir apilib
27129 $ copy *.ads *.ali api.dll apilib
27130 $ attrib +R apilib\*.ali
27131 @end smallexample
27132
27133 @end enumerate
27134
27135 At this point it is possible to use the DLL by directly linking
27136 against it. Note that you must use the GNAT shared runtime when using
27137 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27138 option.
27139
27140 @smallexample
27141 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27142 @end smallexample
27143
27144 @node Building DLLs with GNAT Project files
27145 @section Building DLLs with GNAT Project files
27146 @cindex DLLs, building
27147
27148 @noindent
27149 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27150
27151 @node Building DLLs with gnatdll
27152 @section Building DLLs with gnatdll
27153 @cindex DLLs, building
27154
27155 @menu
27156 * Limitations When Using Ada DLLs from Ada::
27157 * Exporting Ada Entities::
27158 * Ada DLLs and Elaboration::
27159 * Ada DLLs and Finalization::
27160 * Creating a Spec for Ada DLLs::
27161 * Creating the Definition File::
27162 * Using gnatdll::
27163 @end menu
27164
27165 @noindent
27166 Note that it is preferred to use the built-in GNAT DLL support
27167 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27168 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27169
27170 This section explains how to build DLLs containing Ada code using
27171 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27172 remainder of this section.
27173
27174 The steps required to build an Ada DLL that is to be used by Ada as well as
27175 non-Ada applications are as follows:
27176
27177 @enumerate
27178 @item
27179 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27180 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27181 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27182 skip this step if you plan to use the Ada DLL only from Ada applications.
27183
27184 @item
27185 Your Ada code must export an initialization routine which calls the routine
27186 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27187 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27188 routine exported by the Ada DLL must be invoked by the clients of the DLL
27189 to initialize the DLL.
27190
27191 @item
27192 When useful, the DLL should also export a finalization routine which calls
27193 routine @code{adafinal} generated by @command{gnatbind} to perform the
27194 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27195 The finalization routine exported by the Ada DLL must be invoked by the
27196 clients of the DLL when the DLL services are no further needed.
27197
27198 @item
27199 You must provide a spec for the services exported by the Ada DLL in each
27200 of the programming languages to which you plan to make the DLL available.
27201
27202 @item
27203 You must provide a definition file listing the exported entities
27204 (@pxref{The Definition File}).
27205
27206 @item
27207 Finally you must use @code{gnatdll} to produce the DLL and the import
27208 library (@pxref{Using gnatdll}).
27209 @end enumerate
27210
27211 @noindent
27212 Note that a relocatable DLL stripped using the @code{strip} binutils
27213 tool will not be relocatable anymore. To build a DLL without debug
27214 information pass @code{-largs -s} to @code{gnatdll}.
27215
27216 @node Limitations When Using Ada DLLs from Ada
27217 @subsection Limitations When Using Ada DLLs from Ada
27218
27219 @noindent
27220 When using Ada DLLs from Ada applications there is a limitation users
27221 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27222 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27223 each Ada DLL includes the services of the GNAT run time that are necessary
27224 to the Ada code inside the DLL. As a result, when an Ada program uses an
27225 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27226 one in the main program.
27227
27228 It is therefore not possible to exchange GNAT run-time objects between the
27229 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27230 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27231 types, etc.
27232
27233 It is completely safe to exchange plain elementary, array or record types,
27234 Windows object handles, etc.
27235
27236 @node Exporting Ada Entities
27237 @subsection Exporting Ada Entities
27238 @cindex Export table
27239
27240 @noindent
27241 Building a DLL is a way to encapsulate a set of services usable from any
27242 application. As a result, the Ada entities exported by a DLL should be
27243 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27244 any Ada name mangling. Please note that the @code{Stdcall} convention
27245 should only be used for subprograms, not for variables. As an example here
27246 is an Ada package @code{API}, spec and body, exporting two procedures, a
27247 function, and a variable:
27248
27249 @smallexample @c ada
27250 @group
27251 @cartouche
27252 with Interfaces.C; use Interfaces;
27253 package API is
27254    Count : C.int := 0;
27255    function Factorial (Val : C.int) return C.int;
27256
27257    procedure Initialize_API;
27258    procedure Finalize_API;
27259    --  Initialization & Finalization routines. More in the next section.
27260 private
27261    pragma Export (C, Initialize_API);
27262    pragma Export (C, Finalize_API);
27263    pragma Export (C, Count);
27264    pragma Export (C, Factorial);
27265 end API;
27266 @end cartouche
27267 @end group
27268 @end smallexample
27269
27270 @smallexample @c ada
27271 @group
27272 @cartouche
27273 package body API is
27274    function Factorial (Val : C.int) return C.int is
27275       Fact : C.int := 1;
27276    begin
27277       Count := Count + 1;
27278       for K in 1 .. Val loop
27279          Fact := Fact * K;
27280       end loop;
27281       return Fact;
27282    end Factorial;
27283
27284    procedure Initialize_API is
27285       procedure Adainit;
27286       pragma Import (C, Adainit);
27287    begin
27288       Adainit;
27289    end Initialize_API;
27290
27291    procedure Finalize_API is
27292       procedure Adafinal;
27293       pragma Import (C, Adafinal);
27294    begin
27295       Adafinal;
27296    end Finalize_API;
27297 end API;
27298 @end cartouche
27299 @end group
27300 @end smallexample
27301
27302 @noindent
27303 If the Ada DLL you are building will only be used by Ada applications
27304 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27305 convention. As an example, the previous package could be written as
27306 follows:
27307
27308 @smallexample @c ada
27309 @group
27310 @cartouche
27311 package API is
27312    Count : Integer := 0;
27313    function Factorial (Val : Integer) return Integer;
27314
27315    procedure Initialize_API;
27316    procedure Finalize_API;
27317    --  Initialization and Finalization routines.
27318 end API;
27319 @end cartouche
27320 @end group
27321 @end smallexample
27322
27323 @smallexample @c ada
27324 @group
27325 @cartouche
27326 package body API is
27327    function Factorial (Val : Integer) return Integer is
27328       Fact : Integer := 1;
27329    begin
27330       Count := Count + 1;
27331       for K in 1 .. Val loop
27332          Fact := Fact * K;
27333       end loop;
27334       return Fact;
27335    end Factorial;
27336
27337    ...
27338    --  The remainder of this package body is unchanged.
27339 end API;
27340 @end cartouche
27341 @end group
27342 @end smallexample
27343
27344 @noindent
27345 Note that if you do not export the Ada entities with a @code{C} or
27346 @code{Stdcall} convention you will have to provide the mangled Ada names
27347 in the definition file of the Ada DLL
27348 (@pxref{Creating the Definition File}).
27349
27350 @node Ada DLLs and Elaboration
27351 @subsection Ada DLLs and Elaboration
27352 @cindex DLLs and elaboration
27353
27354 @noindent
27355 The DLL that you are building contains your Ada code as well as all the
27356 routines in the Ada library that are needed by it. The first thing a
27357 user of your DLL must do is elaborate the Ada code
27358 (@pxref{Elaboration Order Handling in GNAT}).
27359
27360 To achieve this you must export an initialization routine
27361 (@code{Initialize_API} in the previous example), which must be invoked
27362 before using any of the DLL services. This elaboration routine must call
27363 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27364 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27365 @code{Initialize_Api} for an example. Note that the GNAT binder is
27366 automatically invoked during the DLL build process by the @code{gnatdll}
27367 tool (@pxref{Using gnatdll}).
27368
27369 When a DLL is loaded, Windows systematically invokes a routine called
27370 @code{DllMain}. It would therefore be possible to call @code{adainit}
27371 directly from @code{DllMain} without having to provide an explicit
27372 initialization routine. Unfortunately, it is not possible to call
27373 @code{adainit} from the @code{DllMain} if your program has library level
27374 tasks because access to the @code{DllMain} entry point is serialized by
27375 the system (that is, only a single thread can execute ``through'' it at a
27376 time), which means that the GNAT run time will deadlock waiting for the
27377 newly created task to complete its initialization.
27378
27379 @node Ada DLLs and Finalization
27380 @subsection Ada DLLs and Finalization
27381 @cindex DLLs and finalization
27382
27383 @noindent
27384 When the services of an Ada DLL are no longer needed, the client code should
27385 invoke the DLL finalization routine, if available. The DLL finalization
27386 routine is in charge of releasing all resources acquired by the DLL. In the
27387 case of the Ada code contained in the DLL, this is achieved by calling
27388 routine @code{adafinal} generated by the GNAT binder
27389 (@pxref{Binding with Non-Ada Main Programs}).
27390 See the body of @code{Finalize_Api} for an
27391 example. As already pointed out the GNAT binder is automatically invoked
27392 during the DLL build process by the @code{gnatdll} tool
27393 (@pxref{Using gnatdll}).
27394
27395 @node Creating a Spec for Ada DLLs
27396 @subsection Creating a Spec for Ada DLLs
27397
27398 @noindent
27399 To use the services exported by the Ada DLL from another programming
27400 language (e.g. C), you have to translate the specs of the exported Ada
27401 entities in that language. For instance in the case of @code{API.dll},
27402 the corresponding C header file could look like:
27403
27404 @smallexample
27405 @group
27406 @cartouche
27407 extern int *_imp__count;
27408 #define count (*_imp__count)
27409 int factorial (int);
27410 @end cartouche
27411 @end group
27412 @end smallexample
27413
27414 @noindent
27415 It is important to understand that when building an Ada DLL to be used by
27416 other Ada applications, you need two different specs for the packages
27417 contained in the DLL: one for building the DLL and the other for using
27418 the DLL. This is because the @code{DLL} calling convention is needed to
27419 use a variable defined in a DLL, but when building the DLL, the variable
27420 must have either the @code{Ada} or @code{C} calling convention. As an
27421 example consider a DLL comprising the following package @code{API}:
27422
27423 @smallexample @c ada
27424 @group
27425 @cartouche
27426 package API is
27427    Count : Integer := 0;
27428    ...
27429    --  Remainder of the package omitted.
27430 end API;
27431 @end cartouche
27432 @end group
27433 @end smallexample
27434
27435 @noindent
27436 After producing a DLL containing package @code{API}, the spec that
27437 must be used to import @code{API.Count} from Ada code outside of the
27438 DLL is:
27439
27440 @smallexample @c ada
27441 @group
27442 @cartouche
27443 package API is
27444    Count : Integer;
27445    pragma Import (DLL, Count);
27446 end API;
27447 @end cartouche
27448 @end group
27449 @end smallexample
27450
27451 @node Creating the Definition File
27452 @subsection Creating the Definition File
27453
27454 @noindent
27455 The definition file is the last file needed to build the DLL. It lists
27456 the exported symbols. As an example, the definition file for a DLL
27457 containing only package @code{API} (where all the entities are exported
27458 with a @code{C} calling convention) is:
27459
27460 @smallexample
27461 @group
27462 @cartouche
27463 EXPORTS
27464     count
27465     factorial
27466     finalize_api
27467     initialize_api
27468 @end cartouche
27469 @end group
27470 @end smallexample
27471
27472 @noindent
27473 If the @code{C} calling convention is missing from package @code{API},
27474 then the definition file contains the mangled Ada names of the above
27475 entities, which in this case are:
27476
27477 @smallexample
27478 @group
27479 @cartouche
27480 EXPORTS
27481     api__count
27482     api__factorial
27483     api__finalize_api
27484     api__initialize_api
27485 @end cartouche
27486 @end group
27487 @end smallexample
27488
27489 @node Using gnatdll
27490 @subsection Using @code{gnatdll}
27491 @findex gnatdll
27492
27493 @menu
27494 * gnatdll Example::
27495 * gnatdll behind the Scenes::
27496 * Using dlltool::
27497 @end menu
27498
27499 @noindent
27500 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27501 and non-Ada sources that make up your DLL have been compiled.
27502 @code{gnatdll} is actually in charge of two distinct tasks: build the
27503 static import library for the DLL and the actual DLL. The form of the
27504 @code{gnatdll} command is
27505
27506 @smallexample
27507 @cartouche
27508 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27509 @end cartouche
27510 @end smallexample
27511
27512 @noindent
27513 where @i{list-of-files} is a list of ALI and object files. The object
27514 file list must be the exact list of objects corresponding to the non-Ada
27515 sources whose services are to be included in the DLL. The ALI file list
27516 must be the exact list of ALI files for the corresponding Ada sources
27517 whose services are to be included in the DLL. If @i{list-of-files} is
27518 missing, only the static import library is generated.
27519
27520 @noindent
27521 You may specify any of the following switches to @code{gnatdll}:
27522
27523 @table @code
27524 @item -a[@var{address}]
27525 @cindex @option{-a} (@code{gnatdll})
27526 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27527 specified the default address @var{0x11000000} will be used. By default,
27528 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27529 advise the reader to build relocatable DLL.
27530
27531 @item -b @var{address}
27532 @cindex @option{-b} (@code{gnatdll})
27533 Set the relocatable DLL base address. By default the address is
27534 @var{0x11000000}.
27535
27536 @item -bargs @var{opts}
27537 @cindex @option{-bargs} (@code{gnatdll})
27538 Binder options. Pass @var{opts} to the binder.
27539
27540 @item -d @var{dllfile}
27541 @cindex @option{-d} (@code{gnatdll})
27542 @var{dllfile} is the name of the DLL. This switch must be present for
27543 @code{gnatdll} to do anything. The name of the generated import library is
27544 obtained algorithmically from @var{dllfile} as shown in the following
27545 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27546 @code{libxyz.a}. The name of the definition file to use (if not specified
27547 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27548 as shown in the following example:
27549 if @var{dllfile} is @code{xyz.dll}, the definition
27550 file used is @code{xyz.def}.
27551
27552 @item -e @var{deffile}
27553 @cindex @option{-e} (@code{gnatdll})
27554 @var{deffile} is the name of the definition file.
27555
27556 @item -g
27557 @cindex @option{-g} (@code{gnatdll})
27558 Generate debugging information. This information is stored in the object
27559 file and copied from there to the final DLL file by the linker,
27560 where it can be read by the debugger. You must use the
27561 @option{-g} switch if you plan on using the debugger or the symbolic
27562 stack traceback.
27563
27564 @item -h
27565 @cindex @option{-h} (@code{gnatdll})
27566 Help mode. Displays @code{gnatdll} switch usage information.
27567
27568 @item -Idir
27569 @cindex @option{-I} (@code{gnatdll})
27570 Direct @code{gnatdll} to search the @var{dir} directory for source and
27571 object files needed to build the DLL.
27572 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27573
27574 @item -k
27575 @cindex @option{-k} (@code{gnatdll})
27576 Removes the @code{@@}@i{nn} suffix from the import library's exported
27577 names, but keeps them for the link names. You must specify this
27578 option if you want to use a @code{Stdcall} function in a DLL for which
27579 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27580 of the Windows NT DLL for example. This option has no effect when
27581 @option{-n} option is specified.
27582
27583 @item -l @var{file}
27584 @cindex @option{-l} (@code{gnatdll})
27585 The list of ALI and object files used to build the DLL are listed in
27586 @var{file}, instead of being given in the command line. Each line in
27587 @var{file} contains the name of an ALI or object file.
27588
27589 @item -n
27590 @cindex @option{-n} (@code{gnatdll})
27591 No Import. Do not create the import library.
27592
27593 @item -q
27594 @cindex @option{-q} (@code{gnatdll})
27595 Quiet mode. Do not display unnecessary messages.
27596
27597 @item -v
27598 @cindex @option{-v} (@code{gnatdll})
27599 Verbose mode. Display extra information.
27600
27601 @item -largs @var{opts}
27602 @cindex @option{-largs} (@code{gnatdll})
27603 Linker options. Pass @var{opts} to the linker.
27604 @end table
27605
27606 @node gnatdll Example
27607 @subsubsection @code{gnatdll} Example
27608
27609 @noindent
27610 As an example the command to build a relocatable DLL from @file{api.adb}
27611 once @file{api.adb} has been compiled and @file{api.def} created is
27612
27613 @smallexample
27614 $ gnatdll -d api.dll api.ali
27615 @end smallexample
27616
27617 @noindent
27618 The above command creates two files: @file{libapi.a} (the import
27619 library) and @file{api.dll} (the actual DLL). If you want to create
27620 only the DLL, just type:
27621
27622 @smallexample
27623 $ gnatdll -d api.dll -n api.ali
27624 @end smallexample
27625
27626 @noindent
27627 Alternatively if you want to create just the import library, type:
27628
27629 @smallexample
27630 $ gnatdll -d api.dll
27631 @end smallexample
27632
27633 @node gnatdll behind the Scenes
27634 @subsubsection @code{gnatdll} behind the Scenes
27635
27636 @noindent
27637 This section details the steps involved in creating a DLL. @code{gnatdll}
27638 does these steps for you. Unless you are interested in understanding what
27639 goes on behind the scenes, you should skip this section.
27640
27641 We use the previous example of a DLL containing the Ada package @code{API},
27642 to illustrate the steps necessary to build a DLL. The starting point is a
27643 set of objects that will make up the DLL and the corresponding ALI
27644 files. In the case of this example this means that @file{api.o} and
27645 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27646 the following:
27647
27648 @enumerate
27649 @item
27650 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27651 the information necessary to generate relocation information for the
27652 DLL.
27653
27654 @smallexample
27655 @group
27656 $ gnatbind -n api
27657 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27658 @end group
27659 @end smallexample
27660
27661 @noindent
27662 In addition to the base file, the @command{gnatlink} command generates an
27663 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27664 asks @command{gnatlink} to generate the routines @code{DllMain} and
27665 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27666 is loaded into memory.
27667
27668 @item
27669 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27670 export table (@file{api.exp}). The export table contains the relocation
27671 information in a form which can be used during the final link to ensure
27672 that the Windows loader is able to place the DLL anywhere in memory.
27673
27674 @smallexample
27675 @group
27676 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27677           --output-exp api.exp
27678 @end group
27679 @end smallexample
27680
27681 @item
27682 @code{gnatdll} builds the base file using the new export table. Note that
27683 @command{gnatbind} must be called once again since the binder generated file
27684 has been deleted during the previous call to @command{gnatlink}.
27685
27686 @smallexample
27687 @group
27688 $ gnatbind -n api
27689 $ gnatlink api -o api.jnk api.exp -mdll
27690       -Wl,--base-file,api.base
27691 @end group
27692 @end smallexample
27693
27694 @item
27695 @code{gnatdll} builds the new export table using the new base file and
27696 generates the DLL import library @file{libAPI.a}.
27697
27698 @smallexample
27699 @group
27700 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27701           --output-exp api.exp --output-lib libAPI.a
27702 @end group
27703 @end smallexample
27704
27705 @item
27706 Finally @code{gnatdll} builds the relocatable DLL using the final export
27707 table.
27708
27709 @smallexample
27710 @group
27711 $ gnatbind -n api
27712 $ gnatlink api api.exp -o api.dll -mdll
27713 @end group
27714 @end smallexample
27715 @end enumerate
27716
27717 @node Using dlltool
27718 @subsubsection Using @code{dlltool}
27719
27720 @noindent
27721 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27722 DLLs and static import libraries. This section summarizes the most
27723 common @code{dlltool} switches. The form of the @code{dlltool} command
27724 is
27725
27726 @smallexample
27727 $ dlltool [@var{switches}]
27728 @end smallexample
27729
27730 @noindent
27731 @code{dlltool} switches include:
27732
27733 @table @option
27734 @item --base-file @var{basefile}
27735 @cindex @option{--base-file} (@command{dlltool})
27736 Read the base file @var{basefile} generated by the linker. This switch
27737 is used to create a relocatable DLL.
27738
27739 @item --def @var{deffile}
27740 @cindex @option{--def} (@command{dlltool})
27741 Read the definition file.
27742
27743 @item --dllname @var{name}
27744 @cindex @option{--dllname} (@command{dlltool})
27745 Gives the name of the DLL. This switch is used to embed the name of the
27746 DLL in the static import library generated by @code{dlltool} with switch
27747 @option{--output-lib}.
27748
27749 @item -k
27750 @cindex @option{-k} (@command{dlltool})
27751 Kill @code{@@}@i{nn} from exported names
27752 (@pxref{Windows Calling Conventions}
27753 for a discussion about @code{Stdcall}-style symbols.
27754
27755 @item --help
27756 @cindex @option{--help} (@command{dlltool})
27757 Prints the @code{dlltool} switches with a concise description.
27758
27759 @item --output-exp @var{exportfile}
27760 @cindex @option{--output-exp} (@command{dlltool})
27761 Generate an export file @var{exportfile}. The export file contains the
27762 export table (list of symbols in the DLL) and is used to create the DLL.
27763
27764 @item --output-lib @i{libfile}
27765 @cindex @option{--output-lib} (@command{dlltool})
27766 Generate a static import library @var{libfile}.
27767
27768 @item -v
27769 @cindex @option{-v} (@command{dlltool})
27770 Verbose mode.
27771
27772 @item --as @i{assembler-name}
27773 @cindex @option{--as} (@command{dlltool})
27774 Use @i{assembler-name} as the assembler. The default is @code{as}.
27775 @end table
27776
27777 @node GNAT and Windows Resources
27778 @section GNAT and Windows Resources
27779 @cindex Resources, windows
27780
27781 @menu
27782 * Building Resources::
27783 * Compiling Resources::
27784 * Using Resources::
27785 @end menu
27786
27787 @noindent
27788 Resources are an easy way to add Windows specific objects to your
27789 application. The objects that can be added as resources include:
27790
27791 @itemize @bullet
27792 @item
27793 menus
27794
27795 @item
27796 accelerators
27797
27798 @item
27799 dialog boxes
27800
27801 @item
27802 string tables
27803
27804 @item
27805 bitmaps
27806
27807 @item
27808 cursors
27809
27810 @item
27811 icons
27812
27813 @item
27814 fonts
27815 @end itemize
27816
27817 @noindent
27818 This section explains how to build, compile and use resources.
27819
27820 @node Building Resources
27821 @subsection Building Resources
27822 @cindex Resources, building
27823
27824 @noindent
27825 A resource file is an ASCII file. By convention resource files have an
27826 @file{.rc} extension.
27827 The easiest way to build a resource file is to use Microsoft tools
27828 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27829 @code{dlgedit.exe} to build dialogs.
27830 It is always possible to build an @file{.rc} file yourself by writing a
27831 resource script.
27832
27833 It is not our objective to explain how to write a resource file. A
27834 complete description of the resource script language can be found in the
27835 Microsoft documentation.
27836
27837 @node Compiling Resources
27838 @subsection Compiling Resources
27839 @findex rc
27840 @findex windres
27841 @cindex Resources, compiling
27842
27843 @noindent
27844 This section describes how to build a GNAT-compatible (COFF) object file
27845 containing the resources. This is done using the Resource Compiler
27846 @code{windres} as follows:
27847
27848 @smallexample
27849 $ windres -i myres.rc -o myres.o
27850 @end smallexample
27851
27852 @noindent
27853 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
27854 file. You can specify an alternate preprocessor (usually named
27855 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27856 parameter. A list of all possible options may be obtained by entering
27857 the command @code{windres} @option{--help}.
27858
27859 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27860 to produce a @file{.res} file (binary resource file). See the
27861 corresponding Microsoft documentation for further details. In this case
27862 you need to use @code{windres} to translate the @file{.res} file to a
27863 GNAT-compatible object file as follows:
27864
27865 @smallexample
27866 $ windres -i myres.res -o myres.o
27867 @end smallexample
27868
27869 @node Using Resources
27870 @subsection Using Resources
27871 @cindex Resources, using
27872
27873 @noindent
27874 To include the resource file in your program just add the
27875 GNAT-compatible object file for the resource(s) to the linker
27876 arguments. With @command{gnatmake} this is done by using the @option{-largs}
27877 option:
27878
27879 @smallexample
27880 $ gnatmake myprog -largs myres.o
27881 @end smallexample
27882
27883 @node Debugging a DLL
27884 @section Debugging a DLL
27885 @cindex DLL debugging
27886
27887 @menu
27888 * Program and DLL Both Built with GCC/GNAT::
27889 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27890 @end menu
27891
27892 @noindent
27893 Debugging a DLL is similar to debugging a standard program. But
27894 we have to deal with two different executable parts: the DLL and the
27895 program that uses it. We have the following four possibilities:
27896
27897 @enumerate 1
27898 @item
27899 The program and the DLL are built with @code{GCC/GNAT}.
27900 @item
27901 The program is built with foreign tools and the DLL is built with
27902 @code{GCC/GNAT}.
27903 @item
27904 The program is built with @code{GCC/GNAT} and the DLL is built with
27905 foreign tools.
27906 @item
27907 @end enumerate
27908
27909 @noindent
27910 In this section we address only cases one and two above.
27911 There is no point in trying to debug
27912 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27913 information in it. To do so you must use a debugger compatible with the
27914 tools suite used to build the DLL.
27915
27916 @node Program and DLL Both Built with GCC/GNAT
27917 @subsection Program and DLL Both Built with GCC/GNAT
27918
27919 @noindent
27920 This is the simplest case. Both the DLL and the program have @code{GDB}
27921 compatible debugging information. It is then possible to break anywhere in
27922 the process. Let's suppose here that the main procedure is named
27923 @code{ada_main} and that in the DLL there is an entry point named
27924 @code{ada_dll}.
27925
27926 @noindent
27927 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27928 program must have been built with the debugging information (see GNAT -g
27929 switch). Here are the step-by-step instructions for debugging it:
27930
27931 @enumerate 1
27932 @item Launch @code{GDB} on the main program.
27933
27934 @smallexample
27935 $ gdb -nw ada_main
27936 @end smallexample
27937
27938 @item Break on the main procedure and run the program.
27939
27940 @smallexample
27941 (gdb) break ada_main
27942 (gdb) run
27943 @end smallexample
27944
27945 @noindent
27946 This step is required to be able to set a breakpoint inside the DLL. As long
27947 as the program is not run, the DLL is not loaded. This has the
27948 consequence that the DLL debugging information is also not loaded, so it is not
27949 possible to set a breakpoint in the DLL.
27950
27951 @item Set a breakpoint inside the DLL
27952
27953 @smallexample
27954 (gdb) break ada_dll
27955 (gdb) run
27956 @end smallexample
27957
27958 @end enumerate
27959
27960 @noindent
27961 At this stage a breakpoint is set inside the DLL. From there on
27962 you can use the standard approach to debug the whole program
27963 (@pxref{Running and Debugging Ada Programs}).
27964
27965 To break on the @code{DllMain} routine it is not possible to follow
27966 the procedure above. At the time the program stop on @code{ada_main}
27967 the @code{DllMain} routine as already been called. Either you can use
27968 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
27969
27970 @enumerate 1
27971 @item Launch @code{GDB} on the main program.
27972
27973 @smallexample
27974 $ gdb -nw ada_main
27975 @end smallexample
27976
27977 @item Load DLL symbols
27978
27979 @smallexample
27980 (gdb) add-sym api.dll
27981 @end smallexample
27982
27983 @item Set a breakpoint inside the DLL
27984
27985 @smallexample
27986 (gdb) break ada_dll.adb:45
27987 @end smallexample
27988
27989 Note that at this point it is not possible to break using the routine symbol
27990 directly as the program is not yet running. The solution is to break
27991 on the proper line (break in @file{ada_dll.adb} line 45).
27992
27993 @item Start the program
27994
27995 @smallexample
27996 (gdb) run
27997 @end smallexample
27998
27999 @end enumerate
28000
28001 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28002 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28003
28004 @menu
28005 * Debugging the DLL Directly::
28006 * Attaching to a Running Process::
28007 @end menu
28008
28009 @noindent
28010 In this case things are slightly more complex because it is not possible to
28011 start the main program and then break at the beginning to load the DLL and the
28012 associated DLL debugging information. It is not possible to break at the
28013 beginning of the program because there is no @code{GDB} debugging information,
28014 and therefore there is no direct way of getting initial control. This
28015 section addresses this issue by describing some methods that can be used
28016 to break somewhere in the DLL to debug it.
28017
28018 @noindent
28019 First suppose that the main procedure is named @code{main} (this is for
28020 example some C code built with Microsoft Visual C) and that there is a
28021 DLL named @code{test.dll} containing an Ada entry point named
28022 @code{ada_dll}.
28023
28024 @noindent
28025 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28026 been built with debugging information (see GNAT -g option).
28027
28028 @node Debugging the DLL Directly
28029 @subsubsection Debugging the DLL Directly
28030
28031 @enumerate 1
28032 @item
28033 Launch the debugger on the DLL.
28034
28035 @smallexample
28036 $ gdb -nw test.dll
28037 @end smallexample
28038
28039 @item Set a breakpoint on a DLL subroutine.
28040
28041 @smallexample
28042 (gdb) break ada_dll.adb:45
28043 @end smallexample
28044
28045 Note that at this point it is not possible to break using the routine symbol
28046 directly as the program is not yet running. The solution is to break
28047 on the proper line (break in @file{ada_dll.adb} line 45).
28048
28049 @item
28050 Specify the executable file to @code{GDB}.
28051
28052 @smallexample
28053 (gdb) exec-file main.exe
28054 @end smallexample
28055
28056 @item
28057 Run the program.
28058
28059 @smallexample
28060 (gdb) run
28061 @end smallexample
28062
28063 @noindent
28064 This will run the program until it reaches the breakpoint that has been
28065 set. From that point you can use the standard way to debug a program
28066 as described in (@pxref{Running and Debugging Ada Programs}).
28067
28068 @end enumerate
28069
28070 @noindent
28071 It is also possible to debug the DLL by attaching to a running process.
28072
28073 @node Attaching to a Running Process
28074 @subsubsection Attaching to a Running Process
28075 @cindex DLL debugging, attach to process
28076
28077 @noindent
28078 With @code{GDB} it is always possible to debug a running process by
28079 attaching to it. It is possible to debug a DLL this way. The limitation
28080 of this approach is that the DLL must run long enough to perform the
28081 attach operation. It may be useful for instance to insert a time wasting
28082 loop in the code of the DLL to meet this criterion.
28083
28084 @enumerate 1
28085
28086 @item Launch the main program @file{main.exe}.
28087
28088 @smallexample
28089 $ main
28090 @end smallexample
28091
28092 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28093 that the process PID for @file{main.exe} is 208.
28094
28095 @item Launch gdb.
28096
28097 @smallexample
28098 $ gdb -nw
28099 @end smallexample
28100
28101 @item Attach to the running process to be debugged.
28102
28103 @smallexample
28104 (gdb) attach 208
28105 @end smallexample
28106
28107 @item Load the process debugging information.
28108
28109 @smallexample
28110 (gdb) symbol-file main.exe
28111 @end smallexample
28112
28113 @item Break somewhere in the DLL.
28114
28115 @smallexample
28116 (gdb) break ada_dll
28117 @end smallexample
28118
28119 @item Continue process execution.
28120
28121 @smallexample
28122 (gdb) continue
28123 @end smallexample
28124
28125 @end enumerate
28126
28127 @noindent
28128 This last step will resume the process execution, and stop at
28129 the breakpoint we have set. From there you can use the standard
28130 approach to debug a program as described in
28131 (@pxref{Running and Debugging Ada Programs}).
28132
28133 @node GNAT and COM/DCOM Objects
28134 @section GNAT and COM/DCOM Objects
28135 @findex COM
28136 @findex DCOM
28137
28138 @noindent
28139 This section is temporarily left blank.
28140
28141 @end ifset
28142
28143 @c **********************************
28144 @c * GNU Free Documentation License *
28145 @c **********************************
28146 @include fdl.texi
28147 @c GNU Free Documentation License
28148
28149 @node Index,,GNU Free Documentation License, Top
28150 @unnumbered Index
28151
28152 @printindex cp
28153
28154 @contents
28155 @c Put table of contents at end, otherwise it precedes the "title page" in
28156 @c the .txt version
28157 @c Edit the pdf file to move the contents to the beginning, after the title
28158 @c page
28159
28160 @bye