OSDN Git Service

2005-03-29 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c          Copyright (C) 1992-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,  59 Temple Place - Suite 330,  Boston,  o
21 @c  MA 02111-1307, 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 * 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 @c The following should be removed (BMB 2001-01-23)
1098 @c @smallexample
1099 @c $ ^./hello^$ RUN HELLO^
1100 @c @end smallexample
1101
1102 @smallexample
1103 $ hello
1104 @end smallexample
1105
1106 @noindent
1107 assuming that the current directory is on the search path
1108 for executable programs.
1109
1110 @noindent
1111 and, if all has gone well, you will see
1112
1113 @smallexample
1114 Hello WORLD!
1115 @end smallexample
1116
1117 @noindent
1118 appear in response to this command.
1119
1120 @c ****************************************
1121 @node Running a Program with Multiple Units
1122 @section Running a Program with Multiple Units
1123
1124 @noindent
1125 Consider a slightly more complicated example that has three files: a
1126 main program, and the spec and body of a package:
1127
1128 @smallexample @c ada
1129 @cartouche
1130 @group
1131 package Greetings is
1132    procedure Hello;
1133    procedure Goodbye;
1134 end Greetings;
1135
1136 with Ada.Text_IO; use Ada.Text_IO;
1137 package body Greetings is
1138    procedure Hello is
1139    begin
1140       Put_Line ("Hello WORLD!");
1141    end Hello;
1142
1143    procedure Goodbye is
1144    begin
1145       Put_Line ("Goodbye WORLD!");
1146    end Goodbye;
1147 end Greetings;
1148 @end group
1149
1150 @group
1151 with Greetings;
1152 procedure Gmain is
1153 begin
1154    Greetings.Hello;
1155    Greetings.Goodbye;
1156 end Gmain;
1157 @end group
1158 @end cartouche
1159 @end smallexample
1160
1161 @noindent
1162 Following the one-unit-per-file rule, place this program in the
1163 following three separate files:
1164
1165 @table @file
1166 @item greetings.ads
1167 spec of package @code{Greetings}
1168
1169 @item greetings.adb
1170 body of package @code{Greetings}
1171
1172 @item gmain.adb
1173 body of main program
1174 @end table
1175
1176 @noindent
1177 To build an executable version of
1178 this program, we could use four separate steps to compile, bind, and link
1179 the program, as follows:
1180
1181 @smallexample
1182 $ gcc -c gmain.adb
1183 $ gcc -c greetings.adb
1184 $ gnatbind gmain
1185 $ gnatlink gmain
1186 @end smallexample
1187
1188 @noindent
1189 Note that there is no required order of compilation when using GNAT.
1190 In particular it is perfectly fine to compile the main program first.
1191 Also, it is not necessary to compile package specs in the case where
1192 there is an accompanying body; you only need to compile the body. If you want
1193 to submit these files to the compiler for semantic checking and not code
1194 generation, then use the
1195 @option{-gnatc} switch:
1196
1197 @smallexample
1198 $ gcc -c greetings.ads -gnatc
1199 @end smallexample
1200
1201 @noindent
1202 Although the compilation can be done in separate steps as in the
1203 above example, in practice it is almost always more convenient
1204 to use the @command{gnatmake} tool. All you need to know in this case
1205 is the name of the main program's source file. The effect of the above four
1206 commands can be achieved with a single one:
1207
1208 @smallexample
1209 $ gnatmake gmain.adb
1210 @end smallexample
1211
1212 @noindent
1213 In the next section we discuss the advantages of using @command{gnatmake} in
1214 more detail.
1215
1216 @c *****************************
1217 @node Using the gnatmake Utility
1218 @section Using the @command{gnatmake} Utility
1219
1220 @noindent
1221 If you work on a program by compiling single components at a time using
1222 @command{gcc}, you typically keep track of the units you modify. In order to
1223 build a consistent system, you compile not only these units, but also any
1224 units that depend on the units you have modified.
1225 For example, in the preceding case,
1226 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1227 you edit @file{greetings.ads}, you must recompile both
1228 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1229 units that depend on @file{greetings.ads}.
1230
1231 @code{gnatbind} will warn you if you forget one of these compilation
1232 steps, so that it is impossible to generate an inconsistent program as a
1233 result of forgetting to do a compilation. Nevertheless it is tedious and
1234 error-prone to keep track of dependencies among units.
1235 One approach to handle the dependency-bookkeeping is to use a
1236 makefile. However, makefiles present maintenance problems of their own:
1237 if the dependencies change as you change the program, you must make
1238 sure that the makefile is kept up-to-date manually, which is also an
1239 error-prone process.
1240
1241 The @command{gnatmake} utility takes care of these details automatically.
1242 Invoke it using either one of the following forms:
1243
1244 @smallexample
1245 $ gnatmake gmain.adb
1246 $ gnatmake ^gmain^GMAIN^
1247 @end smallexample
1248
1249 @noindent
1250 The argument is the name of the file containing the main program;
1251 you may omit the extension. @command{gnatmake}
1252 examines the environment, automatically recompiles any files that need
1253 recompiling, and binds and links the resulting set of object files,
1254 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1255 In a large program, it
1256 can be extremely helpful to use @command{gnatmake}, because working out by hand
1257 what needs to be recompiled can be difficult.
1258
1259 Note that @command{gnatmake}
1260 takes into account all the Ada 95 rules that
1261 establish dependencies among units. These include dependencies that result
1262 from inlining subprogram bodies, and from
1263 generic instantiation. Unlike some other
1264 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1265 found by the compiler on a previous compilation, which may possibly
1266 be wrong when sources change. @command{gnatmake} determines the exact set of
1267 dependencies from scratch each time it is run.
1268
1269 @ifset vms
1270 @node Editing with Emacs
1271 @section Editing with Emacs
1272 @cindex Emacs
1273
1274 @noindent
1275 Emacs is an extensible self-documenting text editor that is available in a
1276 separate VMSINSTAL kit.
1277
1278 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1279 click on the Emacs Help menu and run the Emacs Tutorial.
1280 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1281 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1282
1283 Documentation on Emacs and other tools is available in Emacs under the
1284 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1285 use the middle mouse button to select a topic (e.g. Emacs).
1286
1287 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1288 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1289 get to the Emacs manual.
1290 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1291 prompt.
1292
1293 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1294 which is sufficiently extensible to provide for a complete programming
1295 environment and shell for the sophisticated user.
1296 @end ifset
1297
1298 @ifclear vms
1299 @node Introduction to GPS
1300 @section Introduction to GPS
1301 @cindex GPS (GNAT Programming System)
1302 @cindex GNAT Programming System (GPS)
1303 @noindent
1304 Although the command line interface (@command{gnatmake}, etc.) alone
1305 is sufficient, a graphical Interactive Development
1306 Environment can make it easier for you to compose, navigate, and debug
1307 programs.  This section describes the main features of GPS
1308 (``GNAT Programming System''), the GNAT graphical IDE.
1309 You will see how to use GPS to build and debug an executable, and
1310 you will also learn some of the basics of the GNAT ``project'' facility.
1311
1312 GPS enables you to do much more than is presented here;
1313 e.g., you can produce a call graph, interface to a third-party
1314 Version Control System, and inspect the generated assembly language
1315 for a program.
1316 Indeed, GPS also supports languages other than Ada.
1317 Such additional information, and an explanation of all of the GPS menu
1318 items. may be found in the on-line help, which includes
1319 a user's guide and a tutorial (these are also accessible from the GNAT
1320 startup menu).
1321
1322 @menu
1323 * Building a New Program with GPS::
1324 * Simple Debugging with GPS::
1325 @end menu
1326
1327 @node Building a New Program with GPS
1328 @subsection Building a New Program with GPS
1329 @noindent
1330 GPS invokes the GNAT compilation tools using information
1331 contained in a @emph{project} (also known as a @emph{project file}):
1332 a collection of properties such
1333 as source directories, identities of main subprograms, tool switches, etc.,
1334 and their associated values.
1335 See @ref{GNAT Project Manager} for details.
1336 In order to run GPS, you will need to either create a new project
1337 or else open an existing one.
1338
1339 This section will explain how you can use GPS to create a project,
1340 to associate Ada source files with a project, and to build and run
1341 programs.
1342
1343 @enumerate
1344 @item @emph{Creating a project}
1345
1346 Invoke GPS, either from the command line or the platform's IDE.
1347 After it starts, GPS will display a ``Welcome'' screen with three
1348 radio buttons:
1349
1350 @itemize @bullet
1351 @item
1352 @code{Start with default project in directory}
1353
1354 @item
1355 @code{Create new project with wizard}
1356
1357 @item
1358 @code{Open existing project}
1359 @end itemize
1360
1361 @noindent
1362 Select @code{Create new project with wizard} and press @code{OK}.
1363 A new window will appear.  In the text box labeled with
1364 @code{Enter the name of the project to create}, type @file{sample}
1365 as the project name.
1366 In the next box, browse to choose the directory in which you
1367 would like to create the project file.
1368 After selecting an appropriate directory, press @code{Forward}.
1369
1370 A window will appear with the title
1371 @code{Version Control System Configuration}.
1372 Simply press @code{Forward}.
1373
1374 A window will appear with the title
1375 @code{Please select the source directories for this project}.
1376 The directory that you specified for the project file will be selected
1377 by default as the one to use for sources; simply press @code{Forward}.
1378
1379 A window will appear with the title
1380 @code{Please select the build directory for this project}.
1381 The directory that you specified for the project file will be selected
1382 by default for object files and executables;
1383 simply press @code{Forward}.
1384
1385 A window will appear with the title
1386 @code{Please select the main units for this project}.
1387 You will supply this information later, after creating the source file.
1388 Simply press @code{Forward} for now.
1389
1390 A window will appear with the title
1391 @code{Please select the switches to build the project}.
1392 Press @code{Apply}.  This will create a project file named
1393 @file{sample.prj} in the directory that you had specified.
1394
1395 @item @emph{Creating and saving the source file}
1396
1397 After you create the new project, a GPS window will appear, which is
1398 partitioned into two main sections:
1399
1400 @itemize @bullet
1401 @item
1402 A @emph{Workspace area}, initially greyed out, which you will use for
1403 creating and editing source files
1404
1405 @item
1406 Directly below, a @emph{Messages area}, which initially displays a
1407 ``Welcome'' message.
1408 (If the Messages area is not visible, drag its border upward to expand it.)
1409 @end itemize
1410
1411 @noindent
1412 Select @code{File} on the menu bar, and then the @code{New} command.
1413 The Workspace area will become white, and you can now
1414 enter the source program explicitly.
1415 Type the following text
1416
1417 @smallexample @c ada
1418 @group
1419 with Ada.Text_IO; use Ada.Text_IO;
1420 procedure Hello is
1421 begin
1422   Put_Line("Hello from GPS!");
1423 end Hello;
1424 @end group
1425 @end smallexample
1426
1427 @noindent
1428 Select @code{File}, then @code{Save As}, and enter the source file name
1429 @file{hello.adb}.
1430 The file will be saved in the same directory you specified as the
1431 location of the default project file.
1432
1433 @item @emph{Updating the project file}
1434
1435 You need to add the new source file to the project.
1436 To do this, select
1437 the @code{Project} menu and then @code{Edit project properties}.
1438 Click the @code{Main files} tab on the left, and then the
1439 @code{Add} button.
1440 Choose @file{hello.adb} from the list, and press @code{Open}.
1441 The project settings window will reflect this action.
1442 Click @code{OK}.
1443
1444 @item @emph{Building and running the program}
1445
1446 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1447 and select @file{hello.adb}.
1448 The Messages window will display the resulting invocations of @command{gcc},
1449 @command{gnatbind}, and @command{gnatlink}
1450 (reflecting the default switch settings from the
1451 project file that you created) and then a ``successful compilation/build''
1452 message.
1453
1454 To run the program, choose the @code{Build} menu, then @code{Run}, and
1455 select @command{hello}.
1456 An @emph{Arguments Selection} window will appear.
1457 There are no command line arguments, so just click @code{OK}.
1458
1459 The Messages window will now display the program's output (the string
1460 @code{Hello from GPS}), and at the bottom of the GPS window a status
1461 update is displayed (@code{Run: hello}).
1462 Close the GPS window (or select @code{File}, then @code{Exit}) to
1463 terminate this GPS session.
1464 @end enumerate
1465
1466 @node Simple Debugging with GPS
1467 @subsection Simple Debugging with GPS
1468 @noindent
1469 This section illustrates basic debugging techniques (setting breakpoints,
1470 examining/modifying variables, single stepping).
1471
1472 @enumerate
1473 @item @emph{Opening a project}
1474
1475 Start GPS and select @code{Open existing project}; browse to
1476 specify the project file @file{sample.prj} that you had created in the
1477 earlier example.
1478
1479 @item @emph{Creating a source file}
1480
1481 Select @code{File}, then @code{New}, and type in the following program:
1482
1483 @smallexample @c ada
1484 @group
1485 with Ada.Text_IO; use Ada.Text_IO;
1486 procedure Example is
1487    Line : String (1..80);
1488    N    : Natural;
1489 begin
1490    Put_Line("Type a line of text at each prompt; an empty line to exit");
1491    loop
1492       Put(": ");
1493       Get_Line (Line, N);
1494       Put_Line (Line (1..N) );
1495       exit when N=0;
1496    end loop;
1497 end Example;
1498 @end group
1499 @end smallexample
1500
1501 @noindent
1502 Select @code{File}, then @code{Save as}, and enter the file name
1503 @file{example.adb}.
1504
1505 @item @emph{Updating the project file}
1506
1507 Add @code{Example} as a new main unit for the project:
1508 @enumerate a
1509 @item
1510 Select @code{Project}, then @code{Edit Project Properties}.
1511
1512 @item
1513 Select the @code{Main files} tab, click @code{Add}, then
1514 select the file @file{example.adb} from the list, and
1515 click @code{Open}.
1516 You will see the file name appear in the list of main units
1517
1518 @item
1519 Click @code{OK}
1520 @end enumerate
1521
1522 @item @emph{Building/running the executable}
1523
1524 To build the executable
1525 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1526
1527 Run the program to see its effect (in the Messages area).
1528 Each line that you enter is displayed; an empty line will
1529 cause the loop to exit and the program to terminate.
1530
1531 @item @emph{Debugging the program}
1532
1533 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1534 which are required for debugging, are on by default when you create
1535 a new project.
1536 Thus unless you intentionally remove these settings, you will be able
1537 to debug any program that you develop using GPS.
1538
1539 @enumerate a
1540 @item @emph{Initializing}
1541
1542 Select @code{Debug}, then @code{Initialize}, then @file{example}
1543
1544 @item @emph{Setting a breakpoint}
1545
1546 After performing the initialization step, you will observe a small
1547 icon to the right of each line number.
1548 This serves as a toggle for breakpoints; clicking the icon will
1549 set a breakpoint at the corresponding line (the icon will change to
1550 a red circle with an ``x''), and clicking it again
1551 will remove the breakpoint / reset the icon.
1552
1553 For purposes of this example, set a breakpoint at line 10 (the
1554 statement @code{Put_Line@ (Line@ (1..N));}
1555
1556 @item @emph{Starting program execution}
1557
1558 Select @code{Debug}, then @code{Run}.  When the
1559 @code{Program Arguments} window appears, click @code{OK}.
1560 A console window will appear; enter some line of text,
1561 e.g. @code{abcde}, at the prompt.
1562 The program will pause execution when it gets to the
1563 breakpoint, and the corresponding line is highlighted.
1564
1565 @item @emph{Examining a variable}
1566
1567 Move the mouse over one of the occurrences of the variable @code{N}.
1568 You will see the value (5) displayed, in ``tool tip'' fashion.
1569 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1570 You will see information about @code{N} appear in the @code{Debugger Data}
1571 pane, showing the value as 5.
1572
1573 @item @emph{Assigning a new value to a variable}
1574
1575 Right click on the @code{N} in the @code{Debugger Data} pane, and
1576 select @code{Set value of N}.
1577 When the input window appears, enter the value @code{4} and click
1578 @code{OK}.
1579 This value does not automatically appear in the @code{Debugger Data}
1580 pane; to see it, right click again on the @code{N} in the
1581 @code{Debugger Data} pane and select @code{Update value}.
1582 The new value, 4, will appear in red.
1583
1584 @item @emph{Single stepping}
1585
1586 Select @code{Debug}, then @code{Next}.
1587 This will cause the next statement to be executed, in this case the
1588 call of @code{Put_Line} with the string slice.
1589 Notice in the console window that the displayed string is simply
1590 @code{abcd} and not @code{abcde} which you had entered.
1591 This is because the upper bound of the slice is now 4 rather than 5.
1592
1593 @item @emph{Removing a breakpoint}
1594
1595 Toggle the breakpoint icon at line 10.
1596
1597 @item @emph{Resuming execution from a breakpoint}
1598
1599 Select @code{Debug}, then @code{Continue}.
1600 The program will reach the next iteration of the loop, and
1601 wait for input after displaying the prompt.
1602 This time, just hit the @kbd{Enter} key.
1603 The value of @code{N} will be 0, and the program will terminate.
1604 The console window will disappear.
1605 @end enumerate
1606 @end enumerate
1607
1608 @node Introduction to Glide and GVD
1609 @section Introduction to Glide and GVD
1610 @cindex Glide
1611 @cindex GVD
1612 @noindent
1613 This section describes the main features of Glide,
1614 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1615 the GNU Visual Debugger.
1616 These tools may be present in addition to, or in place of, GPS on some
1617 platforms.
1618 Additional information on Glide and GVD may be found
1619 in the on-line help for these tools.
1620
1621 @menu
1622 * Building a New Program with Glide::
1623 * Simple Debugging with GVD::
1624 * Other Glide Features::
1625 @end menu
1626
1627 @node Building a New Program with Glide
1628 @subsection Building a New Program with Glide
1629 @noindent
1630 The simplest way to invoke Glide is to enter @command{glide}
1631 at the command prompt.  It will generally be useful to issue this
1632 as a background command, thus allowing you to continue using
1633 your command window for other purposes while Glide is running:
1634
1635 @smallexample
1636 $ glide&
1637 @end smallexample
1638
1639 @noindent
1640 Glide will start up with an initial screen displaying the top-level menu items
1641 as well as some other information.  The menu selections are as follows
1642 @itemize @bullet
1643 @item @code{Buffers}
1644 @item @code{Files}
1645 @item @code{Tools}
1646 @item @code{Edit}
1647 @item @code{Search}
1648 @item @code{Mule}
1649 @item @code{Glide}
1650 @item @code{Help}
1651 @end itemize
1652
1653 @noindent
1654 For this introductory example, you will need to create a new Ada source file.
1655 First, select the @code{Files} menu.  This will pop open a menu with around
1656 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1657 Depending on the platform, you may see a pop-up window where you can browse
1658 to an appropriate directory and then enter the file name, or else simply
1659 see a line at the bottom of the Glide window where you can likewise enter
1660 the file name.  Note that in Glide, when you attempt to open a non-existent
1661 file, the effect is to create a file with that name.  For this example enter
1662 @file{hello.adb} as the name of the file.
1663
1664 A new buffer will now appear, occupying the entire Glide window,
1665 with the file name at the top.  The menu selections are slightly different
1666 from the ones you saw on the opening screen; there is an @code{Entities} item,
1667 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1668 the file extension to identify the source language, so @file{adb} indicates
1669 an Ada source file.
1670
1671 You will enter some of the source program lines explicitly,
1672 and use the syntax-oriented template mechanism to enter other lines.
1673 First, type the following text:
1674 @smallexample
1675 with Ada.Text_IO; use Ada.Text_IO;
1676 procedure Hello is
1677 begin
1678 @end smallexample
1679
1680 @noindent
1681 Observe that Glide uses different colors to distinguish reserved words from
1682 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1683 automatically indented in anticipation of declarations.  When you enter
1684 @code{begin}, Glide recognizes that there are no declarations and thus places
1685 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1686 indented, where the statement(s) will be placed.
1687
1688 The main part of the program will be a @code{for} loop.  Instead of entering
1689 the text explicitly, however, use a statement template.  Select the @code{Ada}
1690 item on the top menu bar, move the mouse to the @code{Statements} item,
1691 and you will see a large selection of alternatives.  Choose @code{for loop}.
1692 You will be prompted (at the bottom of the buffer) for a loop name;
1693 simply press the @key{Enter} key since a loop name is not needed.
1694 You should see the beginning of a @code{for} loop appear in the source
1695 program window.  You will now be prompted for the name of the loop variable;
1696 enter a line with the identifier @code{ind} (lower case).  Note that,
1697 by default, Glide capitalizes the name (you can override such behavior
1698 if you wish, although this is outside the scope of this introduction).
1699 Next, Glide prompts you for the loop range; enter a line containing
1700 @code{1..5} and you will see this also appear in the source program,
1701 together with the remaining elements of the @code{for} loop syntax.
1702
1703 Next enter the statement (with an intentional error, a missing semicolon)
1704 that will form the body of the loop:
1705 @smallexample
1706 Put_Line("Hello, World" & Integer'Image(I))
1707 @end smallexample
1708
1709 @noindent
1710 Finally, type @code{end Hello;} as the last line in the program.
1711 Now save the file: choose the @code{File} menu item, and then the
1712 @code{Save buffer} selection.  You will see a message at the bottom
1713 of the buffer confirming that the file has been saved.
1714
1715 You are now ready to attempt to build the program.  Select the @code{Ada}
1716 item from the top menu bar.  Although we could choose simply to compile
1717 the file, we will instead attempt to do a build (which invokes
1718 @command{gnatmake}) since, if the compile is successful, we want to build
1719 an executable.  Thus select @code{Ada build}.  This will fail because of the
1720 compilation error, and you will notice that the Glide window has been split:
1721 the top window contains the source file, and the bottom window contains the
1722 output from the GNAT tools. Glide allows you to navigate from a compilation
1723 error to the source file position corresponding to the error: click the
1724 middle mouse button (or simultaneously press the left and right buttons,
1725 on a two-button mouse) on the diagnostic line in the tool window.  The
1726 focus will shift to the source window, and the cursor will be positioned
1727 on the character at which the error was detected.
1728
1729 Correct the error: type in a semicolon to terminate the statement.
1730 Although you can again save the file explicitly, you can also simply invoke
1731 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1732 This time the build will succeed; the tool output window shows you the
1733 options that are supplied by default.  The GNAT tools' output (e.g.
1734 object and ALI files, executable) will go in the directory from which
1735 Glide was launched.
1736
1737 To execute the program, choose @code{Ada} and then @code{Run}.
1738 You should see the program's output displayed in the bottom window:
1739
1740 @smallexample
1741 Hello, world 1
1742 Hello, world 2
1743 Hello, world 3
1744 Hello, world 4
1745 Hello, world 5
1746 @end smallexample
1747
1748 @node Simple Debugging with GVD
1749 @subsection Simple Debugging with GVD
1750
1751 @noindent
1752 This section describes how to set breakpoints, examine/modify variables,
1753 and step through execution.
1754
1755 In order to enable debugging, you need to pass the @option{-g} switch
1756 to both the compiler and to @command{gnatlink}.  If you are using
1757 the command line, passing @option{-g} to @command{gnatmake} will have
1758 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1759 by issuing the command:
1760
1761 @smallexample
1762 $ gvd hello
1763 @end smallexample
1764
1765 @noindent
1766 If you are using Glide, then @option{-g} is passed to the relevant tools
1767 by default when you do a build.  Start the debugger by selecting the
1768 @code{Ada} menu item, and then @code{Debug}.
1769
1770 GVD comes up in a multi-part window.  One pane shows the names of files
1771 comprising your executable; another pane shows the source code of the current
1772 unit (initially your main subprogram), another pane shows the debugger output
1773 and user interactions, and the fourth pane (the data canvas at the top
1774 of the window) displays data objects that you have selected.
1775
1776 To the left of the source file pane, you will notice green dots adjacent
1777 to some lines.  These are lines for which object code exists and where
1778 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1779 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1780 in a red circle.  Clicking the circle toggles the breakpoint off,
1781 and the red circle is replaced by the green dot.
1782
1783 For this example, set a breakpoint at the statement where @code{Put_Line}
1784 is invoked.
1785
1786 Start program execution by selecting the @code{Run} button on the top menu bar.
1787 (The @code{Start} button will also start your program, but it will
1788 cause program execution to break at the entry to your main subprogram.)
1789 Evidence of reaching the breakpoint will appear: the source file line will be
1790 highlighted, and the debugger interactions pane will display
1791 a relevant message.
1792
1793 You can examine the values of variables in several ways.  Move the mouse
1794 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1795 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1796 and select @code{Display Ind}; a box showing the variable's name and value
1797 will appear in the data canvas.
1798
1799 Although a loop index is a constant with respect to Ada semantics,
1800 you can change its value in the debugger.  Right-click in the box
1801 for @code{Ind}, and select the @code{Set Value of Ind} item.
1802 Enter @code{2} as the new value, and press @command{OK}.
1803 The box for @code{Ind} shows the update.
1804
1805 Press the @code{Step} button on the top menu bar; this will step through
1806 one line of program text (the invocation of @code{Put_Line}), and you can
1807 observe the effect of having modified @code{Ind} since the value displayed
1808 is @code{2}.
1809
1810 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1811 button.  You will see the remaining output lines displayed in the debugger
1812 interaction window, along with a message confirming normal program
1813 termination.
1814
1815 @node Other Glide Features
1816 @subsection Other Glide Features
1817
1818 @noindent
1819 You may have observed that some of the menu selections contain abbreviations;
1820 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1821 These are @emph{shortcut keys} that you can use instead of selecting
1822 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1823 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1824 of selecting @code{Files} and then @code{Open file...}.
1825
1826 To abort a Glide command, type @key{Ctrl-g}.
1827
1828 If you want Glide to start with an existing source file, you can either
1829 launch Glide as above and then open the file via @code{Files} @result{}
1830 @code{Open file...}, or else simply pass the name of the source file
1831 on the command line:
1832
1833 @smallexample
1834 $ glide hello.adb&
1835 @end smallexample
1836
1837 @noindent
1838 While you are using Glide, a number of @emph{buffers} exist.
1839 You create some explicitly; e.g., when you open/create a file.
1840 Others arise as an effect of the commands that you issue; e.g., the buffer
1841 containing the output of the tools invoked during a build.  If a buffer
1842 is hidden, you can bring it into a visible window by first opening
1843 the @code{Buffers} menu and then selecting the desired entry.
1844
1845 If a buffer occupies only part of the Glide screen and you want to expand it
1846 to fill the entire screen, then click in the buffer and then select
1847 @code{Files} @result{} @code{One Window}.
1848
1849 If a window is occupied by one buffer and you want to split the window
1850 to bring up a second buffer, perform the following steps:
1851 @itemize @bullet
1852 @item Select @code{Files} @result{} @code{Split Window};
1853 this will produce two windows each of which holds the original buffer
1854 (these are not copies, but rather different views of the same buffer contents)
1855
1856 @item With the focus in one of the windows,
1857 select the desired buffer from the @code{Buffers} menu
1858 @end itemize
1859
1860 @noindent
1861 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1862 @end ifclear
1863
1864 @node The GNAT Compilation Model
1865 @chapter The GNAT Compilation Model
1866 @cindex GNAT compilation model
1867 @cindex Compilation model
1868
1869 @menu
1870 * Source Representation::
1871 * Foreign Language Representation::
1872 * File Naming Rules::
1873 * Using Other File Names::
1874 * Alternative File Naming Schemes::
1875 * Generating Object Files::
1876 * Source Dependencies::
1877 * The Ada Library Information Files::
1878 * Binding an Ada Program::
1879 * Mixed Language Programming::
1880 * Building Mixed Ada & C++ Programs::
1881 * Comparison between GNAT and C/C++ Compilation Models::
1882 * Comparison between GNAT and Conventional Ada Library Models::
1883 @ifset vms
1884 * Placement of temporary files::
1885 @end ifset
1886 @end menu
1887
1888 @noindent
1889 This chapter describes the compilation model used by GNAT. Although
1890 similar to that used by other languages, such as C and C++, this model
1891 is substantially different from the traditional Ada compilation models,
1892 which are based on a library. The model is initially described without
1893 reference to the library-based model. If you have not previously used an
1894 Ada compiler, you need only read the first part of this chapter. The
1895 last section describes and discusses the differences between the GNAT
1896 model and the traditional Ada compiler models. If you have used other
1897 Ada compilers, this section will help you to understand those
1898 differences, and the advantages of the GNAT model.
1899
1900 @node Source Representation
1901 @section Source Representation
1902 @cindex Latin-1
1903
1904 @noindent
1905 Ada source programs are represented in standard text files, using
1906 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1907 7-bit ASCII set, plus additional characters used for
1908 representing foreign languages (@pxref{Foreign Language Representation}
1909 for support of non-USA character sets). The format effector characters
1910 are represented using their standard ASCII encodings, as follows:
1911
1912 @table @code
1913 @item VT
1914 @findex VT
1915 Vertical tab, @code{16#0B#}
1916
1917 @item HT
1918 @findex HT
1919 Horizontal tab, @code{16#09#}
1920
1921 @item CR
1922 @findex CR
1923 Carriage return, @code{16#0D#}
1924
1925 @item LF
1926 @findex LF
1927 Line feed, @code{16#0A#}
1928
1929 @item FF
1930 @findex FF
1931 Form feed, @code{16#0C#}
1932 @end table
1933
1934 @noindent
1935 Source files are in standard text file format. In addition, GNAT will
1936 recognize a wide variety of stream formats, in which the end of
1937 physical lines is marked by any of the following sequences:
1938 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1939 in accommodating files that are imported from other operating systems.
1940
1941 @cindex End of source file
1942 @cindex Source file, end
1943 @findex SUB
1944 The end of a source file is normally represented by the physical end of
1945 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1946 recognized as signalling the end of the source file. Again, this is
1947 provided for compatibility with other operating systems where this
1948 code is used to represent the end of file.
1949
1950 Each file contains a single Ada compilation unit, including any pragmas
1951 associated with the unit. For example, this means you must place a
1952 package declaration (a package @dfn{spec}) and the corresponding body in
1953 separate files. An Ada @dfn{compilation} (which is a sequence of
1954 compilation units) is represented using a sequence of files. Similarly,
1955 you will place each subunit or child unit in a separate file.
1956
1957 @node Foreign Language Representation
1958 @section Foreign Language Representation
1959
1960 @noindent
1961 GNAT supports the standard character sets defined in Ada 95 as well as
1962 several other non-standard character sets for use in localized versions
1963 of the compiler (@pxref{Character Set Control}).
1964 @menu
1965 * Latin-1::
1966 * Other 8-Bit Codes::
1967 * Wide Character Encodings::
1968 @end menu
1969
1970 @node Latin-1
1971 @subsection Latin-1
1972 @cindex Latin-1
1973
1974 @noindent
1975 The basic character set is Latin-1. This character set is defined by ISO
1976 standard 8859, part 1. The lower half (character codes @code{16#00#}
1977 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1978 is used to represent additional characters. These include extended letters
1979 used by European languages, such as French accents, the vowels with umlauts
1980 used in German, and the extra letter A-ring used in Swedish.
1981
1982 @findex Ada.Characters.Latin_1
1983 For a complete list of Latin-1 codes and their encodings, see the source
1984 file of library unit @code{Ada.Characters.Latin_1} in file
1985 @file{a-chlat1.ads}.
1986 You may use any of these extended characters freely in character or
1987 string literals. In addition, the extended characters that represent
1988 letters can be used in identifiers.
1989
1990 @node Other 8-Bit Codes
1991 @subsection Other 8-Bit Codes
1992
1993 @noindent
1994 GNAT also supports several other 8-bit coding schemes:
1995
1996 @table @asis
1997 @item ISO 8859-2 (Latin-2)
1998 @cindex Latin-2
1999 @cindex ISO 8859-2
2000 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2001 equivalence.
2002
2003 @item ISO 8859-3 (Latin-3)
2004 @cindex Latin-3
2005 @cindex ISO 8859-3
2006 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2007 equivalence.
2008
2009 @item ISO 8859-4 (Latin-4)
2010 @cindex Latin-4
2011 @cindex ISO 8859-4
2012 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2013 equivalence.
2014
2015 @item ISO 8859-5 (Cyrillic)
2016 @cindex ISO 8859-5
2017 @cindex Cyrillic
2018 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2019 lowercase equivalence.
2020
2021 @item ISO 8859-15 (Latin-9)
2022 @cindex ISO 8859-15
2023 @cindex Latin-9
2024 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2025 lowercase equivalence
2026
2027 @item IBM PC (code page 437)
2028 @cindex code page 437
2029 This code page is the normal default for PCs in the U.S. It corresponds
2030 to the original IBM PC character set. This set has some, but not all, of
2031 the extended Latin-1 letters, but these letters do not have the same
2032 encoding as Latin-1. In this mode, these letters are allowed in
2033 identifiers with uppercase and lowercase equivalence.
2034
2035 @item IBM PC (code page 850)
2036 @cindex code page 850
2037 This code page is a modification of 437 extended to include all the
2038 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2039 mode, all these letters are allowed in identifiers with uppercase and
2040 lowercase equivalence.
2041
2042 @item Full Upper 8-bit
2043 Any character in the range 80-FF allowed in identifiers, and all are
2044 considered distinct. In other words, there are no uppercase and lowercase
2045 equivalences in this range. This is useful in conjunction with
2046 certain encoding schemes used for some foreign character sets (e.g.
2047 the typical method of representing Chinese characters on the PC).
2048
2049 @item No Upper-Half
2050 No upper-half characters in the range 80-FF are allowed in identifiers.
2051 This gives Ada 83 compatibility for identifier names.
2052 @end table
2053
2054 @noindent
2055 For precise data on the encodings permitted, and the uppercase and lowercase
2056 equivalences that are recognized, see the file @file{csets.adb} in
2057 the GNAT compiler sources. You will need to obtain a full source release
2058 of GNAT to obtain this file.
2059
2060 @node Wide Character Encodings
2061 @subsection Wide Character Encodings
2062
2063 @noindent
2064 GNAT allows wide character codes to appear in character and string
2065 literals, and also optionally in identifiers, by means of the following
2066 possible encoding schemes:
2067
2068 @table @asis
2069
2070 @item Hex Coding
2071 In this encoding, a wide character is represented by the following five
2072 character sequence:
2073
2074 @smallexample
2075 ESC a b c d
2076 @end smallexample
2077
2078 @noindent
2079 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2080 characters (using uppercase letters) of the wide character code. For
2081 example, ESC A345 is used to represent the wide character with code
2082 @code{16#A345#}.
2083 This scheme is compatible with use of the full Wide_Character set.
2084
2085 @item Upper-Half Coding
2086 @cindex Upper-Half Coding
2087 The wide character with encoding @code{16#abcd#} where the upper bit is on
2088 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2089 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2090 character, but is not required to be in the upper half. This method can
2091 be also used for shift-JIS or EUC, where the internal coding matches the
2092 external coding.
2093
2094 @item Shift JIS Coding
2095 @cindex Shift JIS Coding
2096 A wide character is represented by a two-character sequence,
2097 @code{16#ab#} and
2098 @code{16#cd#}, with the restrictions described for upper-half encoding as
2099 described above. The internal character code is the corresponding JIS
2100 character according to the standard algorithm for Shift-JIS
2101 conversion. Only characters defined in the JIS code set table can be
2102 used with this encoding method.
2103
2104 @item EUC Coding
2105 @cindex EUC Coding
2106 A wide character is represented by a two-character sequence
2107 @code{16#ab#} and
2108 @code{16#cd#}, with both characters being in the upper half. The internal
2109 character code is the corresponding JIS character according to the EUC
2110 encoding algorithm. Only characters defined in the JIS code set table
2111 can be used with this encoding method.
2112
2113 @item UTF-8 Coding
2114 A wide character is represented using
2115 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2116 10646-1/Am.2. Depending on the character value, the representation
2117 is a one, two, or three byte sequence:
2118 @smallexample
2119 @iftex
2120 @leftskip=.7cm
2121 @end iftex
2122 16#0000#-16#007f#: 2#0xxxxxxx#
2123 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2124 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2125
2126 @end smallexample
2127
2128 @noindent
2129 where the xxx bits correspond to the left-padded bits of the
2130 16-bit character value. Note that all lower half ASCII characters
2131 are represented as ASCII bytes and all upper half characters and
2132 other wide characters are represented as sequences of upper-half
2133 (The full UTF-8 scheme allows for encoding 31-bit characters as
2134 6-byte sequences, but in this implementation, all UTF-8 sequences
2135 of four or more bytes length will be treated as illegal).
2136 @item Brackets Coding
2137 In this encoding, a wide character is represented by the following eight
2138 character sequence:
2139
2140 @smallexample
2141 [ " a b c d " ]
2142 @end smallexample
2143
2144 @noindent
2145 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2146 characters (using uppercase letters) of the wide character code. For
2147 example, [``A345''] is used to represent the wide character with code
2148 @code{16#A345#}. It is also possible (though not required) to use the
2149 Brackets coding for upper half characters. For example, the code
2150 @code{16#A3#} can be represented as @code{[``A3'']}.
2151
2152 This scheme is compatible with use of the full Wide_Character set,
2153 and is also the method used for wide character encoding in the standard
2154 ACVC (Ada Compiler Validation Capability) test suite distributions.
2155
2156 @end table
2157
2158 @noindent
2159 Note: Some of these coding schemes do not permit the full use of the
2160 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2161 use of the upper half of the Latin-1 set.
2162
2163 @node File Naming Rules
2164 @section File Naming Rules
2165
2166 @noindent
2167 The default file name is determined by the name of the unit that the
2168 file contains. The name is formed by taking the full expanded name of
2169 the unit and replacing the separating dots with hyphens and using
2170 ^lowercase^uppercase^ for all letters.
2171
2172 An exception arises if the file name generated by the above rules starts
2173 with one of the characters
2174 @ifset vms
2175 A,G,I, or S,
2176 @end ifset
2177 @ifclear vms
2178 a,g,i, or s,
2179 @end ifclear
2180 and the second character is a
2181 minus. In this case, the character ^tilde^dollar sign^ is used in place
2182 of the minus. The reason for this special rule is to avoid clashes with
2183 the standard names for child units of the packages System, Ada,
2184 Interfaces, and GNAT, which use the prefixes
2185 @ifset vms
2186 S- A- I- and G-
2187 @end ifset
2188 @ifclear vms
2189 s- a- i- and g-
2190 @end ifclear
2191 respectively.
2192
2193 The file extension is @file{.ads} for a spec and
2194 @file{.adb} for a body. The following list shows some
2195 examples of these rules.
2196
2197 @table @file
2198 @item main.ads
2199 Main (spec)
2200 @item main.adb
2201 Main (body)
2202 @item arith_functions.ads
2203 Arith_Functions (package spec)
2204 @item arith_functions.adb
2205 Arith_Functions (package body)
2206 @item func-spec.ads
2207 Func.Spec (child package spec)
2208 @item func-spec.adb
2209 Func.Spec (child package body)
2210 @item main-sub.adb
2211 Sub (subunit of Main)
2212 @item ^a~bad.adb^A$BAD.ADB^
2213 A.Bad (child package body)
2214 @end table
2215
2216 @noindent
2217 Following these rules can result in excessively long
2218 file names if corresponding
2219 unit names are long (for example, if child units or subunits are
2220 heavily nested). An option is available to shorten such long file names
2221 (called file name ``krunching''). This may be particularly useful when
2222 programs being developed with GNAT are to be used on operating systems
2223 with limited file name lengths. @xref{Using gnatkr}.
2224
2225 Of course, no file shortening algorithm can guarantee uniqueness over
2226 all possible unit names; if file name krunching is used, it is your
2227 responsibility to ensure no name clashes occur. Alternatively you
2228 can specify the exact file names that you want used, as described
2229 in the next section. Finally, if your Ada programs are migrating from a
2230 compiler with a different naming convention, you can use the gnatchop
2231 utility to produce source files that follow the GNAT naming conventions.
2232 (For details @pxref{Renaming Files Using gnatchop}.)
2233
2234 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2235 systems, case is not significant. So for example on @code{Windows XP}
2236 if the canonical name is @code{main-sub.adb}, you can use the file name
2237 @code{Main-Sub.adb} instead. However, case is significant for other
2238 operating systems, so for example, if you want to use other than
2239 canonically cased file names on a Unix system, you need to follow
2240 the procedures described in the next section.
2241
2242 @node Using Other File Names
2243 @section Using Other File Names
2244 @cindex File names
2245
2246 @noindent
2247 In the previous section, we have described the default rules used by
2248 GNAT to determine the file name in which a given unit resides. It is
2249 often convenient to follow these default rules, and if you follow them,
2250 the compiler knows without being explicitly told where to find all
2251 the files it needs.
2252
2253 However, in some cases, particularly when a program is imported from
2254 another Ada compiler environment, it may be more convenient for the
2255 programmer to specify which file names contain which units. GNAT allows
2256 arbitrary file names to be used by means of the Source_File_Name pragma.
2257 The form of this pragma is as shown in the following examples:
2258 @cindex Source_File_Name pragma
2259
2260 @smallexample @c ada
2261 @cartouche
2262 pragma Source_File_Name (My_Utilities.Stacks,
2263   Spec_File_Name => "myutilst_a.ada");
2264 pragma Source_File_name (My_Utilities.Stacks,
2265   Body_File_Name => "myutilst.ada");
2266 @end cartouche
2267 @end smallexample
2268
2269 @noindent
2270 As shown in this example, the first argument for the pragma is the unit
2271 name (in this example a child unit). The second argument has the form
2272 of a named association. The identifier
2273 indicates whether the file name is for a spec or a body;
2274 the file name itself is given by a string literal.
2275
2276 The source file name pragma is a configuration pragma, which means that
2277 normally it will be placed in the @file{gnat.adc}
2278 file used to hold configuration
2279 pragmas that apply to a complete compilation environment.
2280 For more details on how the @file{gnat.adc} file is created and used
2281 see @ref{Handling of Configuration Pragmas}.
2282 @cindex @file{gnat.adc}
2283
2284 @ifclear vms
2285 GNAT allows completely arbitrary file names to be specified using the
2286 source file name pragma. However, if the file name specified has an
2287 extension other than @file{.ads} or @file{.adb} it is necessary to use
2288 a special syntax when compiling the file. The name in this case must be
2289 preceded by the special sequence @code{-x} followed by a space and the name
2290 of the language, here @code{ada}, as in:
2291
2292 @smallexample
2293 $ gcc -c -x ada peculiar_file_name.sim
2294 @end smallexample
2295 @end ifclear
2296
2297 @noindent
2298 @command{gnatmake} handles non-standard file names in the usual manner (the
2299 non-standard file name for the main program is simply used as the
2300 argument to gnatmake). Note that if the extension is also non-standard,
2301 then it must be included in the gnatmake command, it may not be omitted.
2302
2303 @node Alternative File Naming Schemes
2304 @section Alternative File Naming Schemes
2305 @cindex File naming schemes, alternative
2306 @cindex File names
2307
2308 In the previous section, we described the use of the @code{Source_File_Name}
2309 pragma to allow arbitrary names to be assigned to individual source files.
2310 However, this approach requires one pragma for each file, and especially in
2311 large systems can result in very long @file{gnat.adc} files, and also create
2312 a maintenance problem.
2313
2314 GNAT also provides a facility for specifying systematic file naming schemes
2315 other than the standard default naming scheme previously described. An
2316 alternative scheme for naming is specified by the use of
2317 @code{Source_File_Name} pragmas having the following format:
2318 @cindex Source_File_Name pragma
2319
2320 @smallexample @c ada
2321 pragma Source_File_Name (
2322    Spec_File_Name  => FILE_NAME_PATTERN
2323  [,Casing          => CASING_SPEC]
2324  [,Dot_Replacement => STRING_LITERAL]);
2325
2326 pragma Source_File_Name (
2327    Body_File_Name  => FILE_NAME_PATTERN
2328  [,Casing          => CASING_SPEC]
2329  [,Dot_Replacement => STRING_LITERAL]);
2330
2331 pragma Source_File_Name (
2332    Subunit_File_Name  => FILE_NAME_PATTERN
2333  [,Casing             => CASING_SPEC]
2334  [,Dot_Replacement    => STRING_LITERAL]);
2335
2336 FILE_NAME_PATTERN ::= STRING_LITERAL
2337 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2338 @end smallexample
2339
2340 @noindent
2341 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2342 It contains a single asterisk character, and the unit name is substituted
2343 systematically for this asterisk. The optional parameter
2344 @code{Casing} indicates
2345 whether the unit name is to be all upper-case letters, all lower-case letters,
2346 or mixed-case. If no
2347 @code{Casing} parameter is used, then the default is all
2348 ^lower-case^upper-case^.
2349
2350 The optional @code{Dot_Replacement} string is used to replace any periods
2351 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2352 argument is used then separating dots appear unchanged in the resulting
2353 file name.
2354 Although the above syntax indicates that the
2355 @code{Casing} argument must appear
2356 before the @code{Dot_Replacement} argument, but it
2357 is also permissible to write these arguments in the opposite order.
2358
2359 As indicated, it is possible to specify different naming schemes for
2360 bodies, specs, and subunits. Quite often the rule for subunits is the
2361 same as the rule for bodies, in which case, there is no need to give
2362 a separate @code{Subunit_File_Name} rule, and in this case the
2363 @code{Body_File_name} rule is used for subunits as well.
2364
2365 The separate rule for subunits can also be used to implement the rather
2366 unusual case of a compilation environment (e.g. a single directory) which
2367 contains a subunit and a child unit with the same unit name. Although
2368 both units cannot appear in the same partition, the Ada Reference Manual
2369 allows (but does not require) the possibility of the two units coexisting
2370 in the same environment.
2371
2372 The file name translation works in the following steps:
2373
2374 @itemize @bullet
2375
2376 @item
2377 If there is a specific @code{Source_File_Name} pragma for the given unit,
2378 then this is always used, and any general pattern rules are ignored.
2379
2380 @item
2381 If there is a pattern type @code{Source_File_Name} pragma that applies to
2382 the unit, then the resulting file name will be used if the file exists. If
2383 more than one pattern matches, the latest one will be tried first, and the
2384 first attempt resulting in a reference to a file that exists will be used.
2385
2386 @item
2387 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2388 for which the corresponding file exists, then the standard GNAT default
2389 naming rules are used.
2390
2391 @end itemize
2392
2393 @noindent
2394 As an example of the use of this mechanism, consider a commonly used scheme
2395 in which file names are all lower case, with separating periods copied
2396 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2397 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2398 two pragmas appear:
2399
2400 @smallexample @c ada
2401 pragma Source_File_Name
2402   (Spec_File_Name => "*.1.ada");
2403 pragma Source_File_Name
2404   (Body_File_Name => "*.2.ada");
2405 @end smallexample
2406
2407 @noindent
2408 The default GNAT scheme is actually implemented by providing the following
2409 default pragmas internally:
2410
2411 @smallexample @c ada
2412 pragma Source_File_Name
2413   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2414 pragma Source_File_Name
2415   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2416 @end smallexample
2417
2418 @noindent
2419 Our final example implements a scheme typically used with one of the
2420 Ada 83 compilers, where the separator character for subunits was ``__''
2421 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2422 by adding @file{.ADA}, and subunits by
2423 adding @file{.SEP}. All file names were
2424 upper case. Child units were not present of course since this was an
2425 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2426 the same double underscore separator for child units.
2427
2428 @smallexample @c ada
2429 pragma Source_File_Name
2430   (Spec_File_Name => "*_.ADA",
2431    Dot_Replacement => "__",
2432    Casing = Uppercase);
2433 pragma Source_File_Name
2434   (Body_File_Name => "*.ADA",
2435    Dot_Replacement => "__",
2436    Casing = Uppercase);
2437 pragma Source_File_Name
2438   (Subunit_File_Name => "*.SEP",
2439    Dot_Replacement => "__",
2440    Casing = Uppercase);
2441 @end smallexample
2442
2443 @node Generating Object Files
2444 @section Generating Object Files
2445
2446 @noindent
2447 An Ada program consists of a set of source files, and the first step in
2448 compiling the program is to generate the corresponding object files.
2449 These are generated by compiling a subset of these source files.
2450 The files you need to compile are the following:
2451
2452 @itemize @bullet
2453 @item
2454 If a package spec has no body, compile the package spec to produce the
2455 object file for the package.
2456
2457 @item
2458 If a package has both a spec and a body, compile the body to produce the
2459 object file for the package. The source file for the package spec need
2460 not be compiled in this case because there is only one object file, which
2461 contains the code for both the spec and body of the package.
2462
2463 @item
2464 For a subprogram, compile the subprogram body to produce the object file
2465 for the subprogram. The spec, if one is present, is as usual in a
2466 separate file, and need not be compiled.
2467
2468 @item
2469 @cindex Subunits
2470 In the case of subunits, only compile the parent unit. A single object
2471 file is generated for the entire subunit tree, which includes all the
2472 subunits.
2473
2474 @item
2475 Compile child units independently of their parent units
2476 (though, of course, the spec of all the ancestor unit must be present in order
2477 to compile a child unit).
2478
2479 @item
2480 @cindex Generics
2481 Compile generic units in the same manner as any other units. The object
2482 files in this case are small dummy files that contain at most the
2483 flag used for elaboration checking. This is because GNAT always handles generic
2484 instantiation by means of macro expansion. However, it is still necessary to
2485 compile generic units, for dependency checking and elaboration purposes.
2486 @end itemize
2487
2488 @noindent
2489 The preceding rules describe the set of files that must be compiled to
2490 generate the object files for a program. Each object file has the same
2491 name as the corresponding source file, except that the extension is
2492 @file{.o} as usual.
2493
2494 You may wish to compile other files for the purpose of checking their
2495 syntactic and semantic correctness. For example, in the case where a
2496 package has a separate spec and body, you would not normally compile the
2497 spec. However, it is convenient in practice to compile the spec to make
2498 sure it is error-free before compiling clients of this spec, because such
2499 compilations will fail if there is an error in the spec.
2500
2501 GNAT provides an option for compiling such files purely for the
2502 purposes of checking correctness; such compilations are not required as
2503 part of the process of building a program. To compile a file in this
2504 checking mode, use the @option{-gnatc} switch.
2505
2506 @node Source Dependencies
2507 @section Source Dependencies
2508
2509 @noindent
2510 A given object file clearly depends on the source file which is compiled
2511 to produce it. Here we are using @dfn{depends} in the sense of a typical
2512 @code{make} utility; in other words, an object file depends on a source
2513 file if changes to the source file require the object file to be
2514 recompiled.
2515 In addition to this basic dependency, a given object may depend on
2516 additional source files as follows:
2517
2518 @itemize @bullet
2519 @item
2520 If a file being compiled @code{with}'s a unit @var{X}, the object file
2521 depends on the file containing the spec of unit @var{X}. This includes
2522 files that are @code{with}'ed implicitly either because they are parents
2523 of @code{with}'ed child units or they are run-time units required by the
2524 language constructs used in a particular unit.
2525
2526 @item
2527 If a file being compiled instantiates a library level generic unit, the
2528 object file depends on both the spec and body files for this generic
2529 unit.
2530
2531 @item
2532 If a file being compiled instantiates a generic unit defined within a
2533 package, the object file depends on the body file for the package as
2534 well as the spec file.
2535
2536 @item
2537 @findex Inline
2538 @cindex @option{-gnatn} switch
2539 If a file being compiled contains a call to a subprogram for which
2540 pragma @code{Inline} applies and inlining is activated with the
2541 @option{-gnatn} switch, the object file depends on the file containing the
2542 body of this subprogram as well as on the file containing the spec. Note
2543 that for inlining to actually occur as a result of the use of this switch,
2544 it is necessary to compile in optimizing mode.
2545
2546 @cindex @option{-gnatN} switch
2547 The use of @option{-gnatN} activates a more extensive inlining optimization
2548 that is performed by the front end of the compiler. This inlining does
2549 not require that the code generation be optimized. Like @option{-gnatn},
2550 the use of this switch generates additional dependencies.
2551 Note that
2552 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2553 to specify both options.
2554
2555 @item
2556 If an object file O  depends on the proper body of a subunit through inlining
2557 or instantiation, it depends on the parent unit of the subunit. This means that
2558 any modification of the parent unit or one of its subunits affects the
2559 compilation of O.
2560
2561 @item
2562 The object file for a parent unit depends on all its subunit body files.
2563
2564 @item
2565 The previous two rules meant that for purposes of computing dependencies and
2566 recompilation, a body and all its subunits are treated as an indivisible whole.
2567
2568 @noindent
2569 These rules are applied transitively: if unit @code{A} @code{with}'s
2570 unit @code{B}, whose elaboration calls an inlined procedure in package
2571 @code{C}, the object file for unit @code{A} will depend on the body of
2572 @code{C}, in file @file{c.adb}.
2573
2574 The set of dependent files described by these rules includes all the
2575 files on which the unit is semantically dependent, as described in the
2576 Ada 95 Language Reference Manual. However, it is a superset of what the
2577 ARM describes, because it includes generic, inline, and subunit dependencies.
2578
2579 An object file must be recreated by recompiling the corresponding source
2580 file if any of the source files on which it depends are modified. For
2581 example, if the @code{make} utility is used to control compilation,
2582 the rule for an Ada object file must mention all the source files on
2583 which the object file depends, according to the above definition.
2584 The determination of the necessary
2585 recompilations is done automatically when one uses @command{gnatmake}.
2586 @end itemize
2587
2588 @node The Ada Library Information Files
2589 @section The Ada Library Information Files
2590 @cindex Ada Library Information files
2591 @cindex @file{ALI} files
2592
2593 @noindent
2594 Each compilation actually generates two output files. The first of these
2595 is the normal object file that has a @file{.o} extension. The second is a
2596 text file containing full dependency information. It has the same
2597 name as the source file, but an @file{.ali} extension.
2598 This file is known as the Ada Library Information (@file{ALI}) file.
2599 The following information is contained in the @file{ALI} file.
2600
2601 @itemize @bullet
2602 @item
2603 Version information (indicates which version of GNAT was used to compile
2604 the unit(s) in question)
2605
2606 @item
2607 Main program information (including priority and time slice settings,
2608 as well as the wide character encoding used during compilation).
2609
2610 @item
2611 List of arguments used in the @command{gcc} command for the compilation
2612
2613 @item
2614 Attributes of the unit, including configuration pragmas used, an indication
2615 of whether the compilation was successful, exception model used etc.
2616
2617 @item
2618 A list of relevant restrictions applying to the unit (used for consistency)
2619 checking.
2620
2621 @item
2622 Categorization information (e.g. use of pragma @code{Pure}).
2623
2624 @item
2625 Information on all @code{with}'ed units, including presence of
2626 @code{Elaborate} or @code{Elaborate_All} pragmas.
2627
2628 @item
2629 Information from any @code{Linker_Options} pragmas used in the unit
2630
2631 @item
2632 Information on the use of @code{Body_Version} or @code{Version}
2633 attributes in the unit.
2634
2635 @item
2636 Dependency information. This is a list of files, together with
2637 time stamp and checksum information. These are files on which
2638 the unit depends in the sense that recompilation is required
2639 if any of these units are modified.
2640
2641 @item
2642 Cross-reference data. Contains information on all entities referenced
2643 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2644 provide cross-reference information.
2645
2646 @end itemize
2647
2648 @noindent
2649 For a full detailed description of the format of the @file{ALI} file,
2650 see the source of the body of unit @code{Lib.Writ}, contained in file
2651 @file{lib-writ.adb} in the GNAT compiler sources.
2652
2653 @node Binding an Ada Program
2654 @section Binding an Ada Program
2655
2656 @noindent
2657 When using languages such as C and C++, once the source files have been
2658 compiled the only remaining step in building an executable program
2659 is linking the object modules together. This means that it is possible to
2660 link an inconsistent version of a program, in which two units have
2661 included different versions of the same header.
2662
2663 The rules of Ada do not permit such an inconsistent program to be built.
2664 For example, if two clients have different versions of the same package,
2665 it is illegal to build a program containing these two clients.
2666 These rules are enforced by the GNAT binder, which also determines an
2667 elaboration order consistent with the Ada rules.
2668
2669 The GNAT binder is run after all the object files for a program have
2670 been created. It is given the name of the main program unit, and from
2671 this it determines the set of units required by the program, by reading the
2672 corresponding ALI files. It generates error messages if the program is
2673 inconsistent or if no valid order of elaboration exists.
2674
2675 If no errors are detected, the binder produces a main program, in Ada by
2676 default, that contains calls to the elaboration procedures of those
2677 compilation unit that require them, followed by
2678 a call to the main program. This Ada program is compiled to generate the
2679 object file for the main program. The name of
2680 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2681 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2682 main program unit.
2683
2684 Finally, the linker is used to build the resulting executable program,
2685 using the object from the main program from the bind step as well as the
2686 object files for the Ada units of the program.
2687
2688 @node Mixed Language Programming
2689 @section Mixed Language Programming
2690 @cindex Mixed Language Programming
2691
2692 @noindent
2693 This section describes how to develop a mixed-language program,
2694 specifically one that comprises units in both Ada and C.
2695
2696 @menu
2697 * Interfacing to C::
2698 * Calling Conventions::
2699 @end menu
2700
2701 @node Interfacing to C
2702 @subsection Interfacing to C
2703 @noindent
2704 Interfacing Ada with a foreign language such as C involves using
2705 compiler directives to import and/or export entity definitions in each
2706 language---using @code{extern} statements in C, for instance, and the
2707 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2708 a full treatment of these topics, read Appendix B, section 1 of the Ada
2709 95 Language Reference Manual.
2710
2711 There are two ways to build a program using GNAT that contains some Ada
2712 sources and some foreign language sources, depending on whether or not
2713 the main subprogram is written in Ada.  Here is a source example with
2714 the main subprogram in Ada:
2715
2716 @smallexample
2717 /* file1.c */
2718 #include <stdio.h>
2719
2720 void print_num (int num)
2721 @{
2722   printf ("num is %d.\n", num);
2723   return;
2724 @}
2725
2726 /* file2.c */
2727
2728 /* num_from_Ada is declared in my_main.adb */
2729 extern int num_from_Ada;
2730
2731 int get_num (void)
2732 @{
2733   return num_from_Ada;
2734 @}
2735 @end smallexample
2736
2737 @smallexample @c ada
2738 --  my_main.adb
2739 procedure My_Main is
2740
2741    --  Declare then export an Integer entity called num_from_Ada
2742    My_Num : Integer := 10;
2743    pragma Export (C, My_Num, "num_from_Ada");
2744
2745    --  Declare an Ada function spec for Get_Num, then use
2746    --  C function get_num for the implementation.
2747    function Get_Num return Integer;
2748    pragma Import (C, Get_Num, "get_num");
2749
2750    --  Declare an Ada procedure spec for Print_Num, then use
2751    --  C function print_num for the implementation.
2752    procedure Print_Num (Num : Integer);
2753    pragma Import (C, Print_Num, "print_num");
2754
2755 begin
2756    Print_Num (Get_Num);
2757 end My_Main;
2758 @end smallexample
2759
2760 @enumerate
2761 @item
2762 To build this example, first compile the foreign language files to
2763 generate object files:
2764 @smallexample
2765 gcc -c file1.c
2766 gcc -c file2.c
2767 @end smallexample
2768
2769 @item
2770 Then, compile the Ada units to produce a set of object files and ALI
2771 files:
2772 @smallexample
2773 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2774 @end smallexample
2775
2776 @item
2777 Run the Ada binder on the Ada main program:
2778 @smallexample
2779 gnatbind my_main.ali
2780 @end smallexample
2781
2782 @item
2783 Link the Ada main program, the Ada objects and the other language
2784 objects:
2785 @smallexample
2786 gnatlink my_main.ali file1.o file2.o
2787 @end smallexample
2788 @end enumerate
2789
2790 The last three steps can be grouped in a single command:
2791 @smallexample
2792 gnatmake my_main.adb -largs file1.o file2.o
2793 @end smallexample
2794
2795 @cindex Binder output file
2796 @noindent
2797 If the main program is in a language other than Ada, then you may have
2798 more than one entry point into the Ada subsystem. You must use a special
2799 binder option to generate callable routines that initialize and
2800 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2801 Calls to the initialization and finalization routines must be inserted
2802 in the main program, or some other appropriate point in the code. The
2803 call to initialize the Ada units must occur before the first Ada
2804 subprogram is called, and the call to finalize the Ada units must occur
2805 after the last Ada subprogram returns. The binder will place the
2806 initialization and finalization subprograms into the
2807 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2808 sources.  To illustrate, we have the following example:
2809
2810 @smallexample
2811 /* main.c */
2812 extern void adainit (void);
2813 extern void adafinal (void);
2814 extern int add (int, int);
2815 extern int sub (int, int);
2816
2817 int main (int argc, char *argv[])
2818 @{
2819   int a = 21, b = 7;
2820
2821   adainit();
2822
2823   /* Should print "21 + 7 = 28" */
2824   printf ("%d + %d = %d\n", a, b, add (a, b));
2825   /* Should print "21 - 7 = 14" */
2826   printf ("%d - %d = %d\n", a, b, sub (a, b));
2827
2828   adafinal();
2829 @}
2830 @end smallexample
2831
2832 @smallexample @c ada
2833 --  unit1.ads
2834 package Unit1 is
2835    function Add (A, B : Integer) return Integer;
2836    pragma Export (C, Add, "add");
2837 end Unit1;
2838
2839 --  unit1.adb
2840 package body Unit1 is
2841    function Add (A, B : Integer) return Integer is
2842    begin
2843       return A + B;
2844    end Add;
2845 end Unit1;
2846
2847 --  unit2.ads
2848 package Unit2 is
2849    function Sub (A, B : Integer) return Integer;
2850    pragma Export (C, Sub, "sub");
2851 end Unit2;
2852
2853 --  unit2.adb
2854 package body Unit2 is
2855    function Sub (A, B : Integer) return Integer is
2856    begin
2857       return A - B;
2858    end Sub;
2859 end Unit2;
2860 @end smallexample
2861
2862 @enumerate
2863 @item
2864 The build procedure for this application is similar to the last
2865 example's.  First, compile the foreign language files to generate object
2866 files:
2867 @smallexample
2868 gcc -c main.c
2869 @end smallexample
2870
2871 @item
2872 Next, compile the Ada units to produce a set of object files and ALI
2873 files:
2874 @smallexample
2875 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2876 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2877 @end smallexample
2878
2879 @item
2880 Run the Ada binder on every generated ALI file.  Make sure to use the
2881 @option{-n} option to specify a foreign main program:
2882 @smallexample
2883 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2884 @end smallexample
2885
2886 @item
2887 Link the Ada main program, the Ada objects and the foreign language
2888 objects. You need only list the last ALI file here:
2889 @smallexample
2890 gnatlink unit2.ali main.o -o exec_file
2891 @end smallexample
2892
2893 This procedure yields a binary executable called @file{exec_file}.
2894 @end enumerate
2895
2896 @node Calling Conventions
2897 @subsection Calling Conventions
2898 @cindex Foreign Languages
2899 @cindex Calling Conventions
2900 GNAT follows standard calling sequence conventions and will thus interface
2901 to any other language that also follows these conventions. The following
2902 Convention identifiers are recognized by GNAT:
2903
2904 @table @code
2905 @cindex Interfacing to Ada
2906 @cindex Other Ada compilers
2907 @cindex Convention Ada
2908 @item Ada
2909 This indicates that the standard Ada calling sequence will be
2910 used and all Ada data items may be passed without any limitations in the
2911 case where GNAT is used to generate both the caller and callee. It is also
2912 possible to mix GNAT generated code and code generated by another Ada
2913 compiler. In this case, the data types should be restricted to simple
2914 cases, including primitive types. Whether complex data types can be passed
2915 depends on the situation. Probably it is safe to pass simple arrays, such
2916 as arrays of integers or floats. Records may or may not work, depending
2917 on whether both compilers lay them out identically. Complex structures
2918 involving variant records, access parameters, tasks, or protected types,
2919 are unlikely to be able to be passed.
2920
2921 Note that in the case of GNAT running
2922 on a platform that supports DEC Ada 83, a higher degree of compatibility
2923 can be guaranteed, and in particular records are layed out in an identical
2924 manner in the two compilers. Note also that if output from two different
2925 compilers is mixed, the program is responsible for dealing with elaboration
2926 issues. Probably the safest approach is to write the main program in the
2927 version of Ada other than GNAT, so that it takes care of its own elaboration
2928 requirements, and then call the GNAT-generated adainit procedure to ensure
2929 elaboration of the GNAT components. Consult the documentation of the other
2930 Ada compiler for further details on elaboration.
2931
2932 However, it is not possible to mix the tasking run time of GNAT and
2933 DEC Ada 83, All the tasking operations must either be entirely within
2934 GNAT compiled sections of the program, or entirely within DEC Ada 83
2935 compiled sections of the program.
2936
2937 @cindex Interfacing to Assembly
2938 @cindex Convention Assembler
2939 @item Assembler
2940 Specifies assembler as the convention. In practice this has the
2941 same effect as convention Ada (but is not equivalent in the sense of being
2942 considered the same convention).
2943
2944 @cindex Convention Asm
2945 @findex Asm
2946 @item Asm
2947 Equivalent to Assembler.
2948
2949 @cindex Interfacing to COBOL
2950 @cindex Convention COBOL
2951 @findex COBOL
2952 @item COBOL
2953 Data will be passed according to the conventions described
2954 in section B.4 of the Ada 95 Reference Manual.
2955
2956 @findex C
2957 @cindex Interfacing to C
2958 @cindex Convention C
2959 @item C
2960 Data will be passed according to the conventions described
2961 in section B.3 of the Ada 95 Reference Manual.
2962
2963 @findex C varargs function
2964 @cindex Intefacing to C varargs function
2965 @cindex varargs function intefacs
2966 @item C varargs function
2967 In C, @code{varargs} allows a function to take a variable number of
2968 arguments. There is no direct equivalent in this to Ada. One
2969 approach that can be used is to create a C wrapper for each
2970 different profile and then interface to this C wrapper. For
2971 example, to print an @code{int} value using @code{printf},
2972 create a C function @code{printfi} that takes two arguments, a
2973 pointer to a string and an int, and calls @code{printf}.
2974 Then in the Ada program, use pragma @code{Import} to
2975 interface to printfi.
2976
2977 It may work on some platforms to directly interface to
2978 a @code{varargs} function by providing a specific Ada profile
2979 for a a particular call. However, this does not work on
2980 all platforms, since there is no guarantee that the
2981 calling sequence for a two argument normal C function
2982 is the same as for calling a @code{varargs} C function with
2983 the same two arguments.
2984
2985 @cindex Convention Default
2986 @findex Default
2987 @item Default
2988 Equivalent to C.
2989
2990 @cindex Convention External
2991 @findex External
2992 @item External
2993 Equivalent to C.
2994
2995 @findex C++
2996 @cindex Interfacing to C++
2997 @cindex Convention C++
2998 @item CPP
2999 This stands for C++. For most purposes this is identical to C.
3000 See the separate description of the specialized GNAT pragmas relating to
3001 C++ interfacing for further details.
3002
3003 @findex Fortran
3004 @cindex Interfacing to Fortran
3005 @cindex Convention Fortran
3006 @item Fortran
3007 Data will be passed according to the conventions described
3008 in section B.5 of the Ada 95 Reference Manual.
3009
3010 @item Intrinsic
3011 This applies to an intrinsic operation, as defined in the Ada 95
3012 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3013 this means that the body of the subprogram is provided by the compiler itself,
3014 usually by means of an efficient code sequence, and that the user does not
3015 supply an explicit body for it. In an application program, the pragma can
3016 only be applied to the following two sets of names, which the GNAT compiler
3017 recognizes.
3018
3019 @itemize @bullet
3020 @item
3021 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3022 Arithmetic.  The corresponding subprogram declaration must have
3023 two formal parameters. The
3024 first one must be a signed integer type or a modular type with a binary
3025 modulus, and the second parameter must be of type Natural.
3026 The return type must be the same as the type of the first argument. The size
3027 of this type can only be 8, 16, 32, or 64.
3028 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3029 The corresponding operator declaration must have parameters and result type
3030 that have the same root numeric type (for example, all three are long_float
3031 types). This simplifies the definition of operations that use type checking
3032 to perform dimensional checks:
3033
3034 @smallexample @c ada
3035 type Distance is new Long_Float;
3036 type Time     is new Long_Float;
3037 type Velocity is new Long_Float;
3038 function "/" (D : Distance; T : Time)
3039   return Velocity;
3040 pragma Import (Intrinsic, "/");
3041 @end smallexample
3042
3043 @noindent
3044 This common idiom is often programmed with a generic definition and an
3045 explicit body. The pragma makes it simpler to introduce such declarations.
3046 It incurs no overhead in compilation time or code size, because it is
3047 implemented as a single machine instruction.
3048 @end itemize
3049 @noindent
3050
3051 @ifset unw
3052 @findex Stdcall
3053 @cindex Convention Stdcall
3054 @item Stdcall
3055 This is relevant only to NT/Win95 implementations of GNAT,
3056 and specifies that the Stdcall calling sequence will be used, as defined
3057 by the NT API.
3058
3059 @findex DLL
3060 @cindex Convention DLL
3061 @item DLL
3062 This is equivalent to Stdcall.
3063
3064 @findex Win32
3065 @cindex Convention Win32
3066 @item Win32
3067 This is equivalent to Stdcall.
3068 @end ifset
3069
3070 @findex Stubbed
3071 @cindex Convention Stubbed
3072 @item Stubbed
3073 This is a special convention that indicates that the compiler
3074 should provide a stub body that raises @code{Program_Error}.
3075 @end table
3076
3077 @noindent
3078 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3079 that can be used to parametrize conventions and allow additional synonyms
3080 to be specified. For example if you have legacy code in which the convention
3081 identifier Fortran77 was used for Fortran, you can use the configuration
3082 pragma:
3083
3084 @smallexample @c ada
3085 pragma Convention_Identifier (Fortran77, Fortran);
3086 @end smallexample
3087
3088 @noindent
3089 And from now on the identifier Fortran77 may be used as a convention
3090 identifier (for example in an @code{Import} pragma) with the same
3091 meaning as Fortran.
3092
3093 @node Building Mixed Ada & C++ Programs
3094 @section Building Mixed Ada & C++ Programs
3095
3096 @noindent
3097 A programmer inexperienced with mixed-language development may find that
3098 building an application containing both Ada and C++ code can be a
3099 challenge. As a matter of fact, interfacing with C++ has not been
3100 standardized in the Ada 95 Reference Manual due to the immaturity of --
3101 and lack of standards for -- C++ at the time. This section gives a few
3102 hints that should make this task easier. The first section addresses
3103 the differences regarding interfacing with C. The second section
3104 looks into the delicate problem of linking the complete application from
3105 its Ada and C++ parts. The last section gives some hints on how the GNAT
3106 run time can be adapted in order to allow inter-language dispatching
3107 with a new C++ compiler.
3108
3109 @menu
3110 * Interfacing to C++::
3111 * Linking a Mixed C++ & Ada Program::
3112 * A Simple Example::
3113 * Adapting the Run Time to a New C++ Compiler::
3114 @end menu
3115
3116 @node Interfacing to C++
3117 @subsection Interfacing to C++
3118
3119 @noindent
3120 GNAT supports interfacing with C++ compilers generating code that is
3121 compatible with the standard Application Binary Interface of the given
3122 platform.
3123
3124 @noindent
3125 Interfacing can be done at 3 levels: simple data, subprograms, and
3126 classes. In the first two cases, GNAT offers a specific @var{Convention
3127 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3128 the names of subprograms, and currently, GNAT does not provide any help
3129 to solve the demangling problem. This problem can be addressed in two
3130 ways:
3131 @itemize @bullet
3132 @item
3133 by modifying the C++ code in order to force a C convention using
3134 the @code{extern "C"} syntax.
3135
3136 @item
3137 by figuring out the mangled name and use it as the Link_Name argument of
3138 the pragma import.
3139 @end itemize
3140
3141 @noindent
3142 Interfacing at the class level can be achieved by using the GNAT specific
3143 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3144 Reference Manual for additional information.
3145
3146 @node Linking a Mixed C++ & Ada Program
3147 @subsection Linking a Mixed C++ & Ada Program
3148
3149 @noindent
3150 Usually the linker of the C++ development system must be used to link
3151 mixed applications because most C++ systems will resolve elaboration
3152 issues (such as calling constructors on global class instances)
3153 transparently during the link phase. GNAT has been adapted to ease the
3154 use of a foreign linker for the last phase. Three cases can be
3155 considered:
3156 @enumerate
3157
3158 @item
3159 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3160 The C++ linker can simply be called by using the C++ specific driver
3161 called @code{c++}. Note that this setup is not very common because it
3162 may involve recompiling the whole GCC tree from sources, which makes it
3163 harder to upgrade the compilation system for one language without
3164 destabilizing the other.
3165
3166 @smallexample
3167 $ c++ -c file1.C
3168 $ c++ -c file2.C
3169 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3170 @end smallexample
3171
3172 @item
3173 Using GNAT and G++ from two different GCC installations: If both
3174 compilers are on the PATH, the previous method may be used. It is
3175 important to note that environment variables such as C_INCLUDE_PATH,
3176 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3177 at the same time and may make one of the two compilers operate
3178 improperly if set during invocation of the wrong compiler.  It is also
3179 very important that the linker uses the proper @file{libgcc.a} GCC
3180 library -- that is, the one from the C++ compiler installation. The
3181 implicit link command as suggested in the gnatmake command from the
3182 former example can be replaced by an explicit link command with the
3183 full-verbosity option in order to verify which library is used:
3184 @smallexample
3185 $ gnatbind ada_unit
3186 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3187 @end smallexample
3188 If there is a problem due to interfering environment variables, it can
3189 be worked around by using an intermediate script. The following example
3190 shows the proper script to use when GNAT has not been installed at its
3191 default location and g++ has been installed at its default location:
3192
3193 @smallexample
3194 $ cat ./my_script
3195 #!/bin/sh
3196 unset BINUTILS_ROOT
3197 unset GCC_ROOT
3198 c++ $*
3199 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3200 @end smallexample
3201
3202 @item
3203 Using a non-GNU C++ compiler: The commands previously described can be
3204 used to insure that the C++ linker is used. Nonetheless, you need to add
3205 the path to libgcc explicitly, since some libraries needed by GNAT are
3206 located in this directory:
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 @end enumerate
3218
3219 @node A Simple Example
3220 @subsection  A Simple Example
3221 @noindent
3222 The following example, provided as part of the GNAT examples, shows how
3223 to achieve procedural interfacing between Ada and C++ in both
3224 directions. The C++ class A has two methods. The first method is exported
3225 to Ada by the means of an extern C wrapper function. The second method
3226 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3227 a limited record with a layout comparable to the C++ class. The Ada
3228 subprogram, in turn, calls the C++ method. So, starting from the C++
3229 main program, the process passes back and forth between the two
3230 languages.
3231
3232 @noindent
3233 Here are the compilation commands:
3234 @smallexample
3235 $ gnatmake -c simple_cpp_interface
3236 $ c++ -c cpp_main.C
3237 $ c++ -c ex7.C
3238 $ gnatbind -n simple_cpp_interface
3239 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3240       -lstdc++ ex7.o cpp_main.o
3241 @end smallexample
3242
3243 @noindent
3244 Here are the corresponding sources:
3245 @smallexample
3246
3247 //cpp_main.C
3248
3249 #include "ex7.h"
3250
3251 extern "C" @{
3252   void adainit (void);
3253   void adafinal (void);
3254   void method1 (A *t);
3255 @}
3256
3257 void method1 (A *t)
3258 @{
3259   t->method1 ();
3260 @}
3261
3262 int main ()
3263 @{
3264   A obj;
3265   adainit ();
3266   obj.method2 (3030);
3267   adafinal ();
3268 @}
3269
3270 //ex7.h
3271
3272 class Origin @{
3273  public:
3274   int o_value;
3275 @};
3276 class A : public Origin @{
3277  public:
3278   void method1 (void);
3279   void method2 (int v);
3280   A();
3281   int   a_value;
3282 @};
3283
3284 //ex7.C
3285
3286 #include "ex7.h"
3287 #include <stdio.h>
3288
3289 extern "C" @{ void ada_method2 (A *t, int v);@}
3290
3291 void A::method1 (void)
3292 @{
3293   a_value = 2020;
3294   printf ("in A::method1, a_value = %d \n",a_value);
3295
3296 @}
3297
3298 void A::method2 (int v)
3299 @{
3300    ada_method2 (this, v);
3301    printf ("in A::method2, a_value = %d \n",a_value);
3302
3303 @}
3304
3305 A::A(void)
3306 @{
3307    a_value = 1010;
3308   printf ("in A::A, a_value = %d \n",a_value);
3309 @}
3310
3311 -- Ada sources
3312 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3313
3314    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3315    @b{begin}
3316       Method1 (This);
3317       This.A_Value := V;
3318    @b{end} Ada_Method2;
3319
3320 @b{end} Simple_Cpp_Interface;
3321
3322 @b{package} Simple_Cpp_Interface @b{is}
3323    @b{type} A @b{is} @b{limited}
3324       @b{record}
3325          O_Value : Integer;
3326          A_Value : Integer;
3327       @b{end} @b{record};
3328    @b{pragma} Convention (C, A);
3329
3330    @b{procedure} Method1 (This : @b{in} @b{out} A);
3331    @b{pragma} Import (C, Method1);
3332
3333    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3334    @b{pragma} Export (C, Ada_Method2);
3335
3336 @b{end} Simple_Cpp_Interface;
3337 @end smallexample
3338
3339 @node Adapting the Run Time to a New C++ Compiler
3340 @subsection Adapting the Run Time to a New C++ Compiler
3341 @noindent
3342 GNAT offers the capability to derive Ada 95 tagged types directly from
3343 preexisting C++ classes and . See ``Interfacing with C++'' in the
3344 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3345 such a goal
3346 has been made user configurable through a GNAT library unit
3347 @code{Interfaces.CPP}. The default version of this file is adapted to
3348 the GNU C++ compiler. Internal knowledge of the virtual
3349 table layout used by the new C++ compiler is needed to configure
3350 properly this unit. The Interface of this unit is known by the compiler
3351 and cannot be changed except for the value of the constants defining the
3352 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3353 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3354 of this unit for more details.
3355
3356 @node Comparison between GNAT and C/C++ Compilation Models
3357 @section Comparison between GNAT and C/C++ Compilation Models
3358
3359 @noindent
3360 The GNAT model of compilation is close to the C and C++ models. You can
3361 think of Ada specs as corresponding to header files in C. As in C, you
3362 don't need to compile specs; they are compiled when they are used. The
3363 Ada @code{with} is similar in effect to the @code{#include} of a C
3364 header.
3365
3366 One notable difference is that, in Ada, you may compile specs separately
3367 to check them for semantic and syntactic accuracy. This is not always
3368 possible with C headers because they are fragments of programs that have
3369 less specific syntactic or semantic rules.
3370
3371 The other major difference is the requirement for running the binder,
3372 which performs two important functions. First, it checks for
3373 consistency. In C or C++, the only defense against assembling
3374 inconsistent programs lies outside the compiler, in a makefile, for
3375 example. The binder satisfies the Ada requirement that it be impossible
3376 to construct an inconsistent program when the compiler is used in normal
3377 mode.
3378
3379 @cindex Elaboration order control
3380 The other important function of the binder is to deal with elaboration
3381 issues. There are also elaboration issues in C++ that are handled
3382 automatically. This automatic handling has the advantage of being
3383 simpler to use, but the C++ programmer has no control over elaboration.
3384 Where @code{gnatbind} might complain there was no valid order of
3385 elaboration, a C++ compiler would simply construct a program that
3386 malfunctioned at run time.
3387
3388 @node Comparison between GNAT and Conventional Ada Library Models
3389 @section Comparison between GNAT and Conventional Ada Library Models
3390
3391 @noindent
3392 This section is intended to be useful to Ada programmers who have
3393 previously used an Ada compiler implementing the traditional Ada library
3394 model, as described in the Ada 95 Language Reference Manual. If you
3395 have not used such a system, please go on to the next section.
3396
3397 @cindex GNAT library
3398 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3399 source files themselves acts as the library. Compiling Ada programs does
3400 not generate any centralized information, but rather an object file and
3401 a ALI file, which are of interest only to the binder and linker.
3402 In a traditional system, the compiler reads information not only from
3403 the source file being compiled, but also from the centralized library.
3404 This means that the effect of a compilation depends on what has been
3405 previously compiled. In particular:
3406
3407 @itemize @bullet
3408 @item
3409 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3410 to the version of the unit most recently compiled into the library.
3411
3412 @item
3413 Inlining is effective only if the necessary body has already been
3414 compiled into the library.
3415
3416 @item
3417 Compiling a unit may obsolete other units in the library.
3418 @end itemize
3419
3420 @noindent
3421 In GNAT, compiling one unit never affects the compilation of any other
3422 units because the compiler reads only source files. Only changes to source
3423 files can affect the results of a compilation. 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 source version of the unit that is currently accessible to the
3429 compiler.
3430
3431 @item
3432 @cindex Inlining
3433 Inlining requires the appropriate source files for the package or
3434 subprogram bodies to be available to the compiler. Inlining is always
3435 effective, independent of the order in which units are complied.
3436
3437 @item
3438 Compiling a unit never affects any other compilations. The editing of
3439 sources may cause previous compilations to be out of date if they
3440 depended on the source file being modified.
3441 @end itemize
3442
3443 @noindent
3444 The most important result of these differences is that order of compilation
3445 is never significant in GNAT. There is no situation in which one is
3446 required to do one compilation before another. What shows up as order of
3447 compilation requirements in the traditional Ada library becomes, in
3448 GNAT, simple source dependencies; in other words, there is only a set
3449 of rules saying what source files must be present when a file is
3450 compiled.
3451
3452 @ifset vms
3453 @node Placement of temporary files
3454 @section Placement of temporary files
3455 @cindex Temporary files (user control over placement)
3456
3457 @noindent
3458 GNAT creates temporary files in the directory designated by the environment
3459 variable @env{TMPDIR}.
3460 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3461 for detailed information on how environment variables are resolved.
3462 For most users the easiest way to make use of this feature is to simply
3463 define @env{TMPDIR} as a job level logical name).
3464 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3465 for compiler temporary files, then you can include something like the
3466 following command in your @file{LOGIN.COM} file:
3467
3468 @smallexample
3469 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3470 @end smallexample
3471
3472 @noindent
3473 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3474 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3475 designated by @env{TEMP}.
3476 If none of these environment variables are defined then GNAT uses the
3477 directory designated by the logical name @code{SYS$SCRATCH:}
3478 (by default the user's home directory). If all else fails
3479 GNAT uses the current directory for temporary files.
3480 @end ifset
3481
3482 @c *************************
3483 @node Compiling Using gcc
3484 @chapter Compiling Using @command{gcc}
3485
3486 @noindent
3487 This chapter discusses how to compile Ada programs using the @command{gcc}
3488 command. It also describes the set of switches
3489 that can be used to control the behavior of the compiler.
3490 @menu
3491 * Compiling Programs::
3492 * Switches for gcc::
3493 * Search Paths and the Run-Time Library (RTL)::
3494 * Order of Compilation Issues::
3495 * Examples::
3496 @end menu
3497
3498 @node Compiling Programs
3499 @section Compiling Programs
3500
3501 @noindent
3502 The first step in creating an executable program is to compile the units
3503 of the program using the @command{gcc} command. You must compile the
3504 following files:
3505
3506 @itemize @bullet
3507 @item
3508 the body file (@file{.adb}) for a library level subprogram or generic
3509 subprogram
3510
3511 @item
3512 the spec file (@file{.ads}) for a library level package or generic
3513 package that has no body
3514
3515 @item
3516 the body file (@file{.adb}) for a library level package
3517 or generic package that has a body
3518
3519 @end itemize
3520
3521 @noindent
3522 You need @emph{not} compile the following files
3523
3524 @itemize @bullet
3525
3526 @item
3527 the spec of a library unit which has a body
3528
3529 @item
3530 subunits
3531 @end itemize
3532
3533 @noindent
3534 because they are compiled as part of compiling related units. GNAT
3535 package specs
3536 when the corresponding body is compiled, and subunits when the parent is
3537 compiled.
3538
3539 @cindex cannot generate code
3540 If you attempt to compile any of these files, you will get one of the
3541 following error messages (where fff is the name of the file you compiled):
3542
3543 @smallexample
3544 cannot generate code for file @var{fff} (package spec)
3545 to check package spec, use -gnatc
3546
3547 cannot generate code for file @var{fff} (missing subunits)
3548 to check parent unit, use -gnatc
3549
3550 cannot generate code for file @var{fff} (subprogram spec)
3551 to check subprogram spec, use -gnatc
3552
3553 cannot generate code for file @var{fff} (subunit)
3554 to check subunit, use -gnatc
3555 @end smallexample
3556
3557 @noindent
3558 As indicated by the above error messages, if you want to submit
3559 one of these files to the compiler to check for correct semantics
3560 without generating code, then use the @option{-gnatc} switch.
3561
3562 The basic command for compiling a file containing an Ada unit is
3563
3564 @smallexample
3565 $ gcc -c [@var{switches}] @file{file name}
3566 @end smallexample
3567
3568 @noindent
3569 where @var{file name} is the name of the Ada file (usually
3570 having an extension
3571 @file{.ads} for a spec or @file{.adb} for a body).
3572 @ifclear vms
3573 You specify the
3574 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3575 @end ifclear
3576 The result of a successful compilation is an object file, which has the
3577 same name as the source file but an extension of @file{.o} and an Ada
3578 Library Information (ALI) file, which also has the same name as the
3579 source file, but with @file{.ali} as the extension. GNAT creates these
3580 two output files in the current directory, but you may specify a source
3581 file in any directory using an absolute or relative path specification
3582 containing the directory information.
3583
3584 @findex gnat1
3585 @command{gcc} is actually a driver program that looks at the extensions of
3586 the file arguments and loads the appropriate compiler. For example, the
3587 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3588 These programs are in directories known to the driver program (in some
3589 configurations via environment variables you set), but need not be in
3590 your path. The @command{gcc} driver also calls the assembler and any other
3591 utilities needed to complete the generation of the required object
3592 files.
3593
3594 It is possible to supply several file names on the same @command{gcc}
3595 command. This causes @command{gcc} to call the appropriate compiler for
3596 each file. For example, the following command lists three separate
3597 files to be compiled:
3598
3599 @smallexample
3600 $ gcc -c x.adb y.adb z.c
3601 @end smallexample
3602
3603 @noindent
3604 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3605 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3606 The compiler generates three object files @file{x.o}, @file{y.o} and
3607 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3608 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3609 @ifclear vms
3610 except for
3611 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3612 @end ifclear
3613
3614 @node Switches for gcc
3615 @section Switches for @command{gcc}
3616
3617 @noindent
3618 The @command{gcc} command accepts switches that control the
3619 compilation process. These switches are fully described in this section.
3620 First we briefly list all the switches, in alphabetical order, then we
3621 describe the switches in more detail in functionally grouped sections.
3622
3623 More switches exist for GCC than those documented here, especially
3624 for specific targets. However, their use is not recommended as
3625 they may change code generation in ways that are incompatible with
3626 the Ada run-time library, or can cause inconsistencies between
3627 compilation units.
3628
3629 @menu
3630 * Output and Error Message Control::
3631 * Warning Message Control::
3632 * Debugging and Assertion Control::
3633 * Validity Checking::
3634 * Style Checking::
3635 * Run-Time Checks::
3636 * Stack Overflow Checking::
3637 * Using gcc for Syntax Checking::
3638 * Using gcc for Semantic Checking::
3639 * Compiling Different Versions of Ada::
3640 * Character Set Control::
3641 * File Naming Control::
3642 * Subprogram Inlining Control::
3643 * Auxiliary Output Control::
3644 * Debugging Control::
3645 * Exception Handling Control::
3646 * Units to Sources Mapping Files::
3647 * Integrated Preprocessing::
3648 * Code Generation Control::
3649 @ifset vms
3650 * Return Codes::
3651 @end ifset
3652 @end menu
3653
3654 @table @option
3655 @c !sort!
3656 @ifclear vms
3657 @cindex @option{-b} (@command{gcc})
3658 @item -b @var{target}
3659 Compile your program to run on @var{target}, which is the name of a
3660 system configuration. You must have a GNAT cross-compiler built if
3661 @var{target} is not the same as your host system.
3662
3663 @item -B@var{dir}
3664 @cindex @option{-B} (@command{gcc})
3665 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3666 from @var{dir} instead of the default location. Only use this switch
3667 when multiple versions of the GNAT compiler are available. See the
3668 @command{gcc} manual page for further details. You would normally use the
3669 @option{-b} or @option{-V} switch instead.
3670
3671 @item -c
3672 @cindex @option{-c} (@command{gcc})
3673 Compile. Always use this switch when compiling Ada programs.
3674
3675 Note: for some other languages when using @command{gcc}, notably in
3676 the case of C and C++, it is possible to use
3677 use @command{gcc} without a @option{-c} switch to
3678 compile and link in one step. In the case of GNAT, you
3679 cannot use this approach, because the binder must be run
3680 and @command{gcc} cannot be used to run the GNAT binder.
3681 @end ifclear
3682
3683 @item -fno-inline
3684 @cindex @option{-fno-inline} (@command{gcc})
3685 Suppresses all back-end inlining, even if other optimization or inlining
3686 switches are set.
3687 This includes suppression of inlining that results
3688 from the use of the pragma @code{Inline_Always}.
3689 See also @option{-gnatn} and @option{-gnatN}.
3690
3691 @item -fno-strict-aliasing
3692 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3693 Causes the compiler to avoid assumptions regarding non-aliasing
3694 of objects of different types. See
3695 @ref{Optimization and Strict Aliasing} for details.
3696
3697 @item -fstack-check
3698 @cindex @option{-fstack-check} (@command{gcc})
3699 Activates stack checking.
3700 See @ref{Stack Overflow Checking} for details of the use of this option.
3701
3702 @item ^-g^/DEBUG^
3703 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3704 Generate debugging information. This information is stored in the object
3705 file and copied from there to the final executable file by the linker,
3706 where it can be read by the debugger. You must use the
3707 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3708
3709 @item -gnat83
3710 @cindex @option{-gnat83} (@command{gcc})
3711 Enforce Ada 83 restrictions.
3712
3713 @item -gnat95
3714 @cindex @option{-gnat95} (@command{gcc})
3715 Enforce Ada 95 restrictions.
3716
3717 @item -gnat05
3718 @cindex @option{-gnat05} (@command{gcc})
3719 Allow full Ada 2005 features.
3720
3721 @item -gnata
3722 @cindex @option{-gnata} (@command{gcc})
3723 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3724 activated.
3725
3726 @item -gnatA
3727 @cindex @option{-gnatA} (@command{gcc})
3728 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3729 it will be ignored.
3730
3731 @item -gnatb
3732 @cindex @option{-gnatb} (@command{gcc})
3733 Generate brief messages to @file{stderr} even if verbose mode set.
3734
3735 @item -gnatc
3736 @cindex @option{-gnatc} (@command{gcc})
3737 Check syntax and semantics only (no code generation attempted).
3738
3739 @item -gnatd
3740 @cindex @option{-gnatd} (@command{gcc})
3741 Specify debug options for the compiler. The string of characters after
3742 the @option{-gnatd} specify the specific debug options. The possible
3743 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3744 compiler source file @file{debug.adb} for details of the implemented
3745 debug options. Certain debug options are relevant to applications
3746 programmers, and these are documented at appropriate points in this
3747 users guide.
3748
3749 @item -gnatD
3750 @cindex @option{-gnatD} (@command{gcc})
3751 Create expanded source files for source level debugging. This switch
3752 also suppress generation of cross-reference information
3753 (see @option{-gnatx}).
3754
3755 @item -gnatec=@var{path}
3756 @cindex @option{-gnatec} (@command{gcc})
3757 Specify a configuration pragma file
3758 @ifclear vms
3759 (the equal sign is optional)
3760 @end ifclear
3761 (@pxref{The Configuration Pragmas Files}).
3762
3763 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3764 @cindex @option{-gnateD} (@command{gcc})
3765 Defines a symbol, associated with value, for preprocessing.
3766 (@pxref{Integrated Preprocessing}).
3767
3768 @item -gnatef
3769 @cindex @option{-gnatef} (@command{gcc})
3770 Display full source path name in brief error messages.
3771
3772 @item -gnatem=@var{path}
3773 @cindex @option{-gnatem} (@command{gcc})
3774 Specify a mapping file
3775 @ifclear vms
3776 (the equal sign is optional)
3777 @end ifclear
3778 (@pxref{Units to Sources Mapping Files}).
3779
3780 @item -gnatep=@var{file}
3781 @cindex @option{-gnatep} (@command{gcc})
3782 Specify a preprocessing data file
3783 @ifclear vms
3784 (the equal sign is optional)
3785 @end ifclear
3786 (@pxref{Integrated Preprocessing}).
3787
3788 @item -gnatE
3789 @cindex @option{-gnatE} (@command{gcc})
3790 Full dynamic elaboration checks.
3791
3792 @item -gnatf
3793 @cindex @option{-gnatf} (@command{gcc})
3794 Full errors. Multiple errors per line, all undefined references, do not
3795 attempt to suppress cascaded errors.
3796
3797 @item -gnatF
3798 @cindex @option{-gnatF} (@command{gcc})
3799 Externals names are folded to all uppercase.
3800
3801 @item -gnatg
3802 @cindex @option{-gnatg} (@command{gcc})
3803 Internal GNAT implementation mode. This should not be used for
3804 applications programs, it is intended only for use by the compiler
3805 and its run-time library. For documentation, see the GNAT sources.
3806 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3807 are generated on unreferenced entities, and all warnings are treated
3808 as errors.
3809
3810 @item -gnatG
3811 @cindex @option{-gnatG} (@command{gcc})
3812 List generated expanded code in source form.
3813
3814 @item ^-gnath^/HELP^
3815 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3816 Output usage information. The output is written to @file{stdout}.
3817
3818 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3819 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3820 Identifier character set
3821 @ifclear vms
3822 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3823 @end ifclear
3824 @ifset vms
3825 For details of the possible selections for @var{c},
3826 see @ref{Character Set Control}.
3827 @end ifset
3828
3829 @item -gnatk=@var{n}
3830 @cindex @option{-gnatk} (@command{gcc})
3831 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3832
3833 @item -gnatl
3834 @cindex @option{-gnatl} (@command{gcc})
3835 Output full source listing with embedded error messages.
3836
3837 @item -gnatL
3838 @cindex @option{-gnatL} (@command{gcc})
3839 This switch is deprecated. You can use @option{--RTS=sjlj} instead to enable
3840 @code{setjmp/longjmp} exception mechanism.
3841
3842 @item -gnatm=@var{n}
3843 @cindex @option{-gnatm} (@command{gcc})
3844 Limit number of detected error or warning messages to @var{n}
3845 where @var{n} is in the range 1..999_999. The default setting if
3846 no switch is given is 9999. Compilation is terminated if this
3847 limit is exceeded.
3848
3849 @item -gnatn
3850 @cindex @option{-gnatn} (@command{gcc})
3851 Activate inlining for subprograms for which
3852 pragma @code{inline} is specified. This inlining is performed
3853 by the GCC back-end.
3854
3855 @item -gnatN
3856 @cindex @option{-gnatN} (@command{gcc})
3857 Activate front end inlining for subprograms for which
3858 pragma @code{Inline} is specified. This inlining is performed
3859 by the front end and will be visible in the
3860 @option{-gnatG} output.
3861 In some cases, this has proved more effective than the back end
3862 inlining resulting from the use of
3863 @option{-gnatn}.
3864 Note that
3865 @option{-gnatN} automatically implies
3866 @option{-gnatn} so it is not necessary
3867 to specify both options. There are a few cases that the back-end inlining
3868 catches that cannot be dealt with in the front-end.
3869
3870 @item -gnato
3871 @cindex @option{-gnato} (@command{gcc})
3872 Enable numeric overflow checking (which is not normally enabled by
3873 default). Not that division by zero is a separate check that is not
3874 controlled by this switch (division by zero checking is on by default).
3875
3876 @item -gnatp
3877 @cindex @option{-gnatp} (@command{gcc})
3878 Suppress all checks.
3879
3880 @item -gnatP
3881 @cindex @option{-gnatP} (@command{gcc})
3882 Enable polling. This is required on some systems (notably Windows NT) to
3883 obtain asynchronous abort and asynchronous transfer of control capability.
3884 See the description of pragma Polling in the GNAT Reference Manual for
3885 full details.
3886
3887 @item -gnatq
3888 @cindex @option{-gnatq} (@command{gcc})
3889 Don't quit; try semantics, even if parse errors.
3890
3891 @item -gnatQ
3892 @cindex @option{-gnatQ} (@command{gcc})
3893 Don't quit; generate @file{ALI} and tree files even if illegalities.
3894
3895 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3896 @cindex @option{-gnatR} (@command{gcc})
3897 Output representation information for declared types and objects.
3898
3899 @item -gnats
3900 @cindex @option{-gnats} (@command{gcc})
3901 Syntax check only.
3902
3903 @item -gnatS
3904 @cindex @option{-gnatS} (@command{gcc})
3905 Print package Standard.
3906
3907 @item -gnatt
3908 @cindex @option{-gnatt} (@command{gcc})
3909 Generate tree output file.
3910
3911 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3912 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3913 All compiler tables start at @var{nnn} times usual starting size.
3914
3915 @item -gnatu
3916 @cindex @option{-gnatu} (@command{gcc})
3917 List units for this compilation.
3918
3919 @item -gnatU
3920 @cindex @option{-gnatU} (@command{gcc})
3921 Tag all error messages with the unique string ``error:''
3922
3923 @item -gnatv
3924 @cindex @option{-gnatv} (@command{gcc})
3925 Verbose mode. Full error output with source lines to @file{stdout}.
3926
3927 @item -gnatV
3928 @cindex @option{-gnatV} (@command{gcc})
3929 Control level of validity checking. See separate section describing
3930 this feature.
3931
3932 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3933 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
3934 Warning mode where
3935 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3936 the exact warnings that
3937 are enabled or disabled (@pxref{Warning Message Control}).
3938
3939 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3940 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
3941 Wide character encoding method
3942 @ifclear vms
3943 (@var{e}=n/h/u/s/e/8).
3944 @end ifclear
3945 @ifset vms
3946 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3947 @end ifset
3948
3949 @item -gnatx
3950 @cindex @option{-gnatx} (@command{gcc})
3951 Suppress generation of cross-reference information.
3952
3953 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3954 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
3955 Enable built-in style checks (@pxref{Style Checking}).
3956
3957 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3958 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
3959 Distribution stub generation and compilation
3960 @ifclear vms
3961 (@var{m}=r/c for receiver/caller stubs).
3962 @end ifclear
3963 @ifset vms
3964 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3965 to be generated and compiled).
3966 @end ifset
3967
3968 @item -gnatZ
3969 This switch is deprecated. When zero cost exception handling is not the
3970 default and this is supported, you can use @option{--RTS=zcx} instead.
3971
3972 @item ^-I^/SEARCH=^@var{dir}
3973 @cindex @option{^-I^/SEARCH^} (@command{gcc})
3974 @cindex RTL
3975 Direct GNAT to search the @var{dir} directory for source files needed by
3976 the current compilation
3977 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3978
3979 @item ^-I-^/NOCURRENT_DIRECTORY^
3980 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
3981 @cindex RTL
3982 Except for the source file named in the command line, do not look for source
3983 files in the directory containing the source file named in the command line
3984 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3985
3986 @ifclear vms
3987 @item -mbig-switch
3988 @cindex @option{-mbig-switch} (@command{gcc})
3989 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3990 This standard gcc switch causes the compiler to use larger offsets in its
3991 jump table representation for @code{case} statements.
3992 This may result in less efficient code, but is sometimes necessary
3993 (for example on HP-UX targets)
3994 @cindex HP-UX and @option{-mbig-switch} option
3995 in order to compile large and/or nested @code{case} statements.
3996
3997 @item -o @var{file}
3998 @cindex @option{-o} (@command{gcc})
3999 This switch is used in @command{gcc} to redirect the generated object file
4000 and its associated ALI file. Beware of this switch with GNAT, because it may
4001 cause the object file and ALI file to have different names which in turn
4002 may confuse the binder and the linker.
4003 @end ifclear
4004
4005 @item -nostdinc
4006 @cindex @option{-nostdinc} (@command{gcc})
4007 Inhibit the search of the default location for the GNAT Run Time
4008 Library (RTL) source files.
4009
4010 @item -nostdlib
4011 @cindex @option{-nostdlib} (@command{gcc})
4012 Inhibit the search of the default location for the GNAT Run Time
4013 Library (RTL) ALI files.
4014
4015 @ifclear vms
4016 @item -O[@var{n}]
4017 @cindex @option{-O} (@command{gcc})
4018 @var{n} controls the optimization level.
4019
4020 @table @asis
4021 @item n = 0
4022 No optimization, the default setting if no @option{-O} appears
4023
4024 @item n = 1
4025 Normal optimization, the default if you specify @option{-O} without
4026 an operand.
4027
4028 @item n = 2
4029 Extensive optimization
4030
4031 @item n = 3
4032 Extensive optimization with automatic inlining of subprograms not
4033 specified by pragma @code{Inline}. This applies only to
4034 inlining within a unit. For details on control of inlining
4035 see @ref{Subprogram Inlining Control}.
4036 @end table
4037 @end ifclear
4038
4039 @ifset vms
4040 @item  /NOOPTIMIZE
4041 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4042 Equivalent to @option{/OPTIMIZE=NONE}.
4043 This is the default behavior in the absence of an @option{/OPTMIZE}
4044 qualifier.
4045
4046 @item /OPTIMIZE[=(keyword[,...])]
4047 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4048 Selects the level of optimization for your program. The supported
4049 keywords are as follows:
4050 @table @code
4051 @item   ALL
4052 Perform most optimizations, including those that
4053 are expensive.
4054 This is the default if the @option{/OPTMIZE} qualifier is supplied
4055 without keyword options.
4056
4057 @item   NONE
4058 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4059
4060 @item SOME
4061 Perform some optimizations, but omit ones that are costly.
4062
4063 @item   DEVELOPMENT
4064 Same as @code{SOME}.
4065
4066 @item   INLINING
4067 Full optimization, and also attempt automatic inlining of small
4068 subprograms within a unit even when pragma @code{Inline}
4069 is not specified (@pxref{Inlining of Subprograms}).
4070
4071 @item   UNROLL_LOOPS
4072 Try to unroll loops. This keyword may be specified together with
4073 any keyword above other than @code{NONE}. Loop unrolling
4074 usually, but not always, improves the performance of programs.
4075 @end table
4076 @end ifset
4077
4078 @ifclear vms
4079 @item -pass-exit-codes
4080 @cindex @option{-pass-exit-codes} (@command{gcc})
4081 Catch exit codes from the compiler and use the most meaningful as
4082 exit status.
4083 @end ifclear
4084
4085 @item --RTS=@var{rts-path}
4086 @cindex @option{--RTS} (@command{gcc})
4087 Specifies the default location of the runtime library. Same meaning as the
4088 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4089
4090 @item ^-S^/ASM^
4091 @cindex @option{^-S^/ASM^} (@command{gcc})
4092 ^Used in place of @option{-c} to^Used to^
4093 cause the assembler source file to be
4094 generated, using @file{^.s^.S^} as the extension,
4095 instead of the object file.
4096 This may be useful if you need to examine the generated assembly code.
4097
4098 @item ^-fverbose-asm^/VERBOSE_ASM^
4099 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4100 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4101 to cause the generated assembly code file to be annotated with variable
4102 names, making it significantly easier to follow.
4103
4104 @item ^-v^/VERBOSE^
4105 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4106 Show commands generated by the @command{gcc} driver. Normally used only for
4107 debugging purposes or if you need to be sure what version of the
4108 compiler you are executing.
4109
4110 @ifclear vms
4111 @item -V @var{ver}
4112 @cindex @option{-V} (@command{gcc})
4113 Execute @var{ver} version of the compiler. This is the @command{gcc}
4114 version, not the GNAT version.
4115 @end ifclear
4116
4117 @end table
4118
4119 @ifclear vms
4120 You may combine a sequence of GNAT switches into a single switch. For
4121 example, the combined switch
4122
4123 @cindex Combining GNAT switches
4124 @smallexample
4125 -gnatofi3
4126 @end smallexample
4127
4128 @noindent
4129 is equivalent to specifying the following sequence of switches:
4130
4131 @smallexample
4132 -gnato -gnatf -gnati3
4133 @end smallexample
4134 @end ifclear
4135
4136 @c NEED TO CHECK THIS FOR VMS
4137
4138 @noindent
4139 The following restrictions apply to the combination of switches
4140 in this manner:
4141
4142 @itemize @bullet
4143 @item
4144 The switch @option{-gnatc} if combined with other switches must come
4145 first in the string.
4146
4147 @item
4148 The switch @option{-gnats} if combined with other switches must come
4149 first in the string.
4150
4151 @item
4152 The switches
4153 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4154 may not be combined with any other switches.
4155
4156 @ifclear vms
4157 @item
4158 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4159 switch), then all further characters in the switch are interpreted
4160 as style modifiers (see description of @option{-gnaty}).
4161
4162 @item
4163 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4164 switch), then all further characters in the switch are interpreted
4165 as debug flags (see description of @option{-gnatd}).
4166
4167 @item
4168 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4169 switch), then all further characters in the switch are interpreted
4170 as warning mode modifiers (see description of @option{-gnatw}).
4171
4172 @item
4173 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4174 switch), then all further characters in the switch are interpreted
4175 as validity checking options (see description of @option{-gnatV}).
4176 @end ifclear
4177 @end itemize
4178
4179 @node Output and Error Message Control
4180 @subsection Output and Error Message Control
4181 @findex stderr
4182
4183 @noindent
4184 The standard default format for error messages is called ``brief format''.
4185 Brief format messages are written to @file{stderr} (the standard error
4186 file) and have the following form:
4187
4188 @smallexample
4189 e.adb:3:04: Incorrect spelling of keyword "function"
4190 e.adb:4:20: ";" should be "is"
4191 @end smallexample
4192
4193 @noindent
4194 The first integer after the file name is the line number in the file,
4195 and the second integer is the column number within the line.
4196 @code{glide} can parse the error messages
4197 and point to the referenced character.
4198 The following switches provide control over the error message
4199 format:
4200
4201 @table @option
4202 @c !sort!
4203 @item -gnatv
4204 @cindex @option{-gnatv} (@command{gcc})
4205 @findex stdout
4206 @ifclear vms
4207 The v stands for verbose.
4208 @end ifclear
4209 The effect of this setting is to write long-format error
4210 messages to @file{stdout} (the standard output file.
4211 The same program compiled with the
4212 @option{-gnatv} switch would generate:
4213
4214 @smallexample
4215 @cartouche
4216 3. funcion X (Q : Integer)
4217    |
4218 >>> Incorrect spelling of keyword "function"
4219 4. return Integer;
4220                  |
4221 >>> ";" should be "is"
4222 @end cartouche
4223 @end smallexample
4224
4225 @noindent
4226 The vertical bar indicates the location of the error, and the @samp{>>>}
4227 prefix can be used to search for error messages. When this switch is
4228 used the only source lines output are those with errors.
4229
4230 @item -gnatl
4231 @cindex @option{-gnatl} (@command{gcc})
4232 @ifclear vms
4233 The @code{l} stands for list.
4234 @end ifclear
4235 This switch causes a full listing of
4236 the file to be generated. The output might look as follows:
4237
4238 @smallexample
4239 @cartouche
4240  1. procedure E is
4241  2.    V : Integer;
4242  3.    funcion X (Q : Integer)
4243        |
4244     >>> Incorrect spelling of keyword "function"
4245  4.     return Integer;
4246                       |
4247     >>> ";" should be "is"
4248  5.    begin
4249  6.       return Q + Q;
4250  7.    end;
4251  8. begin
4252  9.    V := X + X;
4253 10.end E;
4254 @end cartouche
4255 @end smallexample
4256
4257 @noindent
4258 @findex stderr
4259 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4260 standard output is redirected, a brief summary is written to
4261 @file{stderr} (standard error) giving the number of error messages and
4262 warning messages generated.
4263
4264 @item -gnatU
4265 @cindex @option{-gnatU} (@command{gcc})
4266 This switch forces all error messages to be preceded by the unique
4267 string ``error:''. This means that error messages take a few more
4268 characters in space, but allows easy searching for and identification
4269 of error messages.
4270
4271 @item -gnatb
4272 @cindex @option{-gnatb} (@command{gcc})
4273 @ifclear vms
4274 The @code{b} stands for brief.
4275 @end ifclear
4276 This switch causes GNAT to generate the
4277 brief format error messages to @file{stderr} (the standard error
4278 file) as well as the verbose
4279 format message or full listing (which as usual is written to
4280 @file{stdout} (the standard output file).
4281
4282 @item -gnatm^^=^@var{n}
4283 @cindex @option{-gnatm} (@command{gcc})
4284 @ifclear vms
4285 The @code{m} stands for maximum.
4286 @end ifclear
4287 @var{n} is a decimal integer in the
4288 range of 1 to 999 and limits the number of error messages to be
4289 generated. For example, using @option{-gnatm2} might yield
4290
4291 @smallexample
4292 e.adb:3:04: Incorrect spelling of keyword "function"
4293 e.adb:5:35: missing ".."
4294 fatal error: maximum errors reached
4295 compilation abandoned
4296 @end smallexample
4297
4298 @item -gnatf
4299 @cindex @option{-gnatf} (@command{gcc})
4300 @cindex Error messages, suppressing
4301 @ifclear vms
4302 The @code{f} stands for full.
4303 @end ifclear
4304 Normally, the compiler suppresses error messages that are likely to be
4305 redundant. This switch causes all error
4306 messages to be generated. In particular, in the case of
4307 references to undefined variables. If a given variable is referenced
4308 several times, the normal format of messages is
4309 @smallexample
4310 e.adb:7:07: "V" is undefined (more references follow)
4311 @end smallexample
4312
4313 @noindent
4314 where the parenthetical comment warns that there are additional
4315 references to the variable @code{V}. Compiling the same program with the
4316 @option{-gnatf} switch yields
4317
4318 @smallexample
4319 e.adb:7:07: "V" is undefined
4320 e.adb:8:07: "V" is undefined
4321 e.adb:8:12: "V" is undefined
4322 e.adb:8:16: "V" is undefined
4323 e.adb:9:07: "V" is undefined
4324 e.adb:9:12: "V" is undefined
4325 @end smallexample
4326
4327 @noindent
4328 The @option{-gnatf} switch also generates additional information for
4329 some error messages.  Some examples are:
4330
4331 @itemize @bullet
4332 @item
4333 Full details on entities not available in high integrity mode
4334 @item
4335 Details on possibly non-portable unchecked conversion
4336 @item
4337 List possible interpretations for ambiguous calls
4338 @item
4339 Additional details on incorrect parameters
4340 @end itemize
4341
4342 @item -gnatq
4343 @cindex @option{-gnatq} (@command{gcc})
4344 @ifclear vms
4345 The @code{q} stands for quit (really ``don't quit'').
4346 @end ifclear
4347 In normal operation mode, the compiler first parses the program and
4348 determines if there are any syntax errors. If there are, appropriate
4349 error messages are generated and compilation is immediately terminated.
4350 This switch tells
4351 GNAT to continue with semantic analysis even if syntax errors have been
4352 found. This may enable the detection of more errors in a single run. On
4353 the other hand, the semantic analyzer is more likely to encounter some
4354 internal fatal error when given a syntactically invalid tree.
4355
4356 @item -gnatQ
4357 @cindex @option{-gnatQ} (@command{gcc})
4358 In normal operation mode, the @file{ALI} file is not generated if any
4359 illegalities are detected in the program. The use of @option{-gnatQ} forces
4360 generation of the @file{ALI} file. This file is marked as being in
4361 error, so it cannot be used for binding purposes, but it does contain
4362 reasonably complete cross-reference information, and thus may be useful
4363 for use by tools (e.g. semantic browsing tools or integrated development
4364 environments) that are driven from the @file{ALI} file. This switch
4365 implies @option{-gnatq}, since the semantic phase must be run to get a
4366 meaningful ALI file.
4367
4368 In addition, if @option{-gnatt} is also specified, then the tree file is
4369 generated even if there are illegalities. It may be useful in this case
4370 to also specify @option{-gnatq} to ensure that full semantic processing
4371 occurs. The resulting tree file can be processed by ASIS, for the purpose
4372 of providing partial information about illegal units, but if the error
4373 causes the tree to be badly malformed, then ASIS may crash during the
4374 analysis.
4375
4376 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4377 being in error, @command{gnatmake} will attempt to recompile the source when it
4378 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4379
4380 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4381 since ALI files are never generated if @option{-gnats} is set.
4382
4383 @end table
4384
4385 @node Warning Message Control
4386 @subsection Warning Message Control
4387 @cindex Warning messages
4388 @noindent
4389 In addition to error messages, which correspond to illegalities as defined
4390 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4391 situations.
4392
4393 First, the compiler considers some constructs suspicious and generates a
4394 warning message to alert you to a possible error. Second, if the
4395 compiler detects a situation that is sure to raise an exception at
4396 run time, it generates a warning message. The following shows an example
4397 of warning messages:
4398 @smallexample
4399 e.adb:4:24: warning: creation of object may raise Storage_Error
4400 e.adb:10:17: warning: static value out of range
4401 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4402 @end smallexample
4403
4404 @noindent
4405 GNAT considers a large number of situations as appropriate
4406 for the generation of warning messages. As always, warnings are not
4407 definite indications of errors. For example, if you do an out-of-range
4408 assignment with the deliberate intention of raising a
4409 @code{Constraint_Error} exception, then the warning that may be
4410 issued does not indicate an error. Some of the situations for which GNAT
4411 issues warnings (at least some of the time) are given in the following
4412 list. This list is not complete, and new warnings are often added to
4413 subsequent versions of GNAT. The list is intended to give a general idea
4414 of the kinds of warnings that are generated.
4415
4416 @itemize @bullet
4417 @item
4418 Possible infinitely recursive calls
4419
4420 @item
4421 Out-of-range values being assigned
4422
4423 @item
4424 Possible order of elaboration problems
4425
4426 @item
4427 Unreachable code
4428
4429 @item
4430 Fixed-point type declarations with a null range
4431
4432 @item
4433 Direct_IO or Sequential_IO instantiated with a type that has access values
4434
4435 @item
4436 Variables that are never assigned a value
4437
4438 @item
4439 Variables that are referenced before being initialized
4440
4441 @item
4442 Task entries with no corresponding @code{accept} statement
4443
4444 @item
4445 Duplicate accepts for the same task entry in a @code{select}
4446
4447 @item
4448 Objects that take too much storage
4449
4450 @item
4451 Unchecked conversion between types of differing sizes
4452
4453 @item
4454 Missing @code{return} statement along some execution path in a function
4455
4456 @item
4457 Incorrect (unrecognized) pragmas
4458
4459 @item
4460 Incorrect external names
4461
4462 @item
4463 Allocation from empty storage pool
4464
4465 @item
4466 Potentially blocking operation in protected type
4467
4468 @item
4469 Suspicious parenthesization of expressions
4470
4471 @item
4472 Mismatching bounds in an aggregate
4473
4474 @item
4475 Attempt to return local value by reference
4476
4477 @item
4478 Premature instantiation of a generic body
4479
4480 @item
4481 Attempt to pack aliased components
4482
4483 @item
4484 Out of bounds array subscripts
4485
4486 @item
4487 Wrong length on string assignment
4488
4489 @item
4490 Violations of style rules if style checking is enabled
4491
4492 @item
4493 Unused @code{with} clauses
4494
4495 @item
4496 @code{Bit_Order} usage that does not have any effect
4497
4498 @item
4499 @code{Standard.Duration} used to resolve universal fixed expression
4500
4501 @item
4502 Dereference of possibly null value
4503
4504 @item
4505 Declaration that is likely to cause storage error
4506
4507 @item
4508 Internal GNAT unit @code{with}'ed by application unit
4509
4510 @item
4511 Values known to be out of range at compile time
4512
4513 @item
4514 Unreferenced labels and variables
4515
4516 @item
4517 Address overlays that could clobber memory
4518
4519 @item
4520 Unexpected initialization when address clause present
4521
4522 @item
4523 Bad alignment for address clause
4524
4525 @item
4526 Useless type conversions
4527
4528 @item
4529 Redundant assignment statements and other redundant constructs
4530
4531 @item
4532 Useless exception handlers
4533
4534 @item
4535 Accidental hiding of name by child unit
4536
4537 @item
4538 Access before elaboration detected at compile time
4539
4540 @item
4541 A range in a @code{for} loop that is known to be null or might be null
4542
4543 @end itemize
4544
4545 @noindent
4546 The following switches are available to control the handling of
4547 warning messages:
4548
4549 @table @option
4550 @c !sort!
4551 @item -gnatwa
4552 @emph{Activate all optional errors.}
4553 @cindex @option{-gnatwa} (@command{gcc})
4554 This switch activates most optional warning messages, see remaining list
4555 in this section for details on optional warning messages that can be
4556 individually controlled.  The warnings that are not turned on by this
4557 switch are
4558 @option{-gnatwd} (implicit dereferencing),
4559 @option{-gnatwh} (hiding),
4560 and @option{-gnatwl} (elaboration warnings).
4561 All other optional warnings are turned on.
4562
4563 @item -gnatwA
4564 @emph{Suppress all optional errors.}
4565 @cindex @option{-gnatwA} (@command{gcc})
4566 This switch suppresses all optional warning messages, see remaining list
4567 in this section for details on optional warning messages that can be
4568 individually controlled.
4569
4570 @item -gnatwb
4571 @emph{Activate warnings on bad fixed values.}
4572 @cindex @option{-gnatwb} (@command{gcc})
4573 @cindex Bad fixed values
4574 @cindex Fixed-point Small value
4575 @cindex Small value
4576 This switch activates warnings for static fixed-point expressions whose
4577 value is not an exact multiple of Small. Such values are implementation
4578 dependent, since an implementation is free to choose either of the multiples
4579 that surround the value. GNAT always chooses the closer one, but this is not
4580 required behavior, and it is better to specify a value that is an exact
4581 multiple, ensuring predictable execution. The default is that such warnings
4582 are not generated.
4583
4584 @item -gnatwB
4585 @emph{Suppress warnings on bad fixed values.}
4586 @cindex @option{-gnatwB} (@command{gcc})
4587 This switch suppresses warnings for static fixed-point expressions whose
4588 value is not an exact multiple of Small.
4589
4590 @item -gnatwc
4591 @emph{Activate warnings on conditionals.}
4592 @cindex @option{-gnatwc} (@command{gcc})
4593 @cindex Conditionals, constant
4594 This switch activates warnings for conditional expressions used in
4595 tests that are known to be True or False at compile time. The default
4596 is that such warnings are not generated.
4597 Note that this warning does
4598 not get issued for the use of boolean variables or constants whose
4599 values are known at compile time, since this is a standard technique
4600 for conditional compilation in Ada, and this would generate too many
4601 ``false positive'' warnings.
4602 This warning can also be turned on using @option{-gnatwa}.
4603
4604 @item -gnatwC
4605 @emph{Suppress warnings on conditionals.}
4606 @cindex @option{-gnatwC} (@command{gcc})
4607 This switch suppresses warnings for conditional expressions used in
4608 tests that are known to be True or False at compile time.
4609
4610 @item -gnatwd
4611 @emph{Activate warnings on implicit dereferencing.}
4612 @cindex @option{-gnatwd} (@command{gcc})
4613 If this switch is set, then the use of a prefix of an access type
4614 in an indexed component, slice, or selected component without an
4615 explicit @code{.all} will generate a warning. With this warning
4616 enabled, access checks occur only at points where an explicit
4617 @code{.all} appears in the source code (assuming no warnings are
4618 generated as a result of this switch). The default is that such
4619 warnings are not generated.
4620 Note that @option{-gnatwa} does not affect the setting of
4621 this warning option.
4622
4623 @item -gnatwD
4624 @emph{Suppress warnings on implicit dereferencing.}
4625 @cindex @option{-gnatwD} (@command{gcc})
4626 @cindex Implicit dereferencing
4627 @cindex Dereferencing, implicit
4628 This switch suppresses warnings for implicit dereferences in
4629 indexed components, slices, and selected components.
4630
4631 @item -gnatwe
4632 @emph{Treat warnings as errors.}
4633 @cindex @option{-gnatwe} (@command{gcc})
4634 @cindex Warnings, treat as error
4635 This switch causes warning messages to be treated as errors.
4636 The warning string still appears, but the warning messages are counted
4637 as errors, and prevent the generation of an object file.
4638
4639 @item -gnatwf
4640 @emph{Activate warnings on unreferenced formals.}
4641 @cindex @option{-gnatwf} (@command{gcc})
4642 @cindex Formals, unreferenced
4643 This switch causes a warning to be generated if a formal parameter
4644 is not referenced in the body of the subprogram. This warning can
4645 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4646
4647 @item -gnatwF
4648 @emph{Suppress warnings on unreferenced formals.}
4649 @cindex @option{-gnatwF} (@command{gcc})
4650 This switch suppresses warnings for unreferenced formal
4651 parameters. Note that the
4652 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4653 effect of warning on unreferenced entities other than subprogram
4654 formals.
4655
4656 @item -gnatwg
4657 @emph{Activate warnings on unrecognized pragmas.}
4658 @cindex @option{-gnatwg} (@command{gcc})
4659 @cindex Pragmas, unrecognized
4660 This switch causes a warning to be generated if an unrecognized
4661 pragma is encountered. Apart from issuing this warning, the
4662 pragma is ignored and has no effect. This warning can
4663 also be turned on using @option{-gnatwa}. The default
4664 is that such warnings are issued (satisfying the Ada Reference
4665 Manual requirement that such warnings appear).
4666
4667 @item -gnatwG
4668 @emph{Suppress warnings on unrecognized pragmas.}
4669 @cindex @option{-gnatwG} (@command{gcc})
4670 This switch suppresses warnings for unrecognized pragmas.
4671
4672 @item -gnatwh
4673 @emph{Activate warnings on hiding.}
4674 @cindex @option{-gnatwh} (@command{gcc})
4675 @cindex Hiding of Declarations
4676 This switch activates warnings on hiding declarations.
4677 A declaration is considered hiding
4678 if it is for a non-overloadable entity, and it declares an entity with the
4679 same name as some other entity that is directly or use-visible. The default
4680 is that such warnings are not generated.
4681 Note that @option{-gnatwa} does not affect the setting of this warning option.
4682
4683 @item -gnatwH
4684 @emph{Suppress warnings on hiding.}
4685 @cindex @option{-gnatwH} (@command{gcc})
4686 This switch suppresses warnings on hiding declarations.
4687
4688 @item -gnatwi
4689 @emph{Activate warnings on implementation units.}
4690 @cindex @option{-gnatwi} (@command{gcc})
4691 This switch activates warnings for a @code{with} of an internal GNAT
4692 implementation unit, defined as any unit from the @code{Ada},
4693 @code{Interfaces}, @code{GNAT},
4694 ^^@code{DEC},^ or @code{System}
4695 hierarchies that is not
4696 documented in either the Ada Reference Manual or the GNAT
4697 Programmer's Reference Manual. Such units are intended only
4698 for internal implementation purposes and should not be @code{with}'ed
4699 by user programs. The default is that such warnings are generated
4700 This warning can also be turned on using @option{-gnatwa}.
4701
4702 @item -gnatwI
4703 @emph{Disable warnings on implementation units.}
4704 @cindex @option{-gnatwI} (@command{gcc})
4705 This switch disables warnings for a @code{with} of an internal GNAT
4706 implementation unit.
4707
4708 @item -gnatwj
4709 @emph{Activate warnings on obsolescent features (Annex J).}
4710 @cindex @option{-gnatwj} (@command{gcc})
4711 @cindex Features, obsolescent
4712 @cindex Obsolescent features
4713 If this warning option is activated, then warnings are generated for
4714 calls to subprograms marked with @code{pragma Obsolescent} and
4715 for use of features in Annex J of the Ada Reference Manual. In the
4716 case of Annex J, not all features are flagged. In particular use
4717 of the renamed packages (like @code{Text_IO}) and use of package
4718 @code{ASCII} are not flagged, since these are very common and
4719 would generate many annoying positive warnings. The default is that
4720 such warnings are not generated.
4721
4722 In addition to the above cases, warnings are also generated for
4723 GNAT features that have been provided in past versions but which
4724 have been superceded (typically by features in the new Ada standard).
4725 For example, @code{pragma Ravenscar} will be flagged since its
4726 function is replaced by @code{pragma Profile(Ravenscar)}.
4727
4728 Note that this warning option functions differently from the
4729 restriction @code{No_Obsolescent_Features} in two respects.
4730 First, the restriction applies only to annex J features.
4731 Second, the restriction does flag uses of package @code{ASCII}.
4732
4733 @item -gnatwJ
4734 @emph{Suppress warnings on obsolescent features (Annex J).}
4735 @cindex @option{-gnatwJ} (@command{gcc})
4736 This switch disables warnings on use of obsolescent features.
4737
4738 @item -gnatwk
4739 @emph{Activate warnings on variables that could be constants.}
4740 @cindex @option{-gnatwk} (@command{gcc})
4741 This switch activates warnings for variables that are initialized but
4742 never modified, and then could be declared constants.
4743
4744 @item -gnatwK
4745 @emph{Suppress warnings on variables that could be constants.}
4746 @cindex @option{-gnatwK} (@command{gcc})
4747 This switch disables warnings on variables that could be declared constants.
4748
4749 @item -gnatwl
4750 @emph{Activate warnings for missing elaboration pragmas.}
4751 @cindex @option{-gnatwl} (@command{gcc})
4752 @cindex Elaboration, warnings
4753 This switch activates warnings on missing
4754 @code{pragma Elaborate_All} statements.
4755 See the section in this guide on elaboration checking for details on
4756 when such pragma should be used. Warnings are also generated if you
4757 are using the static mode of elaboration, and a @code{pragma Elaborate}
4758 is encountered. The default is that such warnings
4759 are not generated.
4760 This warning is not automatically turned on by the use of @option{-gnatwa}.
4761
4762 @item -gnatwL
4763 @emph{Suppress warnings for missing elaboration pragmas.}
4764 @cindex @option{-gnatwL} (@command{gcc})
4765 This switch suppresses warnings on missing pragma Elaborate_All statements.
4766 See the section in this guide on elaboration checking for details on
4767 when such pragma should be used.
4768
4769 @item -gnatwm
4770 @emph{Activate warnings on modified but unreferenced variables.}
4771 @cindex @option{-gnatwm} (@command{gcc})
4772 This switch activates warnings for variables that are assigned (using
4773 an initialization value or with one or more assignment statements) but
4774 whose value is never read. The warning is suppressed for volatile
4775 variables and also for variables that are renamings of other variables
4776 or for which an address clause is given.
4777 This warning can also be turned on using @option{-gnatwa}.
4778
4779 @item -gnatwM
4780 @emph{Disable warnings on modified but unreferenced variables.}
4781 @cindex @option{-gnatwM} (@command{gcc})
4782 This switch disables warnings for variables that are assigned or
4783 initialized, but never read.
4784
4785 @item -gnatwn
4786 @emph{Set normal warnings mode.}
4787 @cindex @option{-gnatwn} (@command{gcc})
4788 This switch sets normal warning mode, in which enabled warnings are
4789 issued and treated as warnings rather than errors. This is the default
4790 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4791 an explicit @option{-gnatws} or
4792 @option{-gnatwe}. It also cancels the effect of the
4793 implicit @option{-gnatwe} that is activated by the
4794 use of @option{-gnatg}.
4795
4796 @item -gnatwo
4797 @emph{Activate warnings on address clause overlays.}
4798 @cindex @option{-gnatwo} (@command{gcc})
4799 @cindex Address Clauses, warnings
4800 This switch activates warnings for possibly unintended initialization
4801 effects of defining address clauses that cause one variable to overlap
4802 another. The default is that such warnings are generated.
4803 This warning can also be turned on using @option{-gnatwa}.
4804
4805 @item -gnatwO
4806 @emph{Suppress warnings on address clause overlays.}
4807 @cindex @option{-gnatwO} (@command{gcc})
4808 This switch suppresses warnings on possibly unintended initialization
4809 effects of defining address clauses that cause one variable to overlap
4810 another.
4811
4812 @item -gnatwp
4813 @emph{Activate warnings on ineffective pragma Inlines.}
4814 @cindex @option{-gnatwp} (@command{gcc})
4815 @cindex Inlining, warnings
4816 This switch activates warnings for failure of front end inlining
4817 (activated by @option{-gnatN}) to inline a particular call. There are
4818 many reasons for not being able to inline a call, including most
4819 commonly that the call is too complex to inline.
4820 This warning can also be turned on using @option{-gnatwa}.
4821
4822 @item -gnatwP
4823 @emph{Suppress warnings on ineffective pragma Inlines.}
4824 @cindex @option{-gnatwP} (@command{gcc})
4825 This switch suppresses warnings on ineffective pragma Inlines. If the
4826 inlining mechanism cannot inline a call, it will simply ignore the
4827 request silently.
4828
4829 @item -gnatwr
4830 @emph{Activate warnings on redundant constructs.}
4831 @cindex @option{-gnatwr} (@command{gcc})
4832 This switch activates warnings for redundant constructs. The following
4833 is the current list of constructs regarded as redundant:
4834 This warning can also be turned on using @option{-gnatwa}.
4835
4836 @itemize @bullet
4837 @item
4838 Assignment of an item to itself.
4839 @item
4840 Type conversion that converts an expression to its own type.
4841 @item
4842 Use of the attribute @code{Base} where @code{typ'Base} is the same
4843 as @code{typ}.
4844 @item
4845 Use of pragma @code{Pack} when all components are placed by a record
4846 representation clause.
4847 @item
4848 Exception handler containing only a reraise statement (raise with no
4849 operand) which has no effect.
4850 @item
4851 Use of the operator abs on an operand that is known at compile time
4852 to be non-negative
4853 @item
4854 Comparison of boolean expressions to an explicit True value.
4855 @end itemize
4856
4857 @item -gnatwR
4858 @emph{Suppress warnings on redundant constructs.}
4859 @cindex @option{-gnatwR} (@command{gcc})
4860 This switch suppresses warnings for redundant constructs.
4861
4862 @item -gnatws
4863 @emph{Suppress all warnings.}
4864 @cindex @option{-gnatws} (@command{gcc})
4865 This switch completely suppresses the
4866 output of all warning messages from the GNAT front end.
4867 Note that it does not suppress warnings from the @command{gcc} back end.
4868 To suppress these back end warnings as well, use the switch @option{-w}
4869 in addition to @option{-gnatws}.
4870
4871 @item -gnatwu
4872 @emph{Activate warnings on unused entities.}
4873 @cindex @option{-gnatwu} (@command{gcc})
4874 This switch activates warnings to be generated for entities that
4875 are declared but not referenced, and for units that are @code{with}'ed
4876 and not
4877 referenced. In the case of packages, a warning is also generated if
4878 no entities in the package are referenced. This means that if the package
4879 is referenced but the only references are in @code{use}
4880 clauses or @code{renames}
4881 declarations, a warning is still generated. A warning is also generated
4882 for a generic package that is @code{with}'ed but never instantiated.
4883 In the case where a package or subprogram body is compiled, and there
4884 is a @code{with} on the corresponding spec
4885 that is only referenced in the body,
4886 a warning is also generated, noting that the
4887 @code{with} can be moved to the body. The default is that
4888 such warnings are not generated.
4889 This switch also activates warnings on unreferenced formals
4890 (it includes the effect of @option{-gnatwf}).
4891 This warning can also be turned on using @option{-gnatwa}.
4892
4893 @item -gnatwU
4894 @emph{Suppress warnings on unused entities.}
4895 @cindex @option{-gnatwU} (@command{gcc})
4896 This switch suppresses warnings for unused entities and packages.
4897 It also turns off warnings on unreferenced formals (and thus includes
4898 the effect of @option{-gnatwF}).
4899
4900 @item -gnatwv
4901 @emph{Activate warnings on unassigned variables.}
4902 @cindex @option{-gnatwv} (@command{gcc})
4903 @cindex Unassigned variable warnings
4904 This switch activates warnings for access to variables which
4905 may not be properly initialized. The default is that
4906 such warnings are generated.
4907
4908 @item -gnatwV
4909 @emph{Suppress warnings on unassigned variables.}
4910 @cindex @option{-gnatwV} (@command{gcc})
4911 This switch suppresses warnings for access to variables which
4912 may not be properly initialized.
4913
4914 @item -gnatwx
4915 @emph{Activate warnings on Export/Import pragmas.}
4916 @cindex @option{-gnatwx} (@command{gcc})
4917 @cindex Export/Import pragma warnings
4918 This switch activates warnings on Export/Import pragmas when
4919 the compiler detects a possible conflict between the Ada and
4920 foreign language calling sequences. For example, the use of
4921 default parameters in a convention C procedure is dubious
4922 because the C compiler cannot supply the proper default, so
4923 a warning is issued. The default is that such warnings are
4924 generated.
4925
4926 @item -gnatwX
4927 @emph{Suppress warnings on Export/Import pragmas.}
4928 @cindex @option{-gnatwX} (@command{gcc})
4929 This switch suppresses warnings on Export/Import pragmas.
4930 The sense of this is that you are telling the compiler that
4931 you know what you are doing in writing the pragma, and it
4932 should not complain at you.
4933
4934 @item -gnatwz
4935 @emph{Activate warnings on unchecked conversions.}
4936 @cindex @option{-gnatwz} (@command{gcc})
4937 @cindex Unchecked_Conversion warnings
4938 This switch activates warnings for unchecked conversions
4939 where the types are known at compile time to have different
4940 sizes. The default
4941 is that such warnings are generated.
4942
4943 @item -gnatwZ
4944 @emph{Suppress warnings on unchecked conversions.}
4945 @cindex @option{-gnatwZ} (@command{gcc})
4946 This switch suppresses warnings for unchecked conversions
4947 where the types are known at compile time to have different
4948 sizes.
4949
4950 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4951 @cindex @option{-Wuninitialized}
4952 The warnings controlled by the @option{-gnatw} switch are generated by the
4953 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4954 can provide additional warnings. One such useful warning is provided by
4955 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4956 conjunction with tunrning on optimization mode. This causes the flow
4957 analysis circuits of the back end optimizer to output additional
4958 warnings about uninitialized variables.
4959
4960 @item ^-w^/NO_BACK_END_WARNINGS^
4961 @cindex @option{-w}
4962 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4963 be used in conjunction with @option{-gnatws} to ensure that all warnings
4964 are suppressed during the entire compilation process.
4965
4966 @end table
4967
4968 @noindent
4969 @ifclear vms
4970 A string of warning parameters can be used in the same parameter. For example:
4971
4972 @smallexample
4973 -gnatwaLe
4974 @end smallexample
4975
4976 @noindent
4977 will turn on all optional warnings except for elaboration pragma warnings,
4978 and also specify that warnings should be treated as errors.
4979 @end ifclear
4980 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4981
4982 @table @option
4983 @c !sort!
4984 @item -gnatwC
4985 @item -gnatwD
4986 @item -gnatwF
4987 @item -gnatwg
4988 @item -gnatwH
4989 @item -gnatwi
4990 @item -gnatwJ
4991 @item -gnatwK
4992 @item -gnatwL
4993 @item -gnatwM
4994 @item -gnatwn
4995 @item -gnatwo
4996 @item -gnatwP
4997 @item -gnatwR
4998 @item -gnatwU
4999 @item -gnatwv
5000 @item -gnatwz
5001 @item -gnatwx
5002
5003 @end table
5004
5005 @node Debugging and Assertion Control
5006 @subsection Debugging and Assertion Control
5007
5008 @table @option
5009 @item -gnata
5010 @cindex @option{-gnata} (@command{gcc})
5011 @findex Assert
5012 @findex Debug
5013 @cindex Assertions
5014
5015 @noindent
5016 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5017 are ignored. This switch, where @samp{a} stands for assert, causes
5018 @code{Assert} and @code{Debug} pragmas to be activated.
5019
5020 The pragmas have the form:
5021
5022 @smallexample
5023 @cartouche
5024    @b{pragma} Assert (@var{Boolean-expression} [,
5025                       @var{static-string-expression}])
5026    @b{pragma} Debug (@var{procedure call})
5027 @end cartouche
5028 @end smallexample
5029
5030 @noindent
5031 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5032 If the result is @code{True}, the pragma has no effect (other than
5033 possible side effects from evaluating the expression). If the result is
5034 @code{False}, the exception @code{Assert_Failure} declared in the package
5035 @code{System.Assertions} is
5036 raised (passing @var{static-string-expression}, if present, as the
5037 message associated with the exception). If no string expression is
5038 given the default is a string giving the file name and line number
5039 of the pragma.
5040
5041 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5042 @code{pragma Debug} may appear within a declaration sequence, allowing
5043 debugging procedures to be called between declarations.
5044
5045 @ifset vms
5046 @item /DEBUG[=debug-level]
5047 @itemx  /NODEBUG
5048 Specifies how much debugging information is to be included in
5049 the resulting object file where 'debug-level' is one of the following:
5050 @table @code
5051 @item   TRACEBACK
5052 Include both debugger symbol records and traceback
5053 the object file.
5054 This is the default setting.
5055 @item   ALL
5056 Include both debugger symbol records and traceback in
5057 object file.
5058 @item   NONE
5059 Excludes both debugger symbol records and traceback
5060 the object file. Same as /NODEBUG.
5061 @item   SYMBOLS
5062 Includes only debugger symbol records in the object
5063 file. Note that this doesn't include traceback information.
5064 @end table
5065 @end ifset
5066 @end table
5067
5068 @node Validity Checking
5069 @subsection Validity Checking
5070 @findex Validity Checking
5071
5072 @noindent
5073 The Ada 95 Reference Manual has specific requirements for checking
5074 for invalid values. In particular, RM 13.9.1 requires that the
5075 evaluation of invalid values (for example from unchecked conversions),
5076 not result in erroneous execution. In GNAT, the result of such an
5077 evaluation in normal default mode is to either use the value
5078 unmodified, or to raise Constraint_Error in those cases where use
5079 of the unmodified value would cause erroneous execution. The cases
5080 where unmodified values might lead to erroneous execution are case
5081 statements (where a wild jump might result from an invalid value),
5082 and subscripts on the left hand side (where memory corruption could
5083 occur as a result of an invalid value).
5084
5085 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5086 checking mode.
5087 @ifclear vms
5088 The @code{x} argument is a string of letters that
5089 indicate validity checks that are performed or not performed in addition
5090 to the default checks described above.
5091 @end ifclear
5092 @ifset vms
5093 The options allowed for this qualifier
5094 indicate validity checks that are performed or not performed in addition
5095 to the default checks described above.
5096 @end ifset
5097
5098 @table @option
5099 @c !sort!
5100 @item -gnatVa
5101 @emph{All validity checks.}
5102 @cindex @option{-gnatVa} (@command{gcc})
5103 All validity checks are turned on.
5104 @ifclear vms
5105 That is, @option{-gnatVa} is
5106 equivalent to @option{gnatVcdfimorst}.
5107 @end ifclear
5108
5109 @item -gnatVc
5110 @emph{Validity checks for copies.}
5111 @cindex @option{-gnatVc} (@command{gcc})
5112 The right hand side of assignments, and the initializing values of
5113 object declarations are validity checked.
5114
5115 @item -gnatVd
5116 @emph{Default (RM) validity checks.}
5117 @cindex @option{-gnatVd} (@command{gcc})
5118 Some validity checks are done by default following normal Ada semantics
5119 (RM 13.9.1 (9-11)).
5120 A check is done in case statements that the expression is within the range
5121 of the subtype. If it is not, Constraint_Error is raised.
5122 For assignments to array components, a check is done that the expression used
5123 as index is within the range. If it is not, Constraint_Error is raised.
5124 Both these validity checks may be turned off using switch @option{-gnatVD}.
5125 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5126 switch @option{-gnatVd} will leave the checks turned on.
5127 Switch @option{-gnatVD} should be used only if you are sure that all such
5128 expressions have valid values. If you use this switch and invalid values
5129 are present, then the program is erroneous, and wild jumps or memory
5130 overwriting may occur.
5131
5132 @item -gnatVf
5133 @emph{Validity checks for floating-point values.}
5134 @cindex @option{-gnatVf} (@command{gcc})
5135 In the absence of this switch, validity checking occurs only for discrete
5136 values. If @option{-gnatVf} is specified, then validity checking also applies
5137 for floating-point values, and NaN's and infinities are considered invalid,
5138 as well as out of range values for constrained types. Note that this means
5139 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5140 in which floating-point values are checked depends on the setting of other
5141 options. For example,
5142 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5143 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5144 (the order does not matter) specifies that floating-point parameters of mode
5145 @code{in} should be validity checked.
5146
5147 @item -gnatVi
5148 @emph{Validity checks for @code{in} mode parameters}
5149 @cindex @option{-gnatVi} (@command{gcc})
5150 Arguments for parameters of mode @code{in} are validity checked in function
5151 and procedure calls at the point of call.
5152
5153 @item -gnatVm
5154 @emph{Validity checks for @code{in out} mode parameters.}
5155 @cindex @option{-gnatVm} (@command{gcc})
5156 Arguments for parameters of mode @code{in out} are validity checked in
5157 procedure calls at the point of call. The @code{'m'} here stands for
5158 modify, since this concerns parameters that can be modified by the call.
5159 Note that there is no specific option to test @code{out} parameters,
5160 but any reference within the subprogram will be tested in the usual
5161 manner, and if an invalid value is copied back, any reference to it
5162 will be subject to validity checking.
5163
5164 @item -gnatVn
5165 @emph{No validity checks.}
5166 @cindex @option{-gnatVn} (@command{gcc})
5167 This switch turns off all validity checking, including the default checking
5168 for case statements and left hand side subscripts. Note that the use of
5169 the switch @option{-gnatp} suppresses all run-time checks, including
5170 validity checks, and thus implies @option{-gnatVn}. When this switch
5171 is used, it cancels any other @option{-gnatV} previously issued.
5172
5173 @item -gnatVo
5174 @emph{Validity checks for operator and attribute operands.}
5175 @cindex @option{-gnatVo} (@command{gcc})
5176 Arguments for predefined operators and attributes are validity checked.
5177 This includes all operators in package @code{Standard},
5178 the shift operators defined as intrinsic in package @code{Interfaces}
5179 and operands for attributes such as @code{Pos}. Checks are also made
5180 on individual component values for composite comparisons.
5181
5182 @item -gnatVp
5183 @emph{Validity checks for parameters.}
5184 @cindex @option{-gnatVp} (@command{gcc})
5185 This controls the treatment of parameters within a subprogram (as opposed
5186 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5187 of parameters on a call. If either of these call options is used, then
5188 normally an assumption is made within a subprogram that the input arguments
5189 have been validity checking at the point of call, and do not need checking
5190 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5191 is not made, and parameters are not assumed to be valid, so their validity
5192 will be checked (or rechecked) within the subprogram.
5193
5194 @item -gnatVr
5195 @emph{Validity checks for function returns.}
5196 @cindex @option{-gnatVr} (@command{gcc})
5197 The expression in @code{return} statements in functions is validity
5198 checked.
5199
5200 @item -gnatVs
5201 @emph{Validity checks for subscripts.}
5202 @cindex @option{-gnatVs} (@command{gcc})
5203 All subscripts expressions are checked for validity, whether they appear
5204 on the right side or left side (in default mode only left side subscripts
5205 are validity checked).
5206
5207 @item -gnatVt
5208 @emph{Validity checks for tests.}
5209 @cindex @option{-gnatVt} (@command{gcc})
5210 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5211 statements are checked, as well as guard expressions in entry calls.
5212
5213 @end table
5214
5215 @noindent
5216 The @option{-gnatV} switch may be followed by
5217 ^a string of letters^a list of options^
5218 to turn on a series of validity checking options.
5219 For example,
5220 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5221 specifies that in addition to the default validity checking, copies and
5222 function return expressions are to be validity checked.
5223 In order to make it easier
5224 to specify the desired combination of effects,
5225 @ifclear vms
5226 the upper case letters @code{CDFIMORST} may
5227 be used to turn off the corresponding lower case option.
5228 @end ifclear
5229 @ifset vms
5230 the prefix @code{NO} on an option turns off the corresponding validity
5231 checking:
5232 @itemize @bullet
5233 @item @code{NOCOPIES}
5234 @item @code{NODEFAULT}
5235 @item @code{NOFLOATS}
5236 @item @code{NOIN_PARAMS}
5237 @item @code{NOMOD_PARAMS}
5238 @item @code{NOOPERANDS}
5239 @item @code{NORETURNS}
5240 @item @code{NOSUBSCRIPTS}
5241 @item @code{NOTESTS}
5242 @end itemize
5243 @end ifset
5244 Thus
5245 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5246 turns on all validity checking options except for
5247 checking of @code{@b{in out}} procedure arguments.
5248
5249 The specification of additional validity checking generates extra code (and
5250 in the case of @option{-gnatVa} the code expansion can be substantial.
5251 However, these additional checks can be very useful in detecting
5252 uninitialized variables, incorrect use of unchecked conversion, and other
5253 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5254 is useful in conjunction with the extra validity checking, since this
5255 ensures that wherever possible uninitialized variables have invalid values.
5256
5257 See also the pragma @code{Validity_Checks} which allows modification of
5258 the validity checking mode at the program source level, and also allows for
5259 temporary disabling of validity checks.
5260
5261 @node Style Checking
5262 @subsection Style Checking
5263 @findex Style checking
5264
5265 @noindent
5266 The @option{-gnaty^x^(option,option,...)^} switch
5267 @cindex @option{-gnaty} (@command{gcc})
5268 causes the compiler to
5269 enforce specified style rules. A limited set of style rules has been used
5270 in writing the GNAT sources themselves. This switch allows user programs
5271 to activate all or some of these checks. If the source program fails a
5272 specified style check, an appropriate warning message is given, preceded by
5273 the character sequence ``(style)''.
5274 @ifset vms
5275 @code{(option,option,...)} is a sequence of keywords
5276 @end ifset
5277 @ifclear vms
5278 The string @var{x} is a sequence of letters or digits
5279 @end ifclear
5280 indicating the particular style
5281 checks to be performed. The following checks are defined:
5282
5283 @table @option
5284 @c !sort!
5285 @item 1-9
5286 @emph{Specify indentation level.}
5287 If a digit from 1-9 appears
5288 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5289 then proper indentation is checked, with the digit indicating the
5290 indentation level required.
5291 The general style of required indentation is as specified by
5292 the examples in the Ada Reference Manual. Full line comments must be
5293 aligned with the @code{--} starting on a column that is a multiple of
5294 the alignment level.
5295
5296 @item ^a^ATTRIBUTE^
5297 @emph{Check attribute casing.}
5298 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5299 then attribute names, including the case of keywords such as @code{digits}
5300 used as attributes names, must be written in mixed case, that is, the
5301 initial letter and any letter following an underscore must be uppercase.
5302 All other letters must be lowercase.
5303
5304 @item ^b^BLANKS^
5305 @emph{Blanks not allowed at statement end.}
5306 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5307 trailing blanks are not allowed at the end of statements. The purpose of this
5308 rule, together with h (no horizontal tabs), is to enforce a canonical format
5309 for the use of blanks to separate source tokens.
5310
5311 @item ^c^COMMENTS^
5312 @emph{Check comments.}
5313 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5314 then comments must meet the following set of rules:
5315
5316 @itemize @bullet
5317
5318 @item
5319 The ``@code{--}'' that starts the column must either start in column one,
5320 or else at least one blank must precede this sequence.
5321
5322 @item
5323 Comments that follow other tokens on a line must have at least one blank
5324 following the ``@code{--}'' at the start of the comment.
5325
5326 @item
5327 Full line comments must have two blanks following the ``@code{--}'' that
5328 starts the comment, with the following exceptions.
5329
5330 @item
5331 A line consisting only of the ``@code{--}'' characters, possibly preceded
5332 by blanks is permitted.
5333
5334 @item
5335 A comment starting with ``@code{--x}'' where @code{x} is a special character
5336 is permitted.
5337 This allows proper processing of the output generated by specialized tools
5338 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5339 annotation
5340 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5341 special character is defined as being in one of the ASCII ranges
5342 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5343 Note that this usage is not permitted
5344 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5345
5346 @item
5347 A line consisting entirely of minus signs, possibly preceded by blanks, is
5348 permitted. This allows the construction of box comments where lines of minus
5349 signs are used to form the top and bottom of the box.
5350
5351 @item
5352 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5353 least one blank follows the initial ``@code{--}''. Together with the preceding
5354 rule, this allows the construction of box comments, as shown in the following
5355 example:
5356 @smallexample
5357 ---------------------------
5358 -- This is a box comment --
5359 -- with two text lines.  --
5360 ---------------------------
5361 @end smallexample
5362 @end itemize
5363
5364 @item ^d^DOS_LINE_ENDINGS^
5365 @emph{Check no DOS line terminators present.}
5366 If the ^letter d^word NOCRLF^ appears in the string after @option{-gnaty}
5367 then all lines must be terminated by a single ASCII.LF character (in
5368 particular the DOS line terminator sequence CR/LF is not allowed).
5369
5370 @item ^e^END^
5371 @emph{Check end/exit labels.}
5372 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5373 optional labels on @code{end} statements ending subprograms and on
5374 @code{exit} statements exiting named loops, are required to be present.
5375
5376 @item ^f^VTABS^
5377 @emph{No form feeds or vertical tabs.}
5378 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5379 neither form feeds nor vertical tab characters are permitted
5380 in the source text.
5381
5382 @item ^h^HTABS^
5383 @emph{No horizontal tabs.}
5384 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5385 horizontal tab characters are not permitted in the source text.
5386 Together with the b (no blanks at end of line) check, this
5387 enforces a canonical form for the use of blanks to separate
5388 source tokens.
5389
5390 @item ^i^IF_THEN^
5391 @emph{Check if-then layout.}
5392 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5393 then the keyword @code{then} must appear either on the same
5394 line as corresponding @code{if}, or on a line on its own, lined
5395 up under the @code{if} with at least one non-blank line in between
5396 containing all or part of the condition to be tested.
5397
5398 @item ^k^KEYWORD^
5399 @emph{Check keyword casing.}
5400 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5401 all keywords must be in lower case (with the exception of keywords
5402 such as @code{digits} used as attribute names to which this check
5403 does not apply).
5404
5405 @item ^l^LAYOUT^
5406 @emph{Check layout.}
5407 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5408 layout of statement and declaration constructs must follow the
5409 recommendations in the Ada Reference Manual, as indicated by the
5410 form of the syntax rules. For example an @code{else} keyword must
5411 be lined up with the corresponding @code{if} keyword.
5412
5413 There are two respects in which the style rule enforced by this check
5414 option are more liberal than those in the Ada Reference Manual. First
5415 in the case of record declarations, it is permissible to put the
5416 @code{record} keyword on the same line as the @code{type} keyword, and
5417 then the @code{end} in @code{end record} must line up under @code{type}.
5418 For example, either of the following two layouts is acceptable:
5419
5420 @smallexample @c ada
5421 @cartouche
5422 type q is record
5423    a : integer;
5424    b : integer;
5425 end record;
5426
5427 type q is
5428    record
5429       a : integer;
5430       b : integer;
5431    end record;
5432 @end cartouche
5433 @end smallexample
5434
5435 @noindent
5436 Second, in the case of a block statement, a permitted alternative
5437 is to put the block label on the same line as the @code{declare} or
5438 @code{begin} keyword, and then line the @code{end} keyword up under
5439 the block label. For example both the following are permitted:
5440
5441 @smallexample @c ada
5442 @cartouche
5443 Block : declare
5444    A : Integer := 3;
5445 begin
5446    Proc (A, A);
5447 end Block;
5448
5449 Block :
5450    declare
5451       A : Integer := 3;
5452    begin
5453       Proc (A, A);
5454    end Block;
5455 @end cartouche
5456 @end smallexample
5457
5458 @noindent
5459 The same alternative format is allowed for loops. For example, both of
5460 the following are permitted:
5461
5462 @smallexample @c ada
5463 @cartouche
5464 Clear : while J < 10 loop
5465    A (J) := 0;
5466 end loop Clear;
5467
5468 Clear :
5469    while J < 10 loop
5470       A (J) := 0;
5471    end loop Clear;
5472 @end cartouche
5473 @end smallexample
5474
5475 @item ^Lnnn^MAX_NESTING=nnn^
5476 @emph{Set maximum nesting level}
5477 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5478 the range 0-999, appears in the string after @option{-gnaty} then the
5479 maximum level of nesting of constructs (including subprograms, loops,
5480 blocks, packages, and conditionals) may not exceed the given value. A
5481 value of zero disconnects this style check.
5482
5483 @item ^m^LINE_LENGTH^
5484 @emph{Check maximum line length.}
5485 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5486 then the length of source lines must not exceed 79 characters, including
5487 any trailing blanks. The value of 79 allows convenient display on an
5488 80 character wide device or window, allowing for possible special
5489 treatment of 80 character lines. Note that this count is of raw
5490 characters in the source text. This means that a tab character counts
5491 as one character in this count and a wide character sequence counts as
5492 several characters (however many are needed in the encoding).
5493
5494 @item ^Mnnn^MAX_LENGTH=nnn^
5495 @emph{Set maximum line length.}
5496 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5497 the string after @option{-gnaty} then the length of lines must not exceed the
5498 given value.
5499
5500 @item ^n^STANDARD_CASING^
5501 @emph{Check casing of entities in Standard.}
5502 If the ^letter n^word STANDARD_CASING^ appears in the string
5503 after @option{-gnaty} then any identifier from Standard must be cased
5504 to match the presentation in the Ada Reference Manual (for example,
5505 @code{Integer} and @code{ASCII.NUL}).
5506
5507 @item ^o^ORDERED_SUBPROGRAMS^
5508 @emph{Check order of subprogram bodies.}
5509 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5510 after @option{-gnaty} then all subprogram bodies in a given scope
5511 (e.g. a package body) must be in alphabetical order. The ordering
5512 rule uses normal Ada rules for comparing strings, ignoring casing
5513 of letters, except that if there is a trailing numeric suffix, then
5514 the value of this suffix is used in the ordering (e.g. Junk2 comes
5515 before Junk10).
5516
5517 @item ^p^PRAGMA^
5518 @emph{Check pragma casing.}
5519 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5520 pragma names must be written in mixed case, that is, the
5521 initial letter and any letter following an underscore must be uppercase.
5522 All other letters must be lowercase.
5523
5524 @item ^r^REFERENCES^
5525 @emph{Check references.}
5526 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5527 then all identifier references must be cased in the same way as the
5528 corresponding declaration. No specific casing style is imposed on
5529 identifiers. The only requirement is for consistency of references
5530 with declarations.
5531
5532 @item ^s^SPECS^
5533 @emph{Check separate specs.}
5534 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5535 separate declarations (``specs'') are required for subprograms (a
5536 body is not allowed to serve as its own declaration). The only
5537 exception is that parameterless library level procedures are
5538 not required to have a separate declaration. This exception covers
5539 the most frequent form of main program procedures.
5540
5541 @item ^t^TOKEN^
5542 @emph{Check token spacing.}
5543 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5544 the following token spacing rules are enforced:
5545
5546 @itemize @bullet
5547
5548 @item
5549 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5550
5551 @item
5552 The token @code{=>} must be surrounded by spaces.
5553
5554 @item
5555 The token @code{<>} must be preceded by a space or a left parenthesis.
5556
5557 @item
5558 Binary operators other than @code{**} must be surrounded by spaces.
5559 There is no restriction on the layout of the @code{**} binary operator.
5560
5561 @item
5562 Colon must be surrounded by spaces.
5563
5564 @item
5565 Colon-equal (assignment, initialization) must be surrounded by spaces.
5566
5567 @item
5568 Comma must be the first non-blank character on the line, or be
5569 immediately preceded by a non-blank character, and must be followed
5570 by a space.
5571
5572 @item
5573 If the token preceding a left parenthesis ends with a letter or digit, then
5574 a space must separate the two tokens.
5575
5576 @item
5577 A right parenthesis must either be the first non-blank character on
5578 a line, or it must be preceded by a non-blank character.
5579
5580 @item
5581 A semicolon must not be preceded by a space, and must not be followed by
5582 a non-blank character.
5583
5584 @item
5585 A unary plus or minus may not be followed by a space.
5586
5587 @item
5588 A vertical bar must be surrounded by spaces.
5589 @end itemize
5590
5591 @item ^x^XTRA_PARENS^
5592 @emph{Check extra parentheses.}
5593 Check for the use of an unnecessary extra level of parentheses (C-style)
5594 around conditions in @code{if} statements, @code{while} statements and
5595 @code{exit} statements.
5596
5597 @end table
5598
5599 @noindent
5600 In the above rules, appearing in column one is always permitted, that is,
5601 counts as meeting either a requirement for a required preceding space,
5602 or as meeting a requirement for no preceding space.
5603
5604 Appearing at the end of a line is also always permitted, that is, counts
5605 as meeting either a requirement for a following space, or as meeting
5606 a requirement for no following space.
5607
5608 @noindent
5609 If any of these style rules is violated, a message is generated giving
5610 details on the violation. The initial characters of such messages are
5611 always ``@code{(style)}''. Note that these messages are treated as warning
5612 messages, so they normally do not prevent the generation of an object
5613 file. The @option{-gnatwe} switch can be used to treat warning messages,
5614 including style messages, as fatal errors.
5615
5616 The switch
5617 @ifclear vms
5618 @option{-gnaty} on its own (that is not
5619 followed by any letters or digits),
5620 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5621 options enabled with the exception of -gnatyo,
5622 @end ifclear
5623 @ifset vms
5624 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5625 the exception of ORDERED_SUBPROGRAMS,
5626 @end ifset
5627 with an indentation level of 3. This is the standard
5628 checking option that is used for the GNAT sources.
5629
5630 The switch
5631 @ifclear vms
5632 @option{-gnatyN}
5633 @end ifclear
5634 @ifset vms
5635 /STYLE_CHECKS=NONE
5636 @end ifset
5637 clears any previously set style checks.
5638
5639 @node Run-Time Checks
5640 @subsection Run-Time Checks
5641 @cindex Division by zero
5642 @cindex Access before elaboration
5643 @cindex Checks, division by zero
5644 @cindex Checks, access before elaboration
5645
5646 @noindent
5647 If you compile with the default options, GNAT will insert many run-time
5648 checks into the compiled code, including code that performs range
5649 checking against constraints, but not arithmetic overflow checking for
5650 integer operations (including division by zero) or checks for access
5651 before elaboration on subprogram calls. All other run-time checks, as
5652 required by the Ada 95 Reference Manual, are generated by default.
5653 The following @command{gcc} switches refine this default behavior:
5654
5655 @table @option
5656 @c !sort!
5657 @item -gnatp
5658 @cindex @option{-gnatp} (@command{gcc})
5659 @cindex Suppressing checks
5660 @cindex Checks, suppressing
5661 @findex Suppress
5662 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5663 had been present in the source. Validity checks are also suppressed (in
5664 other words @option{-gnatp} also implies @option{-gnatVn}.
5665 Use this switch to improve the performance
5666 of the code at the expense of safety in the presence of invalid data or
5667 program bugs.
5668
5669 @item -gnato
5670 @cindex @option{-gnato} (@command{gcc})
5671 @cindex Overflow checks
5672 @cindex Check, overflow
5673 Enables overflow checking for integer operations.
5674 This causes GNAT to generate slower and larger executable
5675 programs by adding code to check for overflow (resulting in raising
5676 @code{Constraint_Error} as required by standard Ada
5677 semantics). These overflow checks correspond to situations in which
5678 the true value of the result of an operation may be outside the base
5679 range of the result type. The following example shows the distinction:
5680
5681 @smallexample @c ada
5682 X1 : Integer := Integer'Last;
5683 X2 : Integer range 1 .. 5 := 5;
5684 X3 : Integer := Integer'Last;
5685 X4 : Integer range 1 .. 5 := 5;
5686 F  : Float := 2.0E+20;
5687 ...
5688 X1 := X1 + 1;
5689 X2 := X2 + 1;
5690 X3 := Integer (F);
5691 X4 := Integer (F);
5692 @end smallexample
5693
5694 @noindent
5695 Here the first addition results in a value that is outside the base range
5696 of Integer, and hence requires an overflow check for detection of the
5697 constraint error. Thus the first assignment to @code{X1} raises a
5698 @code{Constraint_Error} exception only if @option{-gnato} is set.
5699
5700 The second increment operation results in a violation
5701 of the explicit range constraint, and such range checks are always
5702 performed (unless specifically suppressed with a pragma @code{suppress}
5703 or the use of @option{-gnatp}).
5704
5705 The two conversions of @code{F} both result in values that are outside
5706 the base range of type @code{Integer} and thus will raise
5707 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5708 The fact that the result of the second conversion is assigned to
5709 variable @code{X4} with a restricted range is irrelevant, since the problem
5710 is in the conversion, not the assignment.
5711
5712 Basically the rule is that in the default mode (@option{-gnato} not
5713 used), the generated code assures that all integer variables stay
5714 within their declared ranges, or within the base range if there is
5715 no declared range. This prevents any serious problems like indexes
5716 out of range for array operations.
5717
5718 What is not checked in default mode is an overflow that results in
5719 an in-range, but incorrect value. In the above example, the assignments
5720 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5721 range of the target variable, but the result is wrong in the sense that
5722 it is too large to be represented correctly. Typically the assignment
5723 to @code{X1} will result in wrap around to the largest negative number.
5724 The conversions of @code{F} will result in some @code{Integer} value
5725 and if that integer value is out of the @code{X4} range then the
5726 subsequent assignment would generate an exception.
5727
5728 @findex Machine_Overflows
5729 Note that the @option{-gnato} switch does not affect the code generated
5730 for any floating-point operations; it applies only to integer
5731 semantics).
5732 For floating-point, GNAT has the @code{Machine_Overflows}
5733 attribute set to @code{False} and the normal mode of operation is to
5734 generate IEEE NaN and infinite values on overflow or invalid operations
5735 (such as dividing 0.0 by 0.0).
5736
5737 The reason that we distinguish overflow checking from other kinds of
5738 range constraint checking is that a failure of an overflow check can
5739 generate an incorrect value, but cannot cause erroneous behavior. This
5740 is unlike the situation with a constraint check on an array subscript,
5741 where failure to perform the check can result in random memory description,
5742 or the range check on a case statement, where failure to perform the check
5743 can cause a wild jump.
5744
5745 Note again that @option{-gnato} is off by default, so overflow checking is
5746 not performed in default mode. This means that out of the box, with the
5747 default settings, GNAT does not do all the checks expected from the
5748 language description in the Ada Reference Manual. If you want all constraint
5749 checks to be performed, as described in this Manual, then you must
5750 explicitly use the -gnato switch either on the @command{gnatmake} or
5751 @command{gcc} command.
5752
5753 @item -gnatE
5754 @cindex @option{-gnatE} (@command{gcc})
5755 @cindex Elaboration checks
5756 @cindex Check, elaboration
5757 Enables dynamic checks for access-before-elaboration
5758 on subprogram calls and generic instantiations.
5759 For full details of the effect and use of this switch,
5760 @xref{Compiling Using gcc}.
5761 @end table
5762
5763 @findex Unsuppress
5764 @noindent
5765 The setting of these switches only controls the default setting of the
5766 checks. You may modify them using either @code{Suppress} (to remove
5767 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5768 the program source.
5769
5770 @node Stack Overflow Checking
5771 @subsection Stack Overflow Checking
5772 @cindex Stack Overflow Checking
5773 @cindex -fstack-check
5774
5775 @noindent
5776 For most operating systems, @command{gcc} does not perform stack overflow
5777 checking by default. This means that if the main environment task or
5778 some other task exceeds the available stack space, then unpredictable
5779 behavior will occur.
5780
5781 To activate stack checking, compile all units with the gcc option
5782 @option{-fstack-check}. For example:
5783
5784 @smallexample
5785 gcc -c -fstack-check package1.adb
5786 @end smallexample
5787
5788 @noindent
5789 Units compiled with this option will generate extra instructions to check
5790 that any use of the stack (for procedure calls or for declaring local
5791 variables in declare blocks) do not exceed the available stack space.
5792 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5793
5794 For declared tasks, the stack size is always controlled by the size
5795 given in an applicable @code{Storage_Size} pragma (or is set to
5796 the default size if no pragma is used.
5797
5798 For the environment task, the stack size depends on
5799 system defaults and is unknown to the compiler. The stack
5800 may even dynamically grow on some systems, precluding the
5801 normal Ada semantics for stack overflow. In the worst case,
5802 unbounded stack usage, causes unbounded stack expansion
5803 resulting in the system running out of virtual memory.
5804
5805 The stack checking may still work correctly if a fixed
5806 size stack is allocated, but this cannot be guaranteed.
5807 To ensure that a clean exception is signalled for stack
5808 overflow, set the environment variable
5809 @code{GNAT_STACK_LIMIT} to indicate the maximum
5810 stack area that can be used, as in:
5811 @cindex GNAT_STACK_LIMIT
5812
5813 @smallexample
5814 SET GNAT_STACK_LIMIT 1600
5815 @end smallexample
5816
5817 @noindent
5818 The limit is given in kilobytes, so the above declaration would
5819 set the stack limit of the environment task to 1.6 megabytes.
5820 Note that the only purpose of this usage is to limit the amount
5821 of stack used by the environment task. If it is necessary to
5822 increase the amount of stack for the environment task, then this
5823 is an operating systems issue, and must be addressed with the
5824 appropriate operating systems commands.
5825
5826 @node Using gcc for Syntax Checking
5827 @subsection Using @command{gcc} for Syntax Checking
5828 @table @option
5829 @item -gnats
5830 @cindex @option{-gnats} (@command{gcc})
5831 @ifclear vms
5832
5833 @noindent
5834 The @code{s} stands for ``syntax''.
5835 @end ifclear
5836
5837 Run GNAT in syntax checking only mode. For
5838 example, the command
5839
5840 @smallexample
5841 $ gcc -c -gnats x.adb
5842 @end smallexample
5843
5844 @noindent
5845 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5846 series of files in a single command
5847 @ifclear vms
5848 , and can use wild cards to specify such a group of files.
5849 Note that you must specify the @option{-c} (compile
5850 only) flag in addition to the @option{-gnats} flag.
5851 @end ifclear
5852 .
5853 You may use other switches in conjunction with @option{-gnats}. In
5854 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5855 format of any generated error messages.
5856
5857 When the source file is empty or contains only empty lines and/or comments,
5858 the output is a warning:
5859
5860 @smallexample
5861 $ gcc -c -gnats -x ada toto.txt
5862 toto.txt:1:01: warning: empty file, contains no compilation units
5863 $
5864 @end smallexample
5865
5866 Otherwise, the output is simply the error messages, if any. No object file or
5867 ALI file is generated by a syntax-only compilation. Also, no units other
5868 than the one specified are accessed. For example, if a unit @code{X}
5869 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5870 check only mode does not access the source file containing unit
5871 @code{Y}.
5872
5873 @cindex Multiple units, syntax checking
5874 Normally, GNAT allows only a single unit in a source file. However, this
5875 restriction does not apply in syntax-check-only mode, and it is possible
5876 to check a file containing multiple compilation units concatenated
5877 together. This is primarily used by the @code{gnatchop} utility
5878 (@pxref{Renaming Files Using gnatchop}).
5879 @end table
5880
5881 @node Using gcc for Semantic Checking
5882 @subsection Using @command{gcc} for Semantic Checking
5883 @table @option
5884 @item -gnatc
5885 @cindex @option{-gnatc} (@command{gcc})
5886
5887 @ifclear vms
5888 @noindent
5889 The @code{c} stands for ``check''.
5890 @end ifclear
5891 Causes the compiler to operate in semantic check mode,
5892 with full checking for all illegalities specified in the
5893 Ada 95 Reference Manual, but without generation of any object code
5894 (no object file is generated).
5895
5896 Because dependent files must be accessed, you must follow the GNAT
5897 semantic restrictions on file structuring to operate in this mode:
5898
5899 @itemize @bullet
5900 @item
5901 The needed source files must be accessible
5902 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5903
5904 @item
5905 Each file must contain only one compilation unit.
5906
5907 @item
5908 The file name and unit name must match (@pxref{File Naming Rules}).
5909 @end itemize
5910
5911 The output consists of error messages as appropriate. No object file is
5912 generated. An @file{ALI} file is generated for use in the context of
5913 cross-reference tools, but this file is marked as not being suitable
5914 for binding (since no object file is generated).
5915 The checking corresponds exactly to the notion of
5916 legality in the Ada 95 Reference Manual.
5917
5918 Any unit can be compiled in semantics-checking-only mode, including
5919 units that would not normally be compiled (subunits,
5920 and specifications where a separate body is present).
5921 @end table
5922
5923 @node Compiling Different Versions of Ada
5924 @subsection Compiling Different Versions of Ada
5925 @table @option
5926 @cindex Compatibility with Ada 83
5927 @cindex Ada 83 mode
5928 @cindex Ada 95 mode
5929 @cindex Ada 2005 mode
5930
5931 GNAT is primarily an Ada 95 compiler, but the switches described in
5932 this section allow operation in Ada 83 compatibility mode, and also
5933 allow the use of a preliminary implementation of many of the expected
5934 new features in Ada 2005, the forthcoming new version of the standard.
5935
5936 @item -gnat83 (Ada 83 Compatibility Mode)
5937 @cindex @option{-gnat83} (@command{gcc})
5938 @cindex ACVC, Ada 83 tests
5939
5940 @noindent
5941 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5942 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5943 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5944 where this can be done easily.
5945 It is not possible to guarantee this switch does a perfect
5946 job; for example, some subtle tests, such as are
5947 found in earlier ACVC tests (and that have been removed from the ACATS suite
5948 for Ada 95), might not compile correctly.
5949 Nevertheless, this switch may be useful in some circumstances, for example
5950 where, due to contractual reasons, legacy code needs to be maintained
5951 using only Ada 83 features.
5952
5953 With few exceptions (most notably the need to use @code{<>} on
5954 @cindex Generic formal parameters
5955 unconstrained generic formal parameters, the use of the new Ada 95
5956 reserved words, and the use of packages
5957 with optional bodies), it is not necessary to use the
5958 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5959 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5960 means that a correct Ada 83 program is usually also a correct Ada 95
5961 program.
5962 For further information, please refer to @ref{Compatibility and Porting Guide}.
5963
5964 @item -gnat95 (Ada 95 mode)
5965 @cindex @option{-gnat95} (@command{gcc})
5966
5967 @noindent
5968 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
5969 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
5970 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
5971 this default Ada95 mode without problems (see section above describing the
5972 use of @option{-gnat83} to run in Ada 83 mode).
5973
5974 In Ada 95 mode, the use of Ada 2005 features will in general cause error
5975 messages or warnings. Some specialized releases of GNAT (notably the GAP
5976 academic version) operate in Ada 2005 mode by default (see section below
5977 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
5978 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
5979 This option also can be used to cancel the effect of a previous
5980 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
5981
5982
5983 @item -gnat05 (Ada 2005 mode)
5984 @cindex @option{-gnat05} (@command{gcc})
5985
5986 @noindent
5987 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
5988 in Ada 2005 mode using this option. Although the new standard has not
5989 yet been issued (as of early 2005), many features have been discussed and
5990 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
5991 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
5992 releases is a file @file{features-ada0y} that describes the current set
5993 of implemented Ada 2005 features.
5994
5995 If these features are used in Ada 95 mode (which is the normal default),
5996 then error messages or warnings may be
5997 generated, reflecting the fact that these new features are otherwise
5998 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
5999 switch (or an equivalent pragma) causes these messages to be suppressed.
6000
6001 Note that some specialized releases of GNAT (notably the GAP academic
6002 version) have Ada 2005 mode on by default, and in such environments,
6003 the Ada 2005 features can be used freely without the use of switches.
6004
6005 @end table
6006
6007 @node Character Set Control
6008 @subsection Character Set Control
6009 @table @option
6010 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6011 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6012
6013 @noindent
6014 Normally GNAT recognizes the Latin-1 character set in source program
6015 identifiers, as described in the Ada 95 Reference Manual.
6016 This switch causes
6017 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6018 single character ^^or word^ indicating the character set, as follows:
6019
6020 @table @code
6021 @item 1
6022 ISO 8859-1 (Latin-1) identifiers
6023
6024 @item 2
6025 ISO 8859-2 (Latin-2) letters allowed in identifiers
6026
6027 @item 3
6028 ISO 8859-3 (Latin-3) letters allowed in identifiers
6029
6030 @item 4
6031 ISO 8859-4 (Latin-4) letters allowed in identifiers
6032
6033 @item 5
6034 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6035
6036 @item 9
6037 ISO 8859-15 (Latin-9) letters allowed in identifiers
6038
6039 @item ^p^PC^
6040 IBM PC letters (code page 437) allowed in identifiers
6041
6042 @item ^8^PC850^
6043 IBM PC letters (code page 850) allowed in identifiers
6044
6045 @item ^f^FULL_UPPER^
6046 Full upper-half codes allowed in identifiers
6047
6048 @item ^n^NO_UPPER^
6049 No upper-half codes allowed in identifiers
6050
6051 @item ^w^WIDE^
6052 Wide-character codes (that is, codes greater than 255)
6053 allowed in identifiers
6054 @end table
6055
6056 @xref{Foreign Language Representation}, for full details on the
6057 implementation of these character sets.
6058
6059 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6060 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6061 Specify the method of encoding for wide characters.
6062 @var{e} is one of the following:
6063
6064 @table @code
6065
6066 @item ^h^HEX^
6067 Hex encoding (brackets coding also recognized)
6068
6069 @item ^u^UPPER^
6070 Upper half encoding (brackets encoding also recognized)
6071
6072 @item ^s^SHIFT_JIS^
6073 Shift/JIS encoding (brackets encoding also recognized)
6074
6075 @item ^e^EUC^
6076 EUC encoding (brackets encoding also recognized)
6077
6078 @item ^8^UTF8^
6079 UTF-8 encoding (brackets encoding also recognized)
6080
6081 @item ^b^BRACKETS^
6082 Brackets encoding only (default value)
6083 @end table
6084 For full details on the these encoding
6085 methods see @ref{Wide Character Encodings}.
6086 Note that brackets coding is always accepted, even if one of the other
6087 options is specified, so for example @option{-gnatW8} specifies that both
6088 brackets and @code{UTF-8} encodings will be recognized. The units that are
6089 with'ed directly or indirectly will be scanned using the specified
6090 representation scheme, and so if one of the non-brackets scheme is
6091 used, it must be used consistently throughout the program. However,
6092 since brackets encoding is always recognized, it may be conveniently
6093 used in standard libraries, allowing these libraries to be used with
6094 any of the available coding schemes.
6095 scheme. If no @option{-gnatW?} parameter is present, then the default
6096 representation is Brackets encoding only.
6097
6098 Note that the wide character representation that is specified (explicitly
6099 or by default) for the main program also acts as the default encoding used
6100 for Wide_Text_IO files if not specifically overridden by a WCEM form
6101 parameter.
6102
6103 @end table
6104 @node File Naming Control
6105 @subsection File Naming Control
6106
6107 @table @option
6108 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6109 @cindex @option{-gnatk} (@command{gcc})
6110 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6111 1-999, indicates the maximum allowable length of a file name (not
6112 including the @file{.ads} or @file{.adb} extension). The default is not
6113 to enable file name krunching.
6114
6115 For the source file naming rules, @xref{File Naming Rules}.
6116 @end table
6117
6118 @node Subprogram Inlining Control
6119 @subsection Subprogram Inlining Control
6120
6121 @table @option
6122 @c !sort!
6123 @item -gnatn
6124 @cindex @option{-gnatn} (@command{gcc})
6125 @ifclear vms
6126 The @code{n} here is intended to suggest the first syllable of the
6127 word ``inline''.
6128 @end ifclear
6129 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6130 inlining to actually occur, optimization must be enabled. To enable
6131 inlining of subprograms specified by pragma @code{Inline},
6132 you must also specify this switch.
6133 In the absence of this switch, GNAT does not attempt
6134 inlining and does not need to access the bodies of
6135 subprograms for which @code{pragma Inline} is specified if they are not
6136 in the current unit.
6137
6138 If you specify this switch the compiler will access these bodies,
6139 creating an extra source dependency for the resulting object file, and
6140 where possible, the call will be inlined.
6141 For further details on when inlining is possible
6142 see @ref{Inlining of Subprograms}.
6143
6144 @item -gnatN
6145 @cindex @option{-gnatN} (@command{gcc})
6146 The front end inlining activated by this switch is generally more extensive,
6147 and quite often more effective than the standard @option{-gnatn} inlining mode.
6148 It will also generate additional dependencies.
6149 Note that
6150 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6151 to specify both options.
6152 @end table
6153
6154 @node Auxiliary Output Control
6155 @subsection Auxiliary Output Control
6156
6157 @table @option
6158 @item -gnatt
6159 @cindex @option{-gnatt} (@command{gcc})
6160 @cindex Writing internal trees
6161 @cindex Internal trees, writing to file
6162 Causes GNAT to write the internal tree for a unit to a file (with the
6163 extension @file{.adt}.
6164 This not normally required, but is used by separate analysis tools.
6165 Typically
6166 these tools do the necessary compilations automatically, so you should
6167 not have to specify this switch in normal operation.
6168
6169 @item -gnatu
6170 @cindex @option{-gnatu} (@command{gcc})
6171 Print a list of units required by this compilation on @file{stdout}.
6172 The listing includes all units on which the unit being compiled depends
6173 either directly or indirectly.
6174
6175 @ifclear vms
6176 @item -pass-exit-codes
6177 @cindex @option{-pass-exit-codes} (@command{gcc})
6178 If this switch is not used, the exit code returned by @command{gcc} when
6179 compiling multiple files indicates whether all source files have
6180 been successfully used to generate object files or not.
6181
6182 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6183 exit status and allows an integrated development environment to better
6184 react to a compilation failure. Those exit status are:
6185
6186 @table @asis
6187 @item 5
6188 There was an error in at least one source file.
6189 @item 3
6190 At least one source file did not generate an object file.
6191 @item 2
6192 The compiler died unexpectedly (internal error for example).
6193 @item 0
6194 An object file has been generated for every source file.
6195 @end table
6196 @end ifclear
6197 @end table
6198
6199 @node Debugging Control
6200 @subsection Debugging Control
6201
6202 @table @option
6203 @c !sort!
6204 @cindex Debugging options
6205 @ifclear vms
6206 @item -gnatd@var{x}
6207 @cindex @option{-gnatd} (@command{gcc})
6208 Activate internal debugging switches. @var{x} is a letter or digit, or
6209 string of letters or digits, which specifies the type of debugging
6210 outputs desired. Normally these are used only for internal development
6211 or system debugging purposes. You can find full documentation for these
6212 switches in the body of the @code{Debug} unit in the compiler source
6213 file @file{debug.adb}.
6214 @end ifclear
6215
6216 @item -gnatG
6217 @cindex @option{-gnatG} (@command{gcc})
6218 This switch causes the compiler to generate auxiliary output containing
6219 a pseudo-source listing of the generated expanded code. Like most Ada
6220 compilers, GNAT works by first transforming the high level Ada code into
6221 lower level constructs. For example, tasking operations are transformed
6222 into calls to the tasking run-time routines. A unique capability of GNAT
6223 is to list this expanded code in a form very close to normal Ada source.
6224 This is very useful in understanding the implications of various Ada
6225 usage on the efficiency of the generated code. There are many cases in
6226 Ada (e.g. the use of controlled types), where simple Ada statements can
6227 generate a lot of run-time code. By using @option{-gnatG} you can identify
6228 these cases, and consider whether it may be desirable to modify the coding
6229 approach to improve efficiency.
6230
6231 The format of the output is very similar to standard Ada source, and is
6232 easily understood by an Ada programmer. The following special syntactic
6233 additions correspond to low level features used in the generated code that
6234 do not have any exact analogies in pure Ada source form. The following
6235 is a partial list of these special constructions. See the specification
6236 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6237
6238 @table @code
6239 @item new @var{xxx} [storage_pool = @var{yyy}]
6240 Shows the storage pool being used for an allocator.
6241
6242 @item at end @var{procedure-name};
6243 Shows the finalization (cleanup) procedure for a scope.
6244
6245 @item (if @var{expr} then @var{expr} else @var{expr})
6246 Conditional expression equivalent to the @code{x?y:z} construction in C.
6247
6248 @item @var{target}^^^(@var{source})
6249 A conversion with floating-point truncation instead of rounding.
6250
6251 @item @var{target}?(@var{source})
6252 A conversion that bypasses normal Ada semantic checking. In particular
6253 enumeration types and fixed-point types are treated simply as integers.
6254
6255 @item @var{target}?^^^(@var{source})
6256 Combines the above two cases.
6257
6258 @item @var{x} #/ @var{y}
6259 @itemx @var{x} #mod @var{y}
6260 @itemx @var{x} #* @var{y}
6261 @itemx @var{x} #rem @var{y}
6262 A division or multiplication of fixed-point values which are treated as
6263 integers without any kind of scaling.
6264
6265 @item free @var{expr} [storage_pool = @var{xxx}]
6266 Shows the storage pool associated with a @code{free} statement.
6267
6268 @item freeze @var{typename} [@var{actions}]
6269 Shows the point at which @var{typename} is frozen, with possible
6270 associated actions to be performed at the freeze point.
6271
6272 @item reference @var{itype}
6273 Reference (and hence definition) to internal type @var{itype}.
6274
6275 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6276 Intrinsic function call.
6277
6278 @item @var{labelname} : label
6279 Declaration of label @var{labelname}.
6280
6281 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6282 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6283 @var{expr}, but handled more efficiently).
6284
6285 @item [constraint_error]
6286 Raise the @code{Constraint_Error} exception.
6287
6288 @item @var{expression}'reference
6289 A pointer to the result of evaluating @var{expression}.
6290
6291 @item @var{target-type}!(@var{source-expression})
6292 An unchecked conversion of @var{source-expression} to @var{target-type}.
6293
6294 @item [@var{numerator}/@var{denominator}]
6295 Used to represent internal real literals (that) have no exact
6296 representation in base 2-16 (for example, the result of compile time
6297 evaluation of the expression 1.0/27.0).
6298 @end table
6299
6300 @item -gnatD
6301 @cindex @option{-gnatD} (@command{gcc})
6302 When used in conjunction with @option{-gnatG}, this switch causes
6303 the expanded source, as described above for
6304 @option{-gnatG} to be written to files with names
6305 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6306 instead of to the standard ooutput file. For
6307 example, if the source file name is @file{hello.adb}, then a file
6308 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6309 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6310 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6311 you to do source level debugging using the generated code which is
6312 sometimes useful for complex code, for example to find out exactly
6313 which part of a complex construction raised an exception. This switch
6314 also suppress generation of cross-reference information (see
6315 @option{-gnatx}) since otherwise the cross-reference information
6316 would refer to the @file{^.dg^.DG^} file, which would cause
6317 confusion since this is not the original source file.
6318
6319 Note that @option{-gnatD} actually implies @option{-gnatG}
6320 automatically, so it is not necessary to give both options.
6321 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6322
6323 @ifclear vms
6324 @item -gnatR[0|1|2|3[s]]
6325 @cindex @option{-gnatR} (@command{gcc})
6326 This switch controls output from the compiler of a listing showing
6327 representation information for declared types and objects. For
6328 @option{-gnatR0}, no information is output (equivalent to omitting
6329 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6330 so @option{-gnatR} with no parameter has the same effect), size and alignment
6331 information is listed for declared array and record types. For
6332 @option{-gnatR2}, size and alignment information is listed for all
6333 expression information for values that are computed at run time for
6334 variant records. These symbolic expressions have a mostly obvious
6335 format with #n being used to represent the value of the n'th
6336 discriminant. See source files @file{repinfo.ads/adb} in the
6337 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6338 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6339 the output is to a file with the name @file{^file.rep^file_REP^} where
6340 file is the name of the corresponding source file.
6341 @end ifclear
6342 @ifset vms
6343 @item /REPRESENTATION_INFO
6344 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6345 This qualifier controls output from the compiler of a listing showing
6346 representation information for declared types and objects. For
6347 @option{/REPRESENTATION_INFO=NONE}, no information is output
6348 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6349 @option{/REPRESENTATION_INFO} without option is equivalent to
6350 @option{/REPRESENTATION_INFO=ARRAYS}.
6351 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6352 information is listed for declared array and record types. For
6353 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6354 is listed for all expression information for values that are computed
6355 at run time for variant records. These symbolic expressions have a mostly
6356 obvious format with #n being used to represent the value of the n'th
6357 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6358 @code{GNAT} sources for full details on the format of
6359 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6360 If _FILE is added at the end of an option
6361 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6362 then the output is to a file with the name @file{file_REP} where
6363 file is the name of the corresponding source file.
6364 @end ifset
6365
6366 @item -gnatS
6367 @cindex @option{-gnatS} (@command{gcc})
6368 The use of the switch @option{-gnatS} for an
6369 Ada compilation will cause the compiler to output a
6370 representation of package Standard in a form very
6371 close to standard Ada. It is not quite possible to
6372 do this entirely in standard Ada (since new
6373 numeric base types cannot be created in standard
6374 Ada), but the output is easily
6375 readable to any Ada programmer, and is useful to
6376 determine the characteristics of target dependent
6377 types in package Standard.
6378
6379 @item -gnatx
6380 @cindex @option{-gnatx} (@command{gcc})
6381 Normally the compiler generates full cross-referencing information in
6382 the @file{ALI} file. This information is used by a number of tools,
6383 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6384 suppresses this information. This saves some space and may slightly
6385 speed up compilation, but means that these tools cannot be used.
6386 @end table
6387
6388 @node Exception Handling Control
6389 @subsection Exception Handling Control
6390
6391 @noindent
6392 GNAT uses two methods for handling exceptions at run-time. The
6393 @code{setjmp/longjmp} method saves the context when entering
6394 a frame with an exception handler. Then when an exception is
6395 raised, the context can be restored immediately, without the
6396 need for tracing stack frames. This method provides very fast
6397 exception propagation, but introduces significant overhead for
6398 the use of exception handlers, even if no exception is raised.
6399
6400 The other approach is called ``zero cost'' exception handling.
6401 With this method, the compiler builds static tables to describe
6402 the exception ranges. No dynamic code is required when entering
6403 a frame containing an exception handler. When an exception is
6404 raised, the tables are used to control a back trace of the
6405 subprogram invocation stack to locate the required exception
6406 handler. This method has considerably poorer performance for
6407 the propagation of exceptions, but there is no overhead for
6408 exception handlers if no exception is raised. Note that in this
6409 mode and in the context of mixed Ada and C/C++ programming,
6410 to propagate an exception through a C/C++ code, the C/C++ code
6411 must be compiled with the @option{-funwind-tables} GCC's
6412 option.
6413
6414 The following switches can be used to control which of the
6415 two exception handling methods is used.
6416
6417 @table @option
6418 @c !sort!
6419
6420 @item --RTS=sjlj
6421 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6422 This switch causes the setjmp/longjmp run-time to be used
6423 for exception handling. If this is the default mechanism for the
6424 target (see below), then this has no effect. If the default
6425 mechanism for the target is zero cost exceptions, then
6426 this switch can be used to modify this default, and must be
6427 used for all units in the partition.
6428 This option is rarely used. One case in which it may be
6429 advantageous is if you have an application where exception
6430 raising is common and the overall performance of the
6431 application is improved by favoring exception propagation.
6432
6433 @item --RTS=zcx
6434 @cindex @option{--RTS=zcx} (@command{gnatmake})
6435 @cindex Zero Cost Exceptions
6436 This switch causes the zero cost approach to be used
6437 for exception handling. If this is the default mechanism for the
6438 target (see below), then this has no effect. If the default
6439 mechanism for the target is setjmp/longjmp exceptions, then
6440 this switch can be used to modify this default, and must be
6441 used for all units in the partition.
6442 This option can only be used if the zero cost approach
6443 is available for the target in use (see below).
6444 @end table
6445
6446 @noindent
6447 The @code{setjmp/longjmp} approach is available on all targets, while
6448 the @code{zero cost} approach is available on selected targets.
6449 To determine whether zero cost exceptions can be used for a
6450 particular target, look at the private part of the file system.ads.
6451 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6452 be True to use the zero cost approach. If both of these switches
6453 are set to False, this means that zero cost exception handling
6454 is not yet available for that target. The switch
6455 @code{ZCX_By_Default} indicates the default approach. If this
6456 switch is set to True, then the @code{zero cost} approach is
6457 used by default.
6458
6459 @node Units to Sources Mapping Files
6460 @subsection Units to Sources Mapping Files
6461
6462 @table @option
6463
6464 @item -gnatem^^=^@var{path}
6465 @cindex @option{-gnatem} (@command{gcc})
6466 A mapping file is a way to communicate to the compiler two mappings:
6467 from unit names to file names (without any directory information) and from
6468 file names to path names (with full directory information). These mappings
6469 are used by the compiler to short-circuit the path search.
6470
6471 The use of mapping files is not required for correct operation of the
6472 compiler, but mapping files can improve efficiency, particularly when
6473 sources are read over a slow network connection. In normal operation,
6474 you need not be concerned with the format or use of mapping files,
6475 and the @option{-gnatem} switch is not a switch that you would use
6476 explicitly. it is intended only for use by automatic tools such as
6477 @command{gnatmake} running under the project file facility. The
6478 description here of the format of mapping files is provided
6479 for completeness and for possible use by other tools.
6480
6481 A mapping file is a sequence of sets of three lines. In each set,
6482 the first line is the unit name, in lower case, with ``@code{%s}''
6483 appended for
6484 specifications and ``@code{%b}'' appended for bodies; the second line is the
6485 file name; and the third line is the path name.
6486
6487 Example:
6488 @smallexample
6489    main%b
6490    main.2.ada
6491    /gnat/project1/sources/main.2.ada
6492 @end smallexample
6493
6494 When the switch @option{-gnatem} is specified, the compiler will create
6495 in memory the two mappings from the specified file. If there is any problem
6496 (non existent file, truncated file or duplicate entries), no mapping
6497 will be created.
6498
6499 Several @option{-gnatem} switches may be specified; however, only the last
6500 one on the command line will be taken into account.
6501
6502 When using a project file, @command{gnatmake} create a temporary mapping file
6503 and communicates it to the compiler using this switch.
6504
6505 @end table
6506
6507 @node Integrated Preprocessing
6508 @subsection Integrated Preprocessing
6509
6510 @noindent
6511 GNAT sources may be preprocessed immediately before compilation; the actual
6512 text of the source is not the text of the source file, but is derived from it
6513 through a process called preprocessing. Integrated preprocessing is specified
6514 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6515 indicates, through a text file, the preprocessing data to be used.
6516 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6517
6518 @noindent
6519 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6520 used when Integrated Preprocessing is used. The reason is that preprocessing
6521 with another Preprocessing Data file without changing the sources will
6522 not trigger recompilation without this switch.
6523
6524 @noindent
6525 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6526 always trigger recompilation for sources that are preprocessed,
6527 because @command{gnatmake} cannot compute the checksum of the source after
6528 preprocessing.
6529
6530 @noindent
6531 The actual preprocessing function is described in details in section
6532 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6533 preprocessing is triggered and parameterized.
6534
6535 @table @code
6536
6537 @item -gnatep=@var{file}
6538 @cindex @option{-gnatep} (@command{gcc})
6539 This switch indicates to the compiler the file name (without directory
6540 information) of the preprocessor data file to use. The preprocessor data file
6541 should be found in the source directories.
6542
6543 @noindent
6544 A preprocessing data file is a text file with significant lines indicating
6545 how should be preprocessed either a specific source or all sources not
6546 mentioned in other lines. A significant line is a non empty, non comment line.
6547 Comments are similar to Ada comments.
6548
6549 @noindent
6550 Each significant line starts with either a literal string or the character '*'.
6551 A literal string is the file name (without directory information) of the source
6552 to preprocess. A character '*' indicates the preprocessing for all the sources
6553 that are not specified explicitly on other lines (order of the lines is not
6554 significant). It is an error to have two lines with the same file name or two
6555 lines starting with the character '*'.
6556
6557 @noindent
6558 After the file name or the character '*', another optional literal string
6559 indicating the file name of the definition file to be used for preprocessing
6560 (@pxref{Form of Definitions File}). The definition files are found by the
6561 compiler in one of the source directories. In some cases, when compiling
6562 a source in a directory other than the current directory, if the definition
6563 file is in the current directory, it may be necessary to add the current
6564 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6565 the compiler would not find the definition file.
6566
6567 @noindent
6568 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6569 be found. Those ^switches^switches^ are:
6570
6571 @table @code
6572
6573 @item -b
6574 Causes both preprocessor lines and the lines deleted by
6575 preprocessing to be replaced by blank lines, preserving the line number.
6576 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6577 it cancels the effect of @option{-c}.
6578
6579 @item -c
6580 Causes both preprocessor lines and the lines deleted
6581 by preprocessing to be retained as comments marked
6582 with the special string ``@code{--! }''.
6583
6584 @item -Dsymbol=value
6585 Define or redefine a symbol, associated with value. A symbol is an Ada
6586 identifier, or an Ada reserved word, with the exception of @code{if},
6587 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6588 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6589 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6590 same name defined in a definition file.
6591
6592 @item -s
6593 Causes a sorted list of symbol names and values to be
6594 listed on the standard output file.
6595
6596 @item -u
6597 Causes undefined symbols to be treated as having the value @code{FALSE}
6598 in the context
6599 of a preprocessor test. In the absence of this option, an undefined symbol in
6600 a @code{#if} or @code{#elsif} test will be treated as an error.
6601
6602 @end table
6603
6604 @noindent
6605 Examples of valid lines in a preprocessor data file:
6606
6607 @smallexample
6608   "toto.adb"  "prep.def" -u
6609   --  preprocess "toto.adb", using definition file "prep.def",
6610   --  undefined symbol are False.
6611
6612   * -c -DVERSION=V101
6613   --  preprocess all other sources without a definition file;
6614   --  suppressed lined are commented; symbol VERSION has the value V101.
6615
6616   "titi.adb" "prep2.def" -s
6617   --  preprocess "titi.adb", using definition file "prep2.def";
6618   --  list all symbols with their values.
6619 @end smallexample
6620
6621 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6622 @cindex @option{-gnateD} (@command{gcc})
6623 Define or redefine a preprocessing symbol, associated with value. If no value
6624 is given on the command line, then the value of the symbol is @code{True}.
6625 A symbol is an identifier, following normal Ada (case-insensitive)
6626 rules for its syntax, and value is any sequence (including an empty sequence)
6627 of characters from the set (letters, digits, period, underline).
6628 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6629 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6630
6631 @noindent
6632 A symbol declared with this ^switch^switch^ on the command line replaces a
6633 symbol with the same name either in a definition file or specified with a
6634 ^switch^switch^ -D in the preprocessor data file.
6635
6636 @noindent
6637 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6638
6639 @end table
6640
6641 @node Code Generation Control
6642 @subsection Code Generation Control
6643
6644 @noindent
6645
6646 The GCC technology provides a wide range of target dependent
6647 @option{-m} switches for controlling
6648 details of code generation with respect to different versions of
6649 architectures. This includes variations in instruction sets (e.g.
6650 different members of the power pc family), and different requirements
6651 for optimal arrangement of instructions (e.g. different members of
6652 the x86 family). The list of available @option{-m} switches may be
6653 found in the GCC documentation.
6654
6655 Use of the these @option{-m} switches may in some cases result in improved
6656 code performance.
6657
6658 The GNAT Pro technology is tested and qualified without any
6659 @option{-m} switches,
6660 so generally the most reliable approach is to avoid the use of these
6661 switches. However, we generally expect most of these switches to work
6662 successfully with GNAT Pro, and many customers have reported successful
6663 use of these options.
6664
6665 Our general advice is to avoid the use of @option{-m} switches unless
6666 special needs lead to requirements in this area. In particular,
6667 there is no point in using @option{-m} switches to improve performance
6668 unless you actually see a performance improvement.
6669
6670 @ifset vms
6671 @node Return Codes
6672 @subsection Return Codes
6673 @cindex Return Codes
6674 @cindex @option{/RETURN_CODES=VMS}
6675
6676 @noindent
6677 On VMS, GNAT compiled programs return POSIX-style codes by default,
6678 e.g. @option{/RETURN_CODES=POSIX}.
6679
6680 To enable VMS style return codes, use GNAT BIND and LINK with the option
6681 @option{/RETURN_CODES=VMS}. For example:
6682
6683 @smallexample
6684 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6685 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6686 @end smallexample
6687
6688 @noindent
6689 Programs built with /RETURN_CODES=VMS are suitable to be called in
6690 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6691 are suitable for spawning with appropriate GNAT RTL routines.
6692
6693 @end ifset
6694
6695 @node Search Paths and the Run-Time Library (RTL)
6696 @section Search Paths and the Run-Time Library (RTL)
6697
6698 @noindent
6699 With the GNAT source-based library system, the compiler must be able to
6700 find source files for units that are needed by the unit being compiled.
6701 Search paths are used to guide this process.
6702
6703 The compiler compiles one source file whose name must be given
6704 explicitly on the command line. In other words, no searching is done
6705 for this file. To find all other source files that are needed (the most
6706 common being the specs of units), the compiler examines the following
6707 directories, in the following order:
6708
6709 @enumerate
6710 @item
6711 The directory containing the source file of the main unit being compiled
6712 (the file name on the command line).
6713
6714 @item
6715 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6716 @command{gcc} command line, in the order given.
6717
6718 @item
6719 @findex ADA_INCLUDE_PATH
6720 Each of the directories listed in the value of the
6721 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6722 @ifclear vms
6723 Construct this value
6724 exactly as the @code{PATH} environment variable: a list of directory
6725 names separated by colons (semicolons when working with the NT version).
6726 @end ifclear
6727 @ifset vms
6728 Normally, define this value as a logical name containing a comma separated
6729 list of directory names.
6730
6731 This variable can also be defined by means of an environment string
6732 (an argument to the DEC C exec* set of functions).
6733
6734 Logical Name:
6735 @smallexample
6736 DEFINE ANOTHER_PATH FOO:[BAG]
6737 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6738 @end smallexample
6739
6740 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6741 first, followed by the standard Ada 95
6742 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6743 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6744 (Text_IO, Sequential_IO, etc)
6745 instead of the Ada95 packages. Thus, in order to get the Ada 95
6746 packages by default, ADA_INCLUDE_PATH must be redefined.
6747 @end ifset
6748
6749 @item
6750 @findex ADA_PRJ_INCLUDE_FILE
6751 Each of the directories listed in the text file whose name is given
6752 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6753
6754 @noindent
6755 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6756 driver when project files are used. It should not normally be set
6757 by other means.
6758
6759 @item
6760 The content of the @file{ada_source_path} file which is part of the GNAT
6761 installation tree and is used to store standard libraries such as the
6762 GNAT Run Time Library (RTL) source files.
6763 @ifclear vms
6764 @ref{Installing a library}
6765 @end ifclear
6766 @end enumerate
6767
6768 @noindent
6769 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6770 inhibits the use of the directory
6771 containing the source file named in the command line. You can still
6772 have this directory on your search path, but in this case it must be
6773 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6774
6775 Specifying the switch @option{-nostdinc}
6776 inhibits the search of the default location for the GNAT Run Time
6777 Library (RTL) source files.
6778
6779 The compiler outputs its object files and ALI files in the current
6780 working directory.
6781 @ifclear vms
6782 Caution: The object file can be redirected with the @option{-o} switch;
6783 however, @command{gcc} and @code{gnat1} have not been coordinated on this
6784 so the @file{ALI} file will not go to the right place. Therefore, you should
6785 avoid using the @option{-o} switch.
6786 @end ifclear
6787
6788 @findex System.IO
6789 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6790 children make up the GNAT RTL, together with the simple @code{System.IO}
6791 package used in the @code{"Hello World"} example. The sources for these units
6792 are needed by the compiler and are kept together in one directory. Not
6793 all of the bodies are needed, but all of the sources are kept together
6794 anyway. In a normal installation, you need not specify these directory
6795 names when compiling or binding. Either the environment variables or
6796 the built-in defaults cause these files to be found.
6797
6798 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6799 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6800 consisting of child units of @code{GNAT}. This is a collection of generally
6801 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6802 further details.
6803
6804 Besides simplifying access to the RTL, a major use of search paths is
6805 in compiling sources from multiple directories. This can make
6806 development environments much more flexible.
6807
6808 @node Order of Compilation Issues
6809 @section Order of Compilation Issues
6810
6811 @noindent
6812 If, in our earlier example, there was a spec for the @code{hello}
6813 procedure, it would be contained in the file @file{hello.ads}; yet this
6814 file would not have to be explicitly compiled. This is the result of the
6815 model we chose to implement library management. Some of the consequences
6816 of this model are as follows:
6817
6818 @itemize @bullet
6819 @item
6820 There is no point in compiling specs (except for package
6821 specs with no bodies) because these are compiled as needed by clients. If
6822 you attempt a useless compilation, you will receive an error message.
6823 It is also useless to compile subunits because they are compiled as needed
6824 by the parent.
6825
6826 @item
6827 There are no order of compilation requirements: performing a
6828 compilation never obsoletes anything. The only way you can obsolete
6829 something and require recompilations is to modify one of the
6830 source files on which it depends.
6831
6832 @item
6833 There is no library as such, apart from the ALI files
6834 (@pxref{The Ada Library Information Files}, for information on the format
6835 of these files). For now we find it convenient to create separate ALI files,
6836 but eventually the information therein may be incorporated into the object
6837 file directly.
6838
6839 @item
6840 When you compile a unit, the source files for the specs of all units
6841 that it @code{with}'s, all its subunits, and the bodies of any generics it
6842 instantiates must be available (reachable by the search-paths mechanism
6843 described above), or you will receive a fatal error message.
6844 @end itemize
6845
6846 @node Examples
6847 @section Examples
6848
6849 @noindent
6850 The following are some typical Ada compilation command line examples:
6851
6852 @table @code
6853 @item $ gcc -c xyz.adb
6854 Compile body in file @file{xyz.adb} with all default options.
6855
6856 @ifclear vms
6857 @item $ gcc -c -O2 -gnata xyz-def.adb
6858 @end ifclear
6859 @ifset vms
6860 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6861 @end ifset
6862
6863 Compile the child unit package in file @file{xyz-def.adb} with extensive
6864 optimizations, and pragma @code{Assert}/@code{Debug} statements
6865 enabled.
6866
6867 @item $ gcc -c -gnatc abc-def.adb
6868 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6869 mode.
6870 @end table
6871
6872 @node Binding Using gnatbind
6873 @chapter Binding Using @code{gnatbind}
6874 @findex gnatbind
6875
6876 @menu
6877 * Running gnatbind::
6878 * Switches for gnatbind::
6879 * Command-Line Access::
6880 * Search Paths for gnatbind::
6881 * Examples of gnatbind Usage::
6882 @end menu
6883
6884 @noindent
6885 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6886 to bind compiled GNAT objects. The @code{gnatbind} program performs
6887 four separate functions:
6888
6889 @enumerate
6890 @item
6891 Checks that a program is consistent, in accordance with the rules in
6892 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6893 messages are generated if a program uses inconsistent versions of a
6894 given unit.
6895
6896 @item
6897 Checks that an acceptable order of elaboration exists for the program
6898 and issues an error message if it cannot find an order of elaboration
6899 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6900
6901 @item
6902 Generates a main program incorporating the given elaboration order.
6903 This program is a small Ada package (body and spec) that
6904 must be subsequently compiled
6905 using the GNAT compiler. The necessary compilation step is usually
6906 performed automatically by @command{gnatlink}. The two most important
6907 functions of this program
6908 are to call the elaboration routines of units in an appropriate order
6909 and to call the main program.
6910
6911 @item
6912 Determines the set of object files required by the given main program.
6913 This information is output in the forms of comments in the generated program,
6914 to be read by the @command{gnatlink} utility used to link the Ada application.
6915 @end enumerate
6916
6917 @node Running gnatbind
6918 @section Running @code{gnatbind}
6919
6920 @noindent
6921 The form of the @code{gnatbind} command is
6922
6923 @smallexample
6924 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6925 @end smallexample
6926
6927 @noindent
6928 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6929 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6930 package in two files whose names are
6931 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6932 For example, if given the
6933 parameter @file{hello.ali}, for a main program contained in file
6934 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6935 and @file{b~hello.adb}.
6936
6937 When doing consistency checking, the binder takes into consideration
6938 any source files it can locate. For example, if the binder determines
6939 that the given main program requires the package @code{Pack}, whose
6940 @file{.ALI}
6941 file is @file{pack.ali} and whose corresponding source spec file is
6942 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6943 (using the same search path conventions as previously described for the
6944 @command{gcc} command). If it can locate this source file, it checks that
6945 the time stamps
6946 or source checksums of the source and its references to in @file{ALI} files
6947 match. In other words, any @file{ALI} files that mentions this spec must have
6948 resulted from compiling this version of the source file (or in the case
6949 where the source checksums match, a version close enough that the
6950 difference does not matter).
6951
6952 @cindex Source files, use by binder
6953 The effect of this consistency checking, which includes source files, is
6954 that the binder ensures that the program is consistent with the latest
6955 version of the source files that can be located at bind time. Editing a
6956 source file without compiling files that depend on the source file cause
6957 error messages to be generated by the binder.
6958
6959 For example, suppose you have a main program @file{hello.adb} and a
6960 package @code{P}, from file @file{p.ads} and you perform the following
6961 steps:
6962
6963 @enumerate
6964 @item
6965 Enter @code{gcc -c hello.adb} to compile the main program.
6966
6967 @item
6968 Enter @code{gcc -c p.ads} to compile package @code{P}.
6969
6970 @item
6971 Edit file @file{p.ads}.
6972
6973 @item
6974 Enter @code{gnatbind hello}.
6975 @end enumerate
6976
6977 @noindent
6978 At this point, the file @file{p.ali} contains an out-of-date time stamp
6979 because the file @file{p.ads} has been edited. The attempt at binding
6980 fails, and the binder generates the following error messages:
6981
6982 @smallexample
6983 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6984 error: "p.ads" has been modified and must be recompiled
6985 @end smallexample
6986
6987 @noindent
6988 Now both files must be recompiled as indicated, and then the bind can
6989 succeed, generating a main program. You need not normally be concerned
6990 with the contents of this file, but for reference purposes a sample
6991 binder output file is given in @ref{Example of Binder Output File}.
6992
6993 In most normal usage, the default mode of @command{gnatbind} which is to
6994 generate the main package in Ada, as described in the previous section.
6995 In particular, this means that any Ada programmer can read and understand
6996 the generated main program. It can also be debugged just like any other
6997 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6998 @command{gnatbind} and @command{gnatlink}.
6999
7000 However for some purposes it may be convenient to generate the main
7001 program in C rather than Ada. This may for example be helpful when you
7002 are generating a mixed language program with the main program in C. The
7003 GNAT compiler itself is an example.
7004 The use of the @option{^-C^/BIND_FILE=C^} switch
7005 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7006 be generated in C (and compiled using the gnu C compiler).
7007
7008 @node Switches for gnatbind
7009 @section Switches for @command{gnatbind}
7010
7011 @noindent
7012 The following switches are available with @code{gnatbind}; details will
7013 be presented in subsequent sections.
7014
7015 @menu
7016 * Consistency-Checking Modes::
7017 * Binder Error Message Control::
7018 * Elaboration Control::
7019 * Output Control::
7020 * Binding with Non-Ada Main Programs::
7021 * Binding Programs with No Main Subprogram::
7022 @end menu
7023
7024 @table @option
7025 @c !sort!
7026 @item ^-aO^/OBJECT_SEARCH^
7027 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7028 Specify directory to be searched for ALI files.
7029
7030 @item ^-aI^/SOURCE_SEARCH^
7031 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7032 Specify directory to be searched for source file.
7033
7034 @item ^-A^/BIND_FILE=ADA^
7035 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7036 Generate binder program in Ada (default)
7037
7038 @item ^-b^/REPORT_ERRORS=BRIEF^
7039 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7040 Generate brief messages to @file{stderr} even if verbose mode set.
7041
7042 @item ^-c^/NOOUTPUT^
7043 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7044 Check only, no generation of binder output file.
7045
7046 @item ^-C^/BIND_FILE=C^
7047 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7048 Generate binder program in C
7049
7050 @item ^-e^/ELABORATION_DEPENDENCIES^
7051 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7052 Output complete list of elaboration-order dependencies.
7053
7054 @item ^-E^/STORE_TRACEBACKS^
7055 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7056 Store tracebacks in exception occurrences when the target supports it.
7057 This is the default with the zero cost exception mechanism.
7058 @ignore
7059 @c The following may get moved to an appendix
7060 This option is currently supported on the following targets:
7061 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7062 @end ignore
7063 See also the packages @code{GNAT.Traceback} and
7064 @code{GNAT.Traceback.Symbolic} for more information.
7065 @ifclear vms
7066 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7067 @command{gcc} option.
7068 @end ifclear
7069
7070 @item ^-F^/FORCE_ELABS_FLAGS^
7071 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7072 Force the checks of elaboration flags. @command{gnatbind} does not normally
7073 generate checks of elaboration flags for the main executable, except when
7074 a Stand-Alone Library is used. However, there are cases when this cannot be
7075 detected by gnatbind. An example is importing an interface of a Stand-Alone
7076 Library through a pragma Import and only specifying through a linker switch
7077 this Stand-Alone Library. This switch is used to guarantee that elaboration
7078 flag checks are generated.
7079
7080 @item ^-h^/HELP^
7081 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7082 Output usage (help) information
7083
7084 @item ^-I^/SEARCH^
7085 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7086 Specify directory to be searched for source and ALI files.
7087
7088 @item ^-I-^/NOCURRENT_DIRECTORY^
7089 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7090 Do not look for sources in the current directory where @code{gnatbind} was
7091 invoked, and do not look for ALI files in the directory containing the
7092 ALI file named in the @code{gnatbind} command line.
7093
7094 @item ^-l^/ORDER_OF_ELABORATION^
7095 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7096 Output chosen elaboration order.
7097
7098 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7099 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7100 Bind the units for library building. In this case the adainit and
7101 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7102 are renamed to ^xxxinit^XXXINIT^ and
7103 ^xxxfinal^XXXFINAL^.
7104 Implies ^-n^/NOCOMPILE^.
7105 @ifclear vms
7106 (@xref{GNAT and Libraries}, for more details.)
7107 @end ifclear
7108 @ifset vms
7109 On OpenVMS, these init and final procedures are exported in uppercase
7110 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7111 the init procedure will be "TOTOINIT" and the exported name of the final
7112 procedure will be "TOTOFINAL".
7113 @end ifset
7114
7115 @item ^-Mxyz^/RENAME_MAIN=xyz^
7116 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7117 Rename generated main program from main to xyz
7118
7119 @item ^-m^/ERROR_LIMIT=^@var{n}
7120 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7121 Limit number of detected errors to @var{n}, where @var{n} is
7122 in the range 1..999_999. The default value if no switch is
7123 given is 9999. Binding is terminated if the limit is exceeded.
7124 @ifset unw
7125 Furthermore, under Windows, the sources pointed to by the libraries path
7126 set in the registry are not searched for.
7127 @end ifset
7128
7129 @item ^-n^/NOMAIN^
7130 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7131 No main program.
7132
7133 @item -nostdinc
7134 @cindex @option{-nostdinc} (@command{gnatbind})
7135 Do not look for sources in the system default directory.
7136
7137 @item -nostdlib
7138 @cindex @option{-nostdlib} (@command{gnatbind})
7139 Do not look for library files in the system default directory.
7140
7141 @item --RTS=@var{rts-path}
7142 @cindex @option{--RTS} (@code{gnatbind})
7143 Specifies the default location of the runtime library. Same meaning as the
7144 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7145
7146 @item ^-o ^/OUTPUT=^@var{file}
7147 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7148 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7149 Note that if this option is used, then linking must be done manually,
7150 gnatlink cannot be used.
7151
7152 @item ^-O^/OBJECT_LIST^
7153 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7154 Output object list.
7155
7156 @item ^-p^/PESSIMISTIC_ELABORATION^
7157 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7158 Pessimistic (worst-case) elaboration order
7159
7160 @item ^-s^/READ_SOURCES=ALL^
7161 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7162 Require all source files to be present.
7163
7164 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7165 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7166 Specifies the value to be used when detecting uninitialized scalar
7167 objects with pragma Initialize_Scalars.
7168 The @var{xxx} ^string specified with the switch^option^ may be either
7169 @itemize @bullet
7170 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7171 @item ``@option{^lo^LOW^}'' for the lowest possible value
7172 possible, and the low
7173 @item ``@option{^hi^HIGH^}'' for the highest possible value
7174 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7175 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7176 @end itemize
7177
7178 In addition, you can specify @option{-Sev} to indicate that the value is
7179 to be set at run time. In this case, the program will look for an environment
7180 @cindex GNAT_INIT_SCALARS
7181 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7182 of @option{in/lo/hi/xx} with the same meanings as above.
7183 If no environment variable is found, or if it does not have a valid value,
7184 then the default is @option{in} (invalid values).
7185
7186 @ifclear vms
7187 @item -static
7188 @cindex @option{-static} (@code{gnatbind})
7189 Link against a static GNAT run time.
7190
7191 @item -shared
7192 @cindex @option{-shared} (@code{gnatbind})
7193 Link against a shared GNAT run time when available.
7194 @end ifclear
7195
7196 @item ^-t^/NOTIME_STAMP_CHECK^
7197 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7198 Tolerate time stamp and other consistency errors
7199
7200 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7201 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7202 Set the time slice value to @var{n} milliseconds. If the system supports
7203 the specification of a specific time slice value, then the indicated value
7204 is used. If the system does not support specific time slice values, but
7205 does support some general notion of round-robin scheduling, then any
7206 non-zero value will activate round-robin scheduling.
7207
7208 A value of zero is treated specially. It turns off time
7209 slicing, and in addition, indicates to the tasking run time that the
7210 semantics should match as closely as possible the Annex D
7211 requirements of the Ada RM, and in particular sets the default
7212 scheduling policy to @code{FIFO_Within_Priorities}.
7213
7214 @item ^-v^/REPORT_ERRORS=VERBOSE^
7215 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7216 Verbose mode. Write error messages, header, summary output to
7217 @file{stdout}.
7218
7219 @ifclear vms
7220 @item -w@var{x}
7221 @cindex @option{-w} (@code{gnatbind})
7222 Warning mode (@var{x}=s/e for suppress/treat as error)
7223 @end ifclear
7224
7225 @ifset vms
7226 @item /WARNINGS=NORMAL
7227 @cindex @option{/WARNINGS} (@code{gnatbind})
7228 Normal warnings mode. Warnings are issued but ignored
7229
7230 @item /WARNINGS=SUPPRESS
7231 @cindex @option{/WARNINGS} (@code{gnatbind})
7232 All warning messages are suppressed
7233
7234 @item /WARNINGS=ERROR
7235 @cindex @option{/WARNINGS} (@code{gnatbind})
7236 Warning messages are treated as fatal errors
7237 @end ifset
7238
7239 @item ^-x^/READ_SOURCES=NONE^
7240 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7241 Exclude source files (check object consistency only).
7242
7243 @ifset vms
7244 @item /READ_SOURCES=AVAILABLE
7245 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7246 Default mode, in which sources are checked for consistency only if
7247 they are available.
7248 @end ifset
7249
7250 @item ^-z^/ZERO_MAIN^
7251 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7252 No main subprogram.
7253 @end table
7254
7255 @ifclear vms
7256 @noindent
7257 You may obtain this listing of switches by running @code{gnatbind} with
7258 no arguments.
7259 @end ifclear
7260
7261 @node Consistency-Checking Modes
7262 @subsection Consistency-Checking Modes
7263
7264 @noindent
7265 As described earlier, by default @code{gnatbind} checks
7266 that object files are consistent with one another and are consistent
7267 with any source files it can locate. The following switches control binder
7268 access to sources.
7269
7270 @table @option
7271 @c !sort!
7272 @item ^-s^/READ_SOURCES=ALL^
7273 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7274 Require source files to be present. In this mode, the binder must be
7275 able to locate all source files that are referenced, in order to check
7276 their consistency. In normal mode, if a source file cannot be located it
7277 is simply ignored. If you specify this switch, a missing source
7278 file is an error.
7279
7280 @item ^-x^/READ_SOURCES=NONE^
7281 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7282 Exclude source files. In this mode, the binder only checks that ALI
7283 files are consistent with one another. Source files are not accessed.
7284 The binder runs faster in this mode, and there is still a guarantee that
7285 the resulting program is self-consistent.
7286 If a source file has been edited since it was last compiled, and you
7287 specify this switch, the binder will not detect that the object
7288 file is out of date with respect to the source file. Note that this is the
7289 mode that is automatically used by @command{gnatmake} because in this
7290 case the checking against sources has already been performed by
7291 @command{gnatmake} in the course of compilation (i.e. before binding).
7292
7293 @ifset vms
7294 @item /READ_SOURCES=AVAILABLE
7295 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7296 This is the default mode in which source files are checked if they are
7297 available, and ignored if they are not available.
7298 @end ifset
7299 @end table
7300
7301 @node Binder Error Message Control
7302 @subsection Binder Error Message Control
7303
7304 @noindent
7305 The following switches provide control over the generation of error
7306 messages from the binder:
7307
7308 @table @option
7309 @c !sort!
7310 @item ^-v^/REPORT_ERRORS=VERBOSE^
7311 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7312 Verbose mode. In the normal mode, brief error messages are generated to
7313 @file{stderr}. If this switch is present, a header is written
7314 to @file{stdout} and any error messages are directed to @file{stdout}.
7315 All that is written to @file{stderr} is a brief summary message.
7316
7317 @item ^-b^/REPORT_ERRORS=BRIEF^
7318 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7319 Generate brief error messages to @file{stderr} even if verbose mode is
7320 specified. This is relevant only when used with the
7321 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7322
7323 @ifclear vms
7324 @item -m@var{n}
7325 @cindex @option{-m} (@code{gnatbind})
7326 Limits the number of error messages to @var{n}, a decimal integer in the
7327 range 1-999. The binder terminates immediately if this limit is reached.
7328
7329 @item -M@var{xxx}
7330 @cindex @option{-M} (@code{gnatbind})
7331 Renames the generated main program from @code{main} to @code{xxx}.
7332 This is useful in the case of some cross-building environments, where
7333 the actual main program is separate from the one generated
7334 by @code{gnatbind}.
7335 @end ifclear
7336
7337 @item ^-ws^/WARNINGS=SUPPRESS^
7338 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7339 @cindex Warnings
7340 Suppress all warning messages.
7341
7342 @item ^-we^/WARNINGS=ERROR^
7343 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7344 Treat any warning messages as fatal errors.
7345
7346 @ifset vms
7347 @item /WARNINGS=NORMAL
7348 Standard mode with warnings generated, but warnings do not get treated
7349 as errors.
7350 @end ifset
7351
7352 @item ^-t^/NOTIME_STAMP_CHECK^
7353 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7354 @cindex Time stamp checks, in binder
7355 @cindex Binder consistency checks
7356 @cindex Consistency checks, in binder
7357 The binder performs a number of consistency checks including:
7358
7359 @itemize @bullet
7360 @item
7361 Check that time stamps of a given source unit are consistent
7362 @item
7363 Check that checksums of a given source unit are consistent
7364 @item
7365 Check that consistent versions of @code{GNAT} were used for compilation
7366 @item
7367 Check consistency of configuration pragmas as required
7368 @end itemize
7369
7370 @noindent
7371 Normally failure of such checks, in accordance with the consistency
7372 requirements of the Ada Reference Manual, causes error messages to be
7373 generated which abort the binder and prevent the output of a binder
7374 file and subsequent link to obtain an executable.
7375
7376 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7377 into warnings, so that
7378 binding and linking can continue to completion even in the presence of such
7379 errors. The result may be a failed link (due to missing symbols), or a
7380 non-functional executable which has undefined semantics.
7381 @emph{This means that
7382 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7383 with extreme care.}
7384 @end table
7385
7386 @node Elaboration Control
7387 @subsection Elaboration Control
7388
7389 @noindent
7390 The following switches provide additional control over the elaboration
7391 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7392
7393 @table @option
7394 @item ^-p^/PESSIMISTIC_ELABORATION^
7395 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7396 Normally the binder attempts to choose an elaboration order that is
7397 likely to minimize the likelihood of an elaboration order error resulting
7398 in raising a @code{Program_Error} exception. This switch reverses the
7399 action of the binder, and requests that it deliberately choose an order
7400 that is likely to maximize the likelihood of an elaboration error.
7401 This is useful in ensuring portability and avoiding dependence on
7402 accidental fortuitous elaboration ordering.
7403
7404 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7405 switch if dynamic
7406 elaboration checking is used (@option{-gnatE} switch used for compilation).
7407 This is because in the default static elaboration mode, all necessary
7408 @code{Elaborate_All} pragmas are implicitly inserted.
7409 These implicit pragmas are still respected by the binder in
7410 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7411 safe elaboration order is assured.
7412 @end table
7413
7414 @node Output Control
7415 @subsection Output Control
7416
7417 @noindent
7418 The following switches allow additional control over the output
7419 generated by the binder.
7420
7421 @table @option
7422 @c !sort!
7423
7424 @item ^-A^/BIND_FILE=ADA^
7425 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7426 Generate binder program in Ada (default). The binder program is named
7427 @file{b~@var{mainprog}.adb} by default. This can be changed with
7428 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7429
7430 @item ^-c^/NOOUTPUT^
7431 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7432 Check only. Do not generate the binder output file. In this mode the
7433 binder performs all error checks but does not generate an output file.
7434
7435 @item ^-C^/BIND_FILE=C^
7436 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7437 Generate binder program in C. The binder program is named
7438 @file{b_@var{mainprog}.c}.
7439 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7440 option.
7441
7442 @item ^-e^/ELABORATION_DEPENDENCIES^
7443 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7444 Output complete list of elaboration-order dependencies, showing the
7445 reason for each dependency. This output can be rather extensive but may
7446 be useful in diagnosing problems with elaboration order. The output is
7447 written to @file{stdout}.
7448
7449 @item ^-h^/HELP^
7450 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7451 Output usage information. The output is written to @file{stdout}.
7452
7453 @item ^-K^/LINKER_OPTION_LIST^
7454 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7455 Output linker options to @file{stdout}. Includes library search paths,
7456 contents of pragmas Ident and Linker_Options, and libraries added
7457 by @code{gnatbind}.
7458
7459 @item ^-l^/ORDER_OF_ELABORATION^
7460 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7461 Output chosen elaboration order. The output is written to @file{stdout}.
7462
7463 @item ^-O^/OBJECT_LIST^
7464 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7465 Output full names of all the object files that must be linked to provide
7466 the Ada component of the program. The output is written to @file{stdout}.
7467 This list includes the files explicitly supplied and referenced by the user
7468 as well as implicitly referenced run-time unit files. The latter are
7469 omitted if the corresponding units reside in shared libraries. The
7470 directory names for the run-time units depend on the system configuration.
7471
7472 @item ^-o ^/OUTPUT=^@var{file}
7473 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7474 Set name of output file to @var{file} instead of the normal
7475 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7476 binder generated body filename. In C mode you would normally give
7477 @var{file} an extension of @file{.c} because it will be a C source program.
7478 Note that if this option is used, then linking must be done manually.
7479 It is not possible to use gnatlink in this case, since it cannot locate
7480 the binder file.
7481
7482 @item ^-r^/RESTRICTION_LIST^
7483 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7484 Generate list of @code{pragma Restrictions} that could be applied to
7485 the current unit. This is useful for code audit purposes, and also may
7486 be used to improve code generation in some cases.
7487
7488 @end table
7489
7490 @node Binding with Non-Ada Main Programs
7491 @subsection Binding with Non-Ada Main Programs
7492
7493 @noindent
7494 In our description so far we have assumed that the main
7495 program is in Ada, and that the task of the binder is to generate a
7496 corresponding function @code{main} that invokes this Ada main
7497 program. GNAT also supports the building of executable programs where
7498 the main program is not in Ada, but some of the called routines are
7499 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7500 The following switch is used in this situation:
7501
7502 @table @option
7503 @item ^-n^/NOMAIN^
7504 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7505 No main program. The main program is not in Ada.
7506 @end table
7507
7508 @noindent
7509 In this case, most of the functions of the binder are still required,
7510 but instead of generating a main program, the binder generates a file
7511 containing the following callable routines:
7512
7513 @table @code
7514 @item adainit
7515 @findex adainit
7516 You must call this routine to initialize the Ada part of the program by
7517 calling the necessary elaboration routines. A call to @code{adainit} is
7518 required before the first call to an Ada subprogram.
7519
7520 Note that it is assumed that the basic execution environment must be setup
7521 to be appropriate for Ada execution at the point where the first Ada
7522 subprogram is called. In particular, if the Ada code will do any
7523 floating-point operations, then the FPU must be setup in an appropriate
7524 manner. For the case of the x86, for example, full precision mode is
7525 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7526 that the FPU is in the right state.
7527
7528 @item adafinal
7529 @findex adafinal
7530 You must call this routine to perform any library-level finalization
7531 required by the Ada subprograms. A call to @code{adafinal} is required
7532 after the last call to an Ada subprogram, and before the program
7533 terminates.
7534 @end table
7535
7536 @noindent
7537 If the @option{^-n^/NOMAIN^} switch
7538 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7539 @cindex Binder, multiple input files
7540 is given, more than one ALI file may appear on
7541 the command line for @code{gnatbind}. The normal @dfn{closure}
7542 calculation is performed for each of the specified units. Calculating
7543 the closure means finding out the set of units involved by tracing
7544 @code{with} references. The reason it is necessary to be able to
7545 specify more than one ALI file is that a given program may invoke two or
7546 more quite separate groups of Ada units.
7547
7548 The binder takes the name of its output file from the last specified ALI
7549 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7550 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7551 The output is an Ada unit in source form that can
7552 be compiled with GNAT unless the -C switch is used in which case the
7553 output is a C source file, which must be compiled using the C compiler.
7554 This compilation occurs automatically as part of the @command{gnatlink}
7555 processing.
7556
7557 Currently the GNAT run time requires a FPU using 80 bits mode
7558 precision. Under targets where this is not the default it is required to
7559 call GNAT.Float_Control.Reset before using floating point numbers (this
7560 include float computation, float input and output) in the Ada code. A
7561 side effect is that this could be the wrong mode for the foreign code
7562 where floating point computation could be broken after this call.
7563
7564 @node Binding Programs with No Main Subprogram
7565 @subsection Binding Programs with No Main Subprogram
7566
7567 @noindent
7568 It is possible to have an Ada program which does not have a main
7569 subprogram. This program will call the elaboration routines of all the
7570 packages, then the finalization routines.
7571
7572 The following switch is used to bind programs organized in this manner:
7573
7574 @table @option
7575 @item ^-z^/ZERO_MAIN^
7576 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7577 Normally the binder checks that the unit name given on the command line
7578 corresponds to a suitable main subprogram. When this switch is used,
7579 a list of ALI files can be given, and the execution of the program
7580 consists of elaboration of these units in an appropriate order.
7581 @end table
7582
7583 @node Command-Line Access
7584 @section Command-Line Access
7585
7586 @noindent
7587 The package @code{Ada.Command_Line} provides access to the command-line
7588 arguments and program name. In order for this interface to operate
7589 correctly, the two variables
7590
7591 @smallexample
7592 @group
7593 int gnat_argc;
7594 char **gnat_argv;
7595 @end group
7596 @end smallexample
7597
7598 @noindent
7599 @findex gnat_argv
7600 @findex gnat_argc
7601 are declared in one of the GNAT library routines. These variables must
7602 be set from the actual @code{argc} and @code{argv} values passed to the
7603 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7604 generates the C main program to automatically set these variables.
7605 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7606 set these variables. If they are not set, the procedures in
7607 @code{Ada.Command_Line} will not be available, and any attempt to use
7608 them will raise @code{Constraint_Error}. If command line access is
7609 required, your main program must set @code{gnat_argc} and
7610 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7611 it.
7612
7613 @node Search Paths for gnatbind
7614 @section Search Paths for @code{gnatbind}
7615
7616 @noindent
7617 The binder takes the name of an ALI file as its argument and needs to
7618 locate source files as well as other ALI files to verify object consistency.
7619
7620 For source files, it follows exactly the same search rules as @command{gcc}
7621 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7622 directories searched are:
7623
7624 @enumerate
7625 @item
7626 The directory containing the ALI file named in the command line, unless
7627 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7628
7629 @item
7630 All directories specified by @option{^-I^/SEARCH^}
7631 switches on the @code{gnatbind}
7632 command line, in the order given.
7633
7634 @item
7635 @findex ADA_OBJECTS_PATH
7636 Each of the directories listed in the value of the
7637 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7638 @ifset unw
7639 Construct this value
7640 exactly as the @code{PATH} environment variable: a list of directory
7641 names separated by colons (semicolons when working with the NT version
7642 of GNAT).
7643 @end ifset
7644 @ifset vms
7645 Normally, define this value as a logical name containing a comma separated
7646 list of directory names.
7647
7648 This variable can also be defined by means of an environment string
7649 (an argument to the DEC C exec* set of functions).
7650
7651 Logical Name:
7652 @smallexample
7653 DEFINE ANOTHER_PATH FOO:[BAG]
7654 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7655 @end smallexample
7656
7657 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7658 first, followed by the standard Ada 95
7659 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7660 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7661 (Text_IO, Sequential_IO, etc)
7662 instead of the Ada95 packages. Thus, in order to get the Ada 95
7663 packages by default, ADA_OBJECTS_PATH must be redefined.
7664 @end ifset
7665
7666 @item
7667 @findex ADA_PRJ_OBJECTS_FILE
7668 Each of the directories listed in the text file whose name is given
7669 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7670
7671 @noindent
7672 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7673 driver when project files are used. It should not normally be set
7674 by other means.
7675
7676 @item
7677 The content of the @file{ada_object_path} file which is part of the GNAT
7678 installation tree and is used to store standard libraries such as the
7679 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7680 specified.
7681 @ifclear vms
7682 @ref{Installing a library}
7683 @end ifclear
7684 @end enumerate
7685
7686 @noindent
7687 In the binder the switch @option{^-I^/SEARCH^}
7688 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7689 is used to specify both source and
7690 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7691 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7692 instead if you want to specify
7693 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7694 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7695 if you want to specify library paths
7696 only. This means that for the binder
7697 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7698 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7699 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7700 The binder generates the bind file (a C language source file) in the
7701 current working directory.
7702
7703 @findex Ada
7704 @findex System
7705 @findex Interfaces
7706 @findex GNAT
7707 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7708 children make up the GNAT Run-Time Library, together with the package
7709 GNAT and its children, which contain a set of useful additional
7710 library functions provided by GNAT. The sources for these units are
7711 needed by the compiler and are kept together in one directory. The ALI
7712 files and object files generated by compiling the RTL are needed by the
7713 binder and the linker and are kept together in one directory, typically
7714 different from the directory containing the sources. In a normal
7715 installation, you need not specify these directory names when compiling
7716 or binding. Either the environment variables or the built-in defaults
7717 cause these files to be found.
7718
7719 Besides simplifying access to the RTL, a major use of search paths is
7720 in compiling sources from multiple directories. This can make
7721 development environments much more flexible.
7722
7723 @node Examples of gnatbind Usage
7724 @section Examples of @code{gnatbind} Usage
7725
7726 @noindent
7727 This section contains a number of examples of using the GNAT binding
7728 utility @code{gnatbind}.
7729
7730 @table @code
7731 @item gnatbind hello
7732 The main program @code{Hello} (source program in @file{hello.adb}) is
7733 bound using the standard switch settings. The generated main program is
7734 @file{b~hello.adb}. This is the normal, default use of the binder.
7735
7736 @ifclear vms
7737 @item gnatbind hello -o mainprog.adb
7738 @end ifclear
7739 @ifset vms
7740 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7741 @end ifset
7742 The main program @code{Hello} (source program in @file{hello.adb}) is
7743 bound using the standard switch settings. The generated main program is
7744 @file{mainprog.adb} with the associated spec in
7745 @file{mainprog.ads}. Note that you must specify the body here not the
7746 spec, in the case where the output is in Ada. Note that if this option
7747 is used, then linking must be done manually, since gnatlink will not
7748 be able to find the generated file.
7749
7750 @ifclear vms
7751 @item gnatbind main -C -o mainprog.c -x
7752 @end ifclear
7753 @ifset vms
7754 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7755 @end ifset
7756 The main program @code{Main} (source program in
7757 @file{main.adb}) is bound, excluding source files from the
7758 consistency checking, generating
7759 the file @file{mainprog.c}.
7760
7761 @ifclear vms
7762 @item gnatbind -x main_program -C -o mainprog.c
7763 This command is exactly the same as the previous example. Switches may
7764 appear anywhere in the command line, and single letter switches may be
7765 combined into a single switch.
7766 @end ifclear
7767
7768 @ifclear vms
7769 @item gnatbind -n math dbase -C -o ada-control.c
7770 @end ifclear
7771 @ifset vms
7772 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7773 @end ifset
7774 The main program is in a language other than Ada, but calls to
7775 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7776 to @code{gnatbind} generates the file @file{ada-control.c} containing
7777 the @code{adainit} and @code{adafinal} routines to be called before and
7778 after accessing the Ada units.
7779 @end table
7780
7781 @c ------------------------------------
7782 @node Linking Using gnatlink
7783 @chapter Linking Using @command{gnatlink}
7784 @c ------------------------------------
7785 @findex gnatlink
7786
7787 @noindent
7788 This chapter discusses @command{gnatlink}, a tool that links
7789 an Ada program and builds an executable file. This utility
7790 invokes the system linker ^(via the @command{gcc} command)^^
7791 with a correct list of object files and library references.
7792 @command{gnatlink} automatically determines the list of files and
7793 references for the Ada part of a program. It uses the binder file
7794 generated by the @command{gnatbind} to determine this list.
7795
7796 @menu
7797 * Running gnatlink::
7798 * Switches for gnatlink::
7799 * Setting Stack Size from gnatlink::
7800 * Setting Heap Size from gnatlink::
7801 @end menu
7802
7803 @node Running gnatlink
7804 @section Running @command{gnatlink}
7805
7806 @noindent
7807 The form of the @command{gnatlink} command is
7808
7809 @smallexample
7810 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7811            [@var{non-Ada objects}] [@var{linker options}]
7812 @end smallexample
7813
7814 @noindent
7815 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
7816 non-Ada objects
7817 or linker options) may be in any order, provided that no non-Ada object may
7818 be mistaken for a main @file{ALI} file.
7819 Any file name @file{F} without the @file{.ali}
7820 extension will be taken as the main @file{ALI} file if a file exists
7821 whose name is the concatenation of @file{F} and @file{.ali}.
7822
7823 @noindent
7824 @file{@var{mainprog}.ali} references the ALI file of the main program.
7825 The @file{.ali} extension of this file can be omitted. From this
7826 reference, @command{gnatlink} locates the corresponding binder file
7827 @file{b~@var{mainprog}.adb} and, using the information in this file along
7828 with the list of non-Ada objects and linker options, constructs a
7829 linker command file to create the executable.
7830
7831 The arguments other than the @command{gnatlink} switches and the main
7832 @file{ALI} file are passed to the linker uninterpreted.
7833 They typically include the names of
7834 object files for units written in other languages than Ada and any library
7835 references required to resolve references in any of these foreign language
7836 units, or in @code{Import} pragmas in any Ada units.
7837
7838 @var{linker options} is an optional list of linker specific
7839 switches.
7840 The default linker called by gnatlink is @var{gcc} which in
7841 turn calls the appropriate system linker.
7842 Standard options for the linker such as @option{-lmy_lib} or
7843 @option{-Ldir} can be added as is.
7844 For options that are not recognized by
7845 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7846 @option{-Wl,}.
7847 Refer to the GCC documentation for
7848 details. Here is an example showing how to generate a linker map:
7849
7850 @ifclear vms
7851 @smallexample
7852 $ gnatlink my_prog -Wl,-Map,MAPFILE
7853 @end smallexample
7854 @end ifclear
7855
7856 @ifset vms
7857 <<Need example for VMS>>
7858 @end ifset
7859
7860 Using @var{linker options} it is possible to set the program stack and
7861 heap size. See @ref{Setting Stack Size from gnatlink} and
7862 @ref{Setting Heap Size from gnatlink}.
7863
7864 @command{gnatlink} determines the list of objects required by the Ada
7865 program and prepends them to the list of objects passed to the linker.
7866 @command{gnatlink} also gathers any arguments set by the use of
7867 @code{pragma Linker_Options} and adds them to the list of arguments
7868 presented to the linker.
7869
7870 @ifset vms
7871 @command{gnatlink} accepts the following types of extra files on the command
7872 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7873 options files (.OPT). These are recognized and handled according to their
7874 extension.
7875 @end ifset
7876
7877 @node Switches for gnatlink
7878 @section Switches for @command{gnatlink}
7879
7880 @noindent
7881 The following switches are available with the @command{gnatlink} utility:
7882
7883 @table @option
7884 @c !sort!
7885
7886 @item ^-A^/BIND_FILE=ADA^
7887 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
7888 The binder has generated code in Ada. This is the default.
7889
7890 @item ^-C^/BIND_FILE=C^
7891 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
7892 If instead of generating a file in Ada, the binder has generated one in
7893 C, then the linker needs to know about it. Use this switch to signal
7894 to @command{gnatlink} that the binder has generated C code rather than
7895 Ada code.
7896
7897 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7898 @cindex Command line length
7899 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
7900 On some targets, the command line length is limited, and @command{gnatlink}
7901 will generate a separate file for the linker if the list of object files
7902 is too long.
7903 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7904 to be generated even if
7905 the limit is not exceeded. This is useful in some cases to deal with
7906 special situations where the command line length is exceeded.
7907
7908 @item ^-g^/DEBUG^
7909 @cindex Debugging information, including
7910 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
7911 The option to include debugging information causes the Ada bind file (in
7912 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7913 @option{^-g^/DEBUG^}.
7914 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7915 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7916 Without @option{^-g^/DEBUG^}, the binder removes these files by
7917 default. The same procedure apply if a C bind file was generated using
7918 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7919 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7920
7921 @item ^-n^/NOCOMPILE^
7922 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
7923 Do not compile the file generated by the binder. This may be used when
7924 a link is rerun with different options, but there is no need to recompile
7925 the binder file.
7926
7927 @item ^-v^/VERBOSE^
7928 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
7929 Causes additional information to be output, including a full list of the
7930 included object files. This switch option is most useful when you want
7931 to see what set of object files are being used in the link step.
7932
7933 @item ^-v -v^/VERBOSE/VERBOSE^
7934 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
7935 Very verbose mode. Requests that the compiler operate in verbose mode when
7936 it compiles the binder file, and that the system linker run in verbose mode.
7937
7938 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7939 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
7940 @var{exec-name} specifies an alternate name for the generated
7941 executable program. If this switch is omitted, the executable has the same
7942 name as the main unit. For example, @code{gnatlink try.ali} creates
7943 an executable called @file{^try^TRY.EXE^}.
7944
7945 @ifclear vms
7946 @item -b @var{target}
7947 @cindex @option{-b} (@command{gnatlink})
7948 Compile your program to run on @var{target}, which is the name of a
7949 system configuration. You must have a GNAT cross-compiler built if
7950 @var{target} is not the same as your host system.
7951
7952 @item -B@var{dir}
7953 @cindex @option{-B} (@command{gnatlink})
7954 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7955 from @var{dir} instead of the default location. Only use this switch
7956 when multiple versions of the GNAT compiler are available. See the
7957 @command{gcc} manual page for further details. You would normally use the
7958 @option{-b} or @option{-V} switch instead.
7959
7960 @item --GCC=@var{compiler_name}
7961 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
7962 Program used for compiling the binder file. The default is
7963 @command{gcc}. You need to use quotes around @var{compiler_name} if
7964 @code{compiler_name} contains spaces or other separator characters. As
7965 an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to use
7966 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7967 inserted after your command name. Thus in the above example the compiler
7968 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
7969 If several @option{--GCC=compiler_name} are used, only the last
7970 @var{compiler_name} is taken into account. However, all the additional
7971 switches are also taken into account. Thus,
7972 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7973 @option{--GCC="bar -x -y -z -t"}.
7974
7975 @item --LINK=@var{name}
7976 @cindex @option{--LINK=} (@command{gnatlink})
7977 @var{name} is the name of the linker to be invoked. This is especially
7978 useful in mixed language programs since languages such as C++ require
7979 their own linker to be used. When this switch is omitted, the default
7980 name for the linker is @command{gcc}. When this switch is used, the
7981 specified linker is called instead of @command{gcc} with exactly the same
7982 parameters that would have been passed to @command{gcc} so if the desired
7983 linker requires different parameters it is necessary to use a wrapper
7984 script that massages the parameters before invoking the real linker. It
7985 may be useful to control the exact invocation by using the verbose
7986 switch.
7987
7988 @end ifclear
7989
7990 @ifset vms
7991 @item /DEBUG=TRACEBACK
7992 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
7993 This qualifier causes sufficient information to be included in the
7994 executable file to allow a traceback, but does not include the full
7995 symbol information needed by the debugger.
7996
7997 @item /IDENTIFICATION="<string>"
7998 @code{"<string>"} specifies the string to be stored in the image file
7999 identification field in the image header.
8000 It overrides any pragma @code{Ident} specified string.
8001
8002 @item /NOINHIBIT-EXEC
8003 Generate the executable file even if there are linker warnings.
8004
8005 @item /NOSTART_FILES
8006 Don't link in the object file containing the ``main'' transfer address.
8007 Used when linking with a foreign language main program compiled with a
8008 Digital compiler.
8009
8010 @item /STATIC
8011 Prefer linking with object libraries over sharable images, even without
8012 /DEBUG.
8013 @end ifset
8014
8015 @end table
8016
8017 @node Setting Stack Size from gnatlink
8018 @section Setting Stack Size from @command{gnatlink}
8019
8020 @noindent
8021 Under Windows systems, it is possible to specify the program stack size from
8022 @command{gnatlink} using either:
8023
8024 @itemize @bullet
8025
8026 @item using @option{-Xlinker} linker option
8027
8028 @smallexample
8029 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
8030 @end smallexample
8031
8032 This sets the stack reserve size to 0x10000 bytes and the stack commit
8033 size to 0x1000 bytes.
8034
8035 @item using @option{-Wl} linker option
8036
8037 @smallexample
8038 $ gnatlink hello -Wl,--stack=0x1000000
8039 @end smallexample
8040
8041 This sets the stack reserve size to 0x1000000 bytes. Note that with
8042 @option{-Wl} option it is not possible to set the stack commit size
8043 because the coma is a separator for this option.
8044
8045 @end itemize
8046
8047 @node Setting Heap Size from gnatlink
8048 @section Setting Heap Size from @command{gnatlink}
8049
8050 @noindent
8051 Under Windows systems, it is possible to specify the program heap size from
8052 @command{gnatlink} using either:
8053
8054 @itemize @bullet
8055
8056 @item using @option{-Xlinker} linker option
8057
8058 @smallexample
8059 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
8060 @end smallexample
8061
8062 This sets the heap reserve size to 0x10000 bytes and the heap commit
8063 size to 0x1000 bytes.
8064
8065 @item using @option{-Wl} linker option
8066
8067 @smallexample
8068 $ gnatlink hello -Wl,--heap=0x1000000
8069 @end smallexample
8070
8071 This sets the heap reserve size to 0x1000000 bytes. Note that with
8072 @option{-Wl} option it is not possible to set the heap commit size
8073 because the coma is a separator for this option.
8074
8075 @end itemize
8076
8077 @node The GNAT Make Program gnatmake
8078 @chapter The GNAT Make Program @command{gnatmake}
8079 @findex gnatmake
8080
8081 @menu
8082 * Running gnatmake::
8083 * Switches for gnatmake::
8084 * Mode Switches for gnatmake::
8085 * Notes on the Command Line::
8086 * How gnatmake Works::
8087 * Examples of gnatmake Usage::
8088 @end menu
8089 @noindent
8090 A typical development cycle when working on an Ada program consists of
8091 the following steps:
8092
8093 @enumerate
8094 @item
8095 Edit some sources to fix bugs.
8096
8097 @item
8098 Add enhancements.
8099
8100 @item
8101 Compile all sources affected.
8102
8103 @item
8104 Rebind and relink.
8105
8106 @item
8107 Test.
8108 @end enumerate
8109
8110 @noindent
8111 The third step can be tricky, because not only do the modified files
8112 @cindex Dependency rules
8113 have to be compiled, but any files depending on these files must also be
8114 recompiled. The dependency rules in Ada can be quite complex, especially
8115 in the presence of overloading, @code{use} clauses, generics and inlined
8116 subprograms.
8117
8118 @command{gnatmake} automatically takes care of the third and fourth steps
8119 of this process. It determines which sources need to be compiled,
8120 compiles them, and binds and links the resulting object files.
8121
8122 Unlike some other Ada make programs, the dependencies are always
8123 accurately recomputed from the new sources. The source based approach of
8124 the GNAT compilation model makes this possible. This means that if
8125 changes to the source program cause corresponding changes in
8126 dependencies, they will always be tracked exactly correctly by
8127 @command{gnatmake}.
8128
8129 @node Running gnatmake
8130 @section Running @command{gnatmake}
8131
8132 @noindent
8133 The usual form of the @command{gnatmake} command is
8134
8135 @smallexample
8136 $ gnatmake [@var{switches}] @var{file_name}
8137       [@var{file_names}] [@var{mode_switches}]
8138 @end smallexample
8139
8140 @noindent
8141 The only required argument is one @var{file_name}, which specifies
8142 a compilation unit that is a main program. Several @var{file_names} can be
8143 specified: this will result in several executables being built.
8144 If @code{switches} are present, they can be placed before the first
8145 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8146 If @var{mode_switches} are present, they must always be placed after
8147 the last @var{file_name} and all @code{switches}.
8148
8149 If you are using standard file extensions (.adb and .ads), then the
8150 extension may be omitted from the @var{file_name} arguments. However, if
8151 you are using non-standard extensions, then it is required that the
8152 extension be given. A relative or absolute directory path can be
8153 specified in a @var{file_name}, in which case, the input source file will
8154 be searched for in the specified directory only. Otherwise, the input
8155 source file will first be searched in the directory where
8156 @command{gnatmake} was invoked and if it is not found, it will be search on
8157 the source path of the compiler as described in
8158 @ref{Search Paths and the Run-Time Library (RTL)}.
8159
8160 All @command{gnatmake} output (except when you specify
8161 @option{^-M^/DEPENDENCIES_LIST^}) is to
8162 @file{stderr}. The output produced by the
8163 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8164 @file{stdout}.
8165
8166 @node Switches for gnatmake
8167 @section Switches for @command{gnatmake}
8168
8169 @noindent
8170 You may specify any of the following switches to @command{gnatmake}:
8171
8172 @table @option
8173 @c !sort!
8174 @ifclear vms
8175 @item --GCC=@var{compiler_name}
8176 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8177 Program used for compiling. The default is `@command{gcc}'. You need to use
8178 quotes around @var{compiler_name} if @code{compiler_name} contains
8179 spaces or other separator characters. As an example @option{--GCC="foo -x
8180 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8181 compiler. Note that switch @option{-c} is always inserted after your
8182 command name. Thus in the above example the compiler command that will
8183 be used by @command{gnatmake} will be @code{foo -c -x -y}.
8184 If several @option{--GCC=compiler_name} are used, only the last
8185 @var{compiler_name} is taken into account. However, all the additional
8186 switches are also taken into account. Thus,
8187 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8188 @option{--GCC="bar -x -y -z -t"}.
8189
8190 @item --GNATBIND=@var{binder_name}
8191 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8192 Program used for binding. The default is `@code{gnatbind}'. You need to
8193 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8194 or other separator characters. As an example @option{--GNATBIND="bar -x
8195 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8196 binder. Binder switches that are normally appended by @command{gnatmake} to
8197 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8198
8199 @item --GNATLINK=@var{linker_name}
8200 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8201 Program used for linking. The default is `@command{gnatlink}'. You need to
8202 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8203 or other separator characters. As an example @option{--GNATLINK="lan -x
8204 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8205 linker. Linker switches that are normally appended by @command{gnatmake} to
8206 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8207
8208 @end ifclear
8209
8210 @item ^-a^/ALL_FILES^
8211 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8212 Consider all files in the make process, even the GNAT internal system
8213 files (for example, the predefined Ada library files), as well as any
8214 locked files. Locked files are files whose ALI file is write-protected.
8215 By default,
8216 @command{gnatmake} does not check these files,
8217 because the assumption is that the GNAT internal files are properly up
8218 to date, and also that any write protected ALI files have been properly
8219 installed. Note that if there is an installation problem, such that one
8220 of these files is not up to date, it will be properly caught by the
8221 binder.
8222 You may have to specify this switch if you are working on GNAT
8223 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8224 in conjunction with @option{^-f^/FORCE_COMPILE^}
8225 if you need to recompile an entire application,
8226 including run-time files, using special configuration pragmas,
8227 such as a @code{Normalize_Scalars} pragma.
8228
8229 By default
8230 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8231 internal files with
8232 @ifclear vms
8233 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8234 @end ifclear
8235 @ifset vms
8236 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8237 @end ifset
8238
8239 @item ^-b^/ACTIONS=BIND^
8240 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8241 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8242 compilation and binding, but no link.
8243 Can be combined with @option{^-l^/ACTIONS=LINK^}
8244 to do binding and linking. When not combined with
8245 @option{^-c^/ACTIONS=COMPILE^}
8246 all the units in the closure of the main program must have been previously
8247 compiled and must be up to date. The root unit specified by @var{file_name}
8248 may be given without extension, with the source extension or, if no GNAT
8249 Project File is specified, with the ALI file extension.
8250
8251 @item ^-c^/ACTIONS=COMPILE^
8252 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8253 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8254 is also specified. Do not perform linking, except if both
8255 @option{^-b^/ACTIONS=BIND^} and
8256  @option{^-l^/ACTIONS=LINK^} are also specified.
8257 If the root unit specified by @var{file_name} is not a main unit, this is the
8258 default. Otherwise @command{gnatmake} will attempt binding and linking
8259 unless all objects are up to date and the executable is more recent than
8260 the objects.
8261
8262 @item ^-C^/MAPPING^
8263 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8264 Use a temporary mapping file. A mapping file is a way to communicate to the
8265 compiler two mappings: from unit names to file names (without any directory
8266 information) and from file names to path names (with full directory
8267 information). These mappings are used by the compiler to short-circuit the path
8268 search. When @command{gnatmake} is invoked with this switch, it will create
8269 a temporary mapping file, initially populated by the project manager,
8270 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8271 Each invocation of the compiler will add the newly accessed sources to the
8272 mapping file. This will improve the source search during the next invocation
8273 of the compiler.
8274
8275 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8276 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8277 Use a specific mapping file. The file, specified as a path name (absolute or
8278 relative) by this switch, should already exist, otherwise the switch is
8279 ineffective. The specified mapping file will be communicated to the compiler.
8280 This switch is not compatible with a project file
8281 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8282 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8283
8284 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8285 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8286 Put all object files and ALI file in directory @var{dir}.
8287 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8288 and ALI files go in the current working directory.
8289
8290 This switch cannot be used when using a project file.
8291
8292 @ifclear vms
8293 @item -eL
8294 @cindex @option{-eL} (@command{gnatmake})
8295 Follow all symbolic links when processing project files.
8296 @end ifclear
8297
8298 @item ^-f^/FORCE_COMPILE^
8299 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8300 Force recompilations. Recompile all sources, even though some object
8301 files may be up to date, but don't recompile predefined or GNAT internal
8302 files or locked files (files with a write-protected ALI file),
8303 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8304
8305 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8306 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8307 When using project files, if some errors or warnings are detected during
8308 parsing and verbose mode is not in effect (no use of switch
8309 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8310 file, rather than its simple file name.
8311
8312 @item ^-i^/IN_PLACE^
8313 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8314 In normal mode, @command{gnatmake} compiles all object files and ALI files
8315 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8316 then instead object files and ALI files that already exist are overwritten
8317 in place. This means that once a large project is organized into separate
8318 directories in the desired manner, then @command{gnatmake} will automatically
8319 maintain and update this organization. If no ALI files are found on the
8320 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8321 the new object and ALI files are created in the
8322 directory containing the source being compiled. If another organization
8323 is desired, where objects and sources are kept in different directories,
8324 a useful technique is to create dummy ALI files in the desired directories.
8325 When detecting such a dummy file, @command{gnatmake} will be forced to
8326 recompile the corresponding source file, and it will be put the resulting
8327 object and ALI files in the directory where it found the dummy file.
8328
8329 @item ^-j^/PROCESSES=^@var{n}
8330 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8331 @cindex Parallel make
8332 Use @var{n} processes to carry out the (re)compilations. On a
8333 multiprocessor machine compilations will occur in parallel. In the
8334 event of compilation errors, messages from various compilations might
8335 get interspersed (but @command{gnatmake} will give you the full ordered
8336 list of failing compiles at the end). If this is problematic, rerun
8337 the make process with n set to 1 to get a clean list of messages.
8338
8339 @item ^-k^/CONTINUE_ON_ERROR^
8340 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8341 Keep going. Continue as much as possible after a compilation error. To
8342 ease the programmer's task in case of compilation errors, the list of
8343 sources for which the compile fails is given when @command{gnatmake}
8344 terminates.
8345
8346 If @command{gnatmake} is invoked with several @file{file_names} and with this
8347 switch, if there are compilation errors when building an executable,
8348 @command{gnatmake} will not attempt to build the following executables.
8349
8350 @item ^-l^/ACTIONS=LINK^
8351 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8352 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8353 and linking. Linking will not be performed if combined with
8354 @option{^-c^/ACTIONS=COMPILE^}
8355 but not with @option{^-b^/ACTIONS=BIND^}.
8356 When not combined with @option{^-b^/ACTIONS=BIND^}
8357 all the units in the closure of the main program must have been previously
8358 compiled and must be up to date, and the main program needs to have been bound.
8359 The root unit specified by @var{file_name}
8360 may be given without extension, with the source extension or, if no GNAT
8361 Project File is specified, with the ALI file extension.
8362
8363 @item ^-m^/MINIMAL_RECOMPILATION^
8364 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8365 Specify that the minimum necessary amount of recompilations
8366 be performed. In this mode @command{gnatmake} ignores time
8367 stamp differences when the only
8368 modifications to a source file consist in adding/removing comments,
8369 empty lines, spaces or tabs. This means that if you have changed the
8370 comments in a source file or have simply reformatted it, using this
8371 switch will tell gnatmake not to recompile files that depend on it
8372 (provided other sources on which these files depend have undergone no
8373 semantic modifications). Note that the debugging information may be
8374 out of date with respect to the sources if the @option{-m} switch causes
8375 a compilation to be switched, so the use of this switch represents a
8376 trade-off between compilation time and accurate debugging information.
8377
8378 @item ^-M^/DEPENDENCIES_LIST^
8379 @cindex Dependencies, producing list
8380 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8381 Check if all objects are up to date. If they are, output the object
8382 dependences to @file{stdout} in a form that can be directly exploited in
8383 a @file{Makefile}. By default, each source file is prefixed with its
8384 (relative or absolute) directory name. This name is whatever you
8385 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8386 and @option{^-I^/SEARCH^} switches. If you use
8387 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8388 @option{^-q^/QUIET^}
8389 (see below), only the source file names,
8390 without relative paths, are output. If you just specify the
8391 @option{^-M^/DEPENDENCIES_LIST^}
8392 switch, dependencies of the GNAT internal system files are omitted. This
8393 is typically what you want. If you also specify
8394 the @option{^-a^/ALL_FILES^} switch,
8395 dependencies of the GNAT internal files are also listed. Note that
8396 dependencies of the objects in external Ada libraries (see switch
8397 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8398 are never reported.
8399
8400 @item ^-n^/DO_OBJECT_CHECK^
8401 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8402 Don't compile, bind, or link. Checks if all objects are up to date.
8403 If they are not, the full name of the first file that needs to be
8404 recompiled is printed.
8405 Repeated use of this option, followed by compiling the indicated source
8406 file, will eventually result in recompiling all required units.
8407
8408 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8409 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8410 Output executable name. The name of the final executable program will be
8411 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8412 name for the executable will be the name of the input file in appropriate form
8413 for an executable file on the host system.
8414
8415 This switch cannot be used when invoking @command{gnatmake} with several
8416 @file{file_names}.
8417
8418 @item ^-P^/PROJECT_FILE=^@var{project}
8419 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8420 Use project file @var{project}. Only one such switch can be used.
8421 @xref{gnatmake and Project Files}.
8422
8423 @item ^-q^/QUIET^
8424 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8425 Quiet. When this flag is not set, the commands carried out by
8426 @command{gnatmake} are displayed.
8427
8428 @item ^-s^/SWITCH_CHECK/^
8429 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8430 Recompile if compiler switches have changed since last compilation.
8431 All compiler switches but -I and -o are taken into account in the
8432 following way:
8433 orders between different ``first letter'' switches are ignored, but
8434 orders between same switches are taken into account. For example,
8435 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8436 is equivalent to @option{-O -g}.
8437
8438 This switch is recommended when Integrated Preprocessing is used.
8439
8440 @item ^-u^/UNIQUE^
8441 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8442 Unique. Recompile at most the main files. It implies -c. Combined with
8443 -f, it is equivalent to calling the compiler directly. Note that using
8444 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8445 (@pxref{Project Files and Main Subprograms}).
8446
8447 @item ^-U^/ALL_PROJECTS^
8448 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8449 When used without a project file or with one or several mains on the command
8450 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8451 on the command line, all sources of all project files are checked and compiled
8452 if not up to date, and libraries are rebuilt, if necessary.
8453
8454 @item ^-v^/REASONS^
8455 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8456 Verbose. Display the reason for all recompilations @command{gnatmake}
8457 decides are necessary.
8458
8459 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8460 Indicate the verbosity of the parsing of GNAT project files.
8461 @xref{Switches Related to Project Files}.
8462
8463 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8464 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8465 Indicate that sources that are not part of any Project File may be compiled.
8466 Normally, when using Project Files, only sources that are part of a Project
8467 File may be compile. When this switch is used, a source outside of all Project
8468 Files may be compiled. The ALI file and the object file will be put in the
8469 object directory of the main Project. The compilation switches used will only
8470 be those specified on the command line.
8471
8472 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8473 Indicate that external variable @var{name} has the value @var{value}.
8474 The Project Manager will use this value for occurrences of
8475 @code{external(name)} when parsing the project file.
8476 @xref{Switches Related to Project Files}.
8477
8478 @item ^-z^/NOMAIN^
8479 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8480 No main subprogram. Bind and link the program even if the unit name
8481 given on the command line is a package name. The resulting executable
8482 will execute the elaboration routines of the package and its closure,
8483 then the finalization routines.
8484
8485 @item ^-g^/DEBUG^
8486 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8487 Enable debugging. This switch is simply passed to the compiler and to the
8488 linker.
8489
8490 @end table
8491
8492 @table @asis
8493 @item @command{gcc} @asis{switches}
8494 @ifclear vms
8495 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8496 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8497 @end ifclear
8498 @ifset vms
8499 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8500 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8501 automatically treated as a compiler switch, and passed on to all
8502 compilations that are carried out.
8503 @end ifset
8504 @end table
8505
8506 @noindent
8507 Source and library search path switches:
8508
8509 @table @option
8510 @c !sort!
8511 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8512 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8513 When looking for source files also look in directory @var{dir}.
8514 The order in which source files search is undertaken is
8515 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8516
8517 @item ^-aL^/SKIP_MISSING=^@var{dir}
8518 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8519 Consider @var{dir} as being an externally provided Ada library.
8520 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8521 files have been located in directory @var{dir}. This allows you to have
8522 missing bodies for the units in @var{dir} and to ignore out of date bodies
8523 for the same units. You still need to specify
8524 the location of the specs for these units by using the switches
8525 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8526 or @option{^-I^/SEARCH=^@var{dir}}.
8527 Note: this switch is provided for compatibility with previous versions
8528 of @command{gnatmake}. The easier method of causing standard libraries
8529 to be excluded from consideration is to write-protect the corresponding
8530 ALI files.
8531
8532 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8533 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8534 When searching for library and object files, look in directory
8535 @var{dir}. The order in which library files are searched is described in
8536 @ref{Search Paths for gnatbind}.
8537
8538 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8539 @cindex Search paths, for @command{gnatmake}
8540 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8541 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8542 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8543
8544 @item ^-I^/SEARCH=^@var{dir}
8545 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8546 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8547 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8548
8549 @item ^-I-^/NOCURRENT_DIRECTORY^
8550 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8551 @cindex Source files, suppressing search
8552 Do not look for source files in the directory containing the source
8553 file named in the command line.
8554 Do not look for ALI or object files in the directory
8555 where @command{gnatmake} was invoked.
8556
8557 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8558 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8559 @cindex Linker libraries
8560 Add directory @var{dir} to the list of directories in which the linker
8561 will search for libraries. This is equivalent to
8562 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8563 @ifclear vms
8564 Furthermore, under Windows, the sources pointed to by the libraries path
8565 set in the registry are not searched for.
8566 @end ifclear
8567
8568 @item -nostdinc
8569 @cindex @option{-nostdinc} (@command{gnatmake})
8570 Do not look for source files in the system default directory.
8571
8572 @item -nostdlib
8573 @cindex @option{-nostdlib} (@command{gnatmake})
8574 Do not look for library files in the system default directory.
8575
8576 @item --RTS=@var{rts-path}
8577 @cindex @option{--RTS} (@command{gnatmake})
8578 Specifies the default location of the runtime library. GNAT looks for the
8579 runtime
8580 in the following directories, and stops as soon as a valid runtime is found
8581 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8582 @file{ada_object_path} present):
8583
8584 @itemize @bullet
8585 @item <current directory>/$rts_path
8586
8587 @item <default-search-dir>/$rts_path
8588
8589 @item <default-search-dir>/rts-$rts_path
8590 @end itemize
8591
8592 @noindent
8593 The selected path is handled like a normal RTS path.
8594
8595 @end table
8596
8597 @node Mode Switches for gnatmake
8598 @section Mode Switches for @command{gnatmake}
8599
8600 @noindent
8601 The mode switches (referred to as @code{mode_switches}) allow the
8602 inclusion of switches that are to be passed to the compiler itself, the
8603 binder or the linker. The effect of a mode switch is to cause all
8604 subsequent switches up to the end of the switch list, or up to the next
8605 mode switch, to be interpreted as switches to be passed on to the
8606 designated component of GNAT.
8607
8608 @table @option
8609 @c !sort!
8610 @item -cargs @var{switches}
8611 @cindex @option{-cargs} (@command{gnatmake})
8612 Compiler switches. Here @var{switches} is a list of switches
8613 that are valid switches for @command{gcc}. They will be passed on to
8614 all compile steps performed by @command{gnatmake}.
8615
8616 @item -bargs @var{switches}
8617 @cindex @option{-bargs} (@command{gnatmake})
8618 Binder switches. Here @var{switches} is a list of switches
8619 that are valid switches for @code{gnatbind}. They will be passed on to
8620 all bind steps performed by @command{gnatmake}.
8621
8622 @item -largs @var{switches}
8623 @cindex @option{-largs} (@command{gnatmake})
8624 Linker switches. Here @var{switches} is a list of switches
8625 that are valid switches for @command{gnatlink}. They will be passed on to
8626 all link steps performed by @command{gnatmake}.
8627
8628 @item -margs @var{switches}
8629 @cindex @option{-margs} (@command{gnatmake})
8630 Make switches. The switches are directly interpreted by @command{gnatmake},
8631 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8632 or @option{-largs}.
8633 @end table
8634
8635 @node Notes on the Command Line
8636 @section Notes on the Command Line
8637
8638 @noindent
8639 This section contains some additional useful notes on the operation
8640 of the @command{gnatmake} command.
8641
8642 @itemize @bullet
8643 @item
8644 @cindex Recompilation, by @command{gnatmake}
8645 If @command{gnatmake} finds no ALI files, it recompiles the main program
8646 and all other units required by the main program.
8647 This means that @command{gnatmake}
8648 can be used for the initial compile, as well as during subsequent steps of
8649 the development cycle.
8650
8651 @item
8652 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8653 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8654 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8655 warning.
8656
8657 @item
8658 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8659 is used to specify both source and
8660 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8661 instead if you just want to specify
8662 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8663 if you want to specify library paths
8664 only.
8665
8666 @item
8667 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8668 This may conveniently be used to exclude standard libraries from
8669 consideration and in particular it means that the use of the
8670 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8671 unless @option{^-a^/ALL_FILES^} is also specified.
8672
8673 @item
8674 @command{gnatmake} has been designed to make the use of Ada libraries
8675 particularly convenient. Assume you have an Ada library organized
8676 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8677 of your Ada compilation units,
8678 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8679 specs of these units, but no bodies. Then to compile a unit
8680 stored in @code{main.adb}, which uses this Ada library you would just type
8681
8682 @smallexample
8683 @ifclear vms
8684 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8685 @end ifclear
8686 @ifset vms
8687 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8688            /SKIP_MISSING=@i{[OBJ_DIR]} main
8689 @end ifset
8690 @end smallexample
8691
8692 @item
8693 Using @command{gnatmake} along with the
8694 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8695 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8696 this switch,
8697 you can update the comments/format of your
8698 source files without having to recompile everything. Note, however, that
8699 adding or deleting lines in a source files may render its debugging
8700 info obsolete. If the file in question is a spec, the impact is rather
8701 limited, as that debugging info will only be useful during the
8702 elaboration phase of your program. For bodies the impact can be more
8703 significant. In all events, your debugger will warn you if a source file
8704 is more recent than the corresponding object, and alert you to the fact
8705 that the debugging information may be out of date.
8706 @end itemize
8707
8708 @node How gnatmake Works
8709 @section How @command{gnatmake} Works
8710
8711 @noindent
8712 Generally @command{gnatmake} automatically performs all necessary
8713 recompilations and you don't need to worry about how it works. However,
8714 it may be useful to have some basic understanding of the @command{gnatmake}
8715 approach and in particular to understand how it uses the results of
8716 previous compilations without incorrectly depending on them.
8717
8718 First a definition: an object file is considered @dfn{up to date} if the
8719 corresponding ALI file exists and if all the source files listed in the
8720 dependency section of this ALI file have time stamps matching those in
8721 the ALI file. This means that neither the source file itself nor any
8722 files that it depends on have been modified, and hence there is no need
8723 to recompile this file.
8724
8725 @command{gnatmake} works by first checking if the specified main unit is up
8726 to date. If so, no compilations are required for the main unit. If not,
8727 @command{gnatmake} compiles the main program to build a new ALI file that
8728 reflects the latest sources. Then the ALI file of the main unit is
8729 examined to find all the source files on which the main program depends,
8730 and @command{gnatmake} recursively applies the above procedure on all these
8731 files.
8732
8733 This process ensures that @command{gnatmake} only trusts the dependencies
8734 in an existing ALI file if they are known to be correct. Otherwise it
8735 always recompiles to determine a new, guaranteed accurate set of
8736 dependencies. As a result the program is compiled ``upside down'' from what may
8737 be more familiar as the required order of compilation in some other Ada
8738 systems. In particular, clients are compiled before the units on which
8739 they depend. The ability of GNAT to compile in any order is critical in
8740 allowing an order of compilation to be chosen that guarantees that
8741 @command{gnatmake} will recompute a correct set of new dependencies if
8742 necessary.
8743
8744 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8745 imported by several of the executables, it will be recompiled at most once.
8746
8747 Note: when using non-standard naming conventions
8748 (@pxref{Using Other File Names}), changing through a configuration pragmas
8749 file the version of a source and invoking @command{gnatmake} to recompile may
8750 have no effect, if the previous version of the source is still accessible
8751 by @command{gnatmake}. It may be necessary to use the switch
8752 ^-f^/FORCE_COMPILE^.
8753
8754 @node Examples of gnatmake Usage
8755 @section Examples of @command{gnatmake} Usage
8756
8757 @table @code
8758 @item gnatmake hello.adb
8759 Compile all files necessary to bind and link the main program
8760 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8761 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8762
8763 @item gnatmake main1 main2 main3
8764 Compile all files necessary to bind and link the main programs
8765 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8766 (containing unit @code{Main2}) and @file{main3.adb}
8767 (containing unit @code{Main3}) and bind and link the resulting object files
8768 to generate three executable files @file{^main1^MAIN1.EXE^},
8769 @file{^main2^MAIN2.EXE^}
8770 and @file{^main3^MAIN3.EXE^}.
8771
8772 @ifclear vms
8773 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8774 @end ifclear
8775
8776 @ifset vms
8777 @item gnatmake Main_Unit /QUIET
8778    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8779    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8780 @end ifset
8781 Compile all files necessary to bind and link the main program unit
8782 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8783 be done with optimization level 2 and the order of elaboration will be
8784 listed by the binder. @command{gnatmake} will operate in quiet mode, not
8785 displaying commands it is executing.
8786 @end table
8787
8788 @c *************************
8789 @node Improving Performance
8790 @chapter Improving Performance
8791 @cindex Improving performance
8792
8793 @noindent
8794 This chapter presents several topics related to program performance.
8795 It first describes some of the tradeoffs that need to be considered
8796 and some of the techniques for making your program run faster.
8797 It then documents the @command{gnatelim} tool, which can reduce
8798 the size of program executables.
8799
8800 @ifnottex
8801 @menu
8802 * Performance Considerations::
8803 * Reducing the Size of Ada Executables with gnatelim::
8804 @end menu
8805 @end ifnottex
8806
8807 @c *****************************
8808 @node Performance Considerations
8809 @section Performance Considerations
8810
8811 @noindent
8812 The GNAT system provides a number of options that allow a trade-off
8813 between
8814
8815 @itemize @bullet
8816 @item
8817 performance of the generated code
8818
8819 @item
8820 speed of compilation
8821
8822 @item
8823 minimization of dependences and recompilation
8824
8825 @item
8826 the degree of run-time checking.
8827 @end itemize
8828
8829 @noindent
8830 The defaults (if no options are selected) aim at improving the speed
8831 of compilation and minimizing dependences, at the expense of performance
8832 of the generated code:
8833
8834 @itemize @bullet
8835 @item
8836 no optimization
8837
8838 @item
8839 no inlining of subprogram calls
8840
8841 @item
8842 all run-time checks enabled except overflow and elaboration checks
8843 @end itemize
8844
8845 @noindent
8846 These options are suitable for most program development purposes. This
8847 chapter describes how you can modify these choices, and also provides
8848 some guidelines on debugging optimized code.
8849
8850 @menu
8851 * Controlling Run-Time Checks::
8852 * Use of Restrictions::
8853 * Optimization Levels::
8854 * Debugging Optimized Code::
8855 * Inlining of Subprograms::
8856 * Optimization and Strict Aliasing::
8857 @ifset vms
8858 * Coverage Analysis::
8859 @end ifset
8860 @end menu
8861
8862 @node Controlling Run-Time Checks
8863 @subsection Controlling Run-Time Checks
8864
8865 @noindent
8866 By default, GNAT generates all run-time checks, except arithmetic overflow
8867 checking for integer operations and checks for access before elaboration on
8868 subprogram calls. The latter are not required in default mode, because all
8869 necessary checking is done at compile time.
8870 @cindex @option{-gnatp} (@command{gcc})
8871 @cindex @option{-gnato} (@command{gcc})
8872 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8873 be modified. @xref{Run-Time Checks}.
8874
8875 Our experience is that the default is suitable for most development
8876 purposes.
8877
8878 We treat integer overflow specially because these
8879 are quite expensive and in our experience are not as important as other
8880 run-time checks in the development process. Note that division by zero
8881 is not considered an overflow check, and divide by zero checks are
8882 generated where required by default.
8883
8884 Elaboration checks are off by default, and also not needed by default, since
8885 GNAT uses a static elaboration analysis approach that avoids the need for
8886 run-time checking. This manual contains a full chapter discussing the issue
8887 of elaboration checks, and if the default is not satisfactory for your use,
8888 you should read this chapter.
8889
8890 For validity checks, the minimal checks required by the Ada Reference
8891 Manual (for case statements and assignments to array elements) are on
8892 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8893 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8894 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8895 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8896 are also suppressed entirely if @option{-gnatp} is used.
8897
8898 @cindex Overflow checks
8899 @cindex Checks, overflow
8900 @findex Suppress
8901 @findex Unsuppress
8902 @cindex pragma Suppress
8903 @cindex pragma Unsuppress
8904 Note that the setting of the switches controls the default setting of
8905 the checks. They may be modified using either @code{pragma Suppress} (to
8906 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8907 checks) in the program source.
8908
8909 @node Use of Restrictions
8910 @subsection Use of Restrictions
8911
8912 @noindent
8913 The use of pragma Restrictions allows you to control which features are
8914 permitted in your program. Apart from the obvious point that if you avoid
8915 relatively expensive features like finalization (enforceable by the use
8916 of pragma Restrictions (No_Finalization), the use of this pragma does not
8917 affect the generated code in most cases.
8918
8919 One notable exception to this rule is that the possibility of task abort
8920 results in some distributed overhead, particularly if finalization or
8921 exception handlers are used. The reason is that certain sections of code
8922 have to be marked as non-abortable.
8923
8924 If you use neither the @code{abort} statement, nor asynchronous transfer
8925 of control (@code{select .. then abort}), then this distributed overhead
8926 is removed, which may have a general positive effect in improving
8927 overall performance.  Especially code involving frequent use of tasking
8928 constructs and controlled types will show much improved performance.
8929 The relevant restrictions pragmas are
8930
8931 @smallexample
8932    pragma Restrictions (No_Abort_Statements);
8933    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8934 @end smallexample
8935
8936 @noindent
8937 It is recommended that these restriction pragmas be used if possible. Note
8938 that this also means that you can write code without worrying about the
8939 possibility of an immediate abort at any point.
8940
8941 @node Optimization Levels
8942 @subsection Optimization Levels
8943 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
8944
8945 @noindent
8946 The default is optimization off. This results in the fastest compile
8947 times, but GNAT makes absolutely no attempt to optimize, and the
8948 generated programs are considerably larger and slower than when
8949 optimization is enabled. You can use the
8950 @ifclear vms
8951 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8952 @end ifclear
8953 @ifset vms
8954 @code{OPTIMIZE} qualifier
8955 @end ifset
8956 to @command{gcc} to control the optimization level:
8957
8958 @table @option
8959 @item ^-O0^/OPTIMIZE=NONE^
8960 No optimization (the default);
8961 generates unoptimized code but has
8962 the fastest compilation time.
8963
8964 @item ^-O1^/OPTIMIZE=SOME^
8965 Medium level optimization;
8966 optimizes reasonably well but does not
8967 degrade compilation time significantly.
8968
8969 @item ^-O2^/OPTIMIZE=ALL^
8970 @ifset vms
8971 @itemx /OPTIMIZE=DEVELOPMENT
8972 @end ifset
8973 Full optimization;
8974 generates highly optimized code and has
8975 the slowest compilation time.
8976
8977 @item ^-O3^/OPTIMIZE=INLINING^
8978 Full optimization as in @option{-O2},
8979 and also attempts automatic inlining of small
8980 subprograms within a unit (@pxref{Inlining of Subprograms}).
8981 @end table
8982
8983 @noindent
8984 Higher optimization levels perform more global transformations on the
8985 program and apply more expensive analysis algorithms in order to generate
8986 faster and more compact code. The price in compilation time, and the
8987 resulting improvement in execution time,
8988 both depend on the particular application and the hardware environment.
8989 You should experiment to find the best level for your application.
8990
8991 Since the precise set of optimizations done at each level will vary from
8992 release to release (and sometime from target to target), it is best to think
8993 of the optimization settings in general terms.
8994 The @cite{Using GNU GCC} manual contains details about
8995 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8996 individually enable or disable specific optimizations.
8997
8998 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8999 been tested extensively at all optimization levels. There are some bugs
9000 which appear only with optimization turned on, but there have also been
9001 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9002 level of optimization does not improve the reliability of the code
9003 generator, which in practice is highly reliable at all optimization
9004 levels.
9005
9006 Note regarding the use of @option{-O3}: The use of this optimization level
9007 is generally discouraged with GNAT, since it often results in larger
9008 executables which run more slowly. See further discussion of this point
9009 in @ref{Inlining of Subprograms}.
9010
9011 @node Debugging Optimized Code
9012 @subsection Debugging Optimized Code
9013 @cindex Debugging optimized code
9014 @cindex Optimization and debugging
9015
9016 @noindent
9017 Although it is possible to do a reasonable amount of debugging at
9018 @ifclear vms
9019 non-zero optimization levels,
9020 the higher the level the more likely that
9021 @end ifclear
9022 @ifset vms
9023 @option{/OPTIMIZE} settings other than @code{NONE},
9024 such settings will make it more likely that
9025 @end ifset
9026 source-level constructs will have been eliminated by optimization.
9027 For example, if a loop is strength-reduced, the loop
9028 control variable may be completely eliminated and thus cannot be
9029 displayed in the debugger.
9030 This can only happen at @option{-O2} or @option{-O3}.
9031 Explicit temporary variables that you code might be eliminated at
9032 ^level^setting^ @option{-O1} or higher.
9033
9034 The use of the @option{^-g^/DEBUG^} switch,
9035 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9036 which is needed for source-level debugging,
9037 affects the size of the program executable on disk,
9038 and indeed the debugging information can be quite large.
9039 However, it has no effect on the generated code (and thus does not
9040 degrade performance)
9041
9042 Since the compiler generates debugging tables for a compilation unit before
9043 it performs optimizations, the optimizing transformations may invalidate some
9044 of the debugging data.  You therefore need to anticipate certain
9045 anomalous situations that may arise while debugging optimized code.
9046 These are the most common cases:
9047
9048 @enumerate
9049 @item
9050 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9051 commands show
9052 the PC bouncing back and forth in the code.  This may result from any of
9053 the following optimizations:
9054
9055 @itemize @bullet
9056 @item
9057 @i{Common subexpression elimination:} using a single instance of code for a
9058 quantity that the source computes several times.  As a result you
9059 may not be able to stop on what looks like a statement.
9060
9061 @item
9062 @i{Invariant code motion:} moving an expression that does not change within a
9063 loop, to the beginning of the loop.
9064
9065 @item
9066 @i{Instruction scheduling:} moving instructions so as to
9067 overlap loads and stores (typically) with other code, or in
9068 general to move computations of values closer to their uses. Often
9069 this causes you to pass an assignment statement without the assignment
9070 happening and then later bounce back to the statement when the
9071 value is actually needed.  Placing a breakpoint on a line of code
9072 and then stepping over it may, therefore, not always cause all the
9073 expected side-effects.
9074 @end itemize
9075
9076 @item
9077 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9078 two identical pieces of code are merged and the program counter suddenly
9079 jumps to a statement that is not supposed to be executed, simply because
9080 it (and the code following) translates to the same thing as the code
9081 that @emph{was} supposed to be executed.  This effect is typically seen in
9082 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9083 a @code{break} in a C @code{^switch^switch^} statement.
9084
9085 @item
9086 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9087 There are various reasons for this effect:
9088
9089 @itemize @bullet
9090 @item
9091 In a subprogram prologue, a parameter may not yet have been moved to its
9092 ``home''.
9093
9094 @item
9095 A variable may be dead, and its register re-used.  This is
9096 probably the most common cause.
9097
9098 @item
9099 As mentioned above, the assignment of a value to a variable may
9100 have been moved.
9101
9102 @item
9103 A variable may be eliminated entirely by value propagation or
9104 other means.  In this case, GCC may incorrectly generate debugging
9105 information for the variable
9106 @end itemize
9107
9108 @noindent
9109 In general, when an unexpected value appears for a local variable or parameter
9110 you should first ascertain if that value was actually computed by
9111 your program, as opposed to being incorrectly reported by the debugger.
9112 Record fields or
9113 array elements in an object designated by an access value
9114 are generally less of a problem, once you have ascertained that the access
9115 value is sensible.
9116 Typically, this means checking variables in the preceding code and in the
9117 calling subprogram to verify that the value observed is explainable from other
9118 values (one must apply the procedure recursively to those
9119 other values); or re-running the code and stopping a little earlier
9120 (perhaps before the call) and stepping to better see how the variable obtained
9121 the value in question; or continuing to step @emph{from} the point of the
9122 strange value to see if code motion had simply moved the variable's
9123 assignments later.
9124 @end enumerate
9125
9126 @noindent
9127 In light of such anomalies, a recommended technique is to use @option{-O0}
9128 early in the software development cycle, when extensive debugging capabilities
9129 are most needed, and then move to @option{-O1} and later @option{-O2} as
9130 the debugger becomes less critical.
9131 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9132 a release management issue.
9133 @ifclear vms
9134 Note that if you use @option{-g} you can then use the @command{strip} program
9135 on the resulting executable,
9136 which removes both debugging information and global symbols.
9137 @end ifclear
9138
9139 @node Inlining of Subprograms
9140 @subsection Inlining of Subprograms
9141
9142 @noindent
9143 A call to a subprogram in the current unit is inlined if all the
9144 following conditions are met:
9145
9146 @itemize @bullet
9147 @item
9148 The optimization level is at least @option{-O1}.
9149
9150 @item
9151 The called subprogram is suitable for inlining: It must be small enough
9152 and not contain nested subprograms or anything else that @command{gcc}
9153 cannot support in inlined subprograms.
9154
9155 @item
9156 The call occurs after the definition of the body of the subprogram.
9157
9158 @item
9159 @cindex pragma Inline
9160 @findex Inline
9161 Either @code{pragma Inline} applies to the subprogram or it is
9162 small and automatic inlining (optimization level @option{-O3}) is
9163 specified.
9164 @end itemize
9165
9166 @noindent
9167 Calls to subprograms in @code{with}'ed units are normally not inlined.
9168 To achieve this level of inlining, the following conditions must all be
9169 true:
9170
9171 @itemize @bullet
9172 @item
9173 The optimization level is at least @option{-O1}.
9174
9175 @item
9176 The called subprogram is suitable for inlining: It must be small enough
9177 and not contain nested subprograms or anything else @command{gcc} cannot
9178 support in inlined subprograms.
9179
9180 @item
9181 The call appears in a body (not in a package spec).
9182
9183 @item
9184 There is a @code{pragma Inline} for the subprogram.
9185
9186 @item
9187 @cindex @option{-gnatn} (@command{gcc})
9188 The @option{^-gnatn^/INLINE^} switch
9189 is used in the @command{gcc} command line
9190 @end itemize
9191
9192 Note that specifying the @option{-gnatn} switch causes additional
9193 compilation dependencies. Consider the following:
9194
9195 @smallexample @c ada
9196 @cartouche
9197 package R is
9198    procedure Q;
9199    pragma Inline (Q);
9200 end R;
9201 package body R is
9202    ...
9203 end R;
9204
9205 with R;
9206 procedure Main is
9207 begin
9208    ...
9209    R.Q;
9210 end Main;
9211 @end cartouche
9212 @end smallexample
9213
9214 @noindent
9215 With the default behavior (no @option{-gnatn} switch specified), the
9216 compilation of the @code{Main} procedure depends only on its own source,
9217 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9218 means that editing the body of @code{R} does not require recompiling
9219 @code{Main}.
9220
9221 On the other hand, the call @code{R.Q} is not inlined under these
9222 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9223 is compiled, the call will be inlined if the body of @code{Q} is small
9224 enough, but now @code{Main} depends on the body of @code{R} in
9225 @file{r.adb} as well as on the spec. This means that if this body is edited,
9226 the main program must be recompiled. Note that this extra dependency
9227 occurs whether or not the call is in fact inlined by @command{gcc}.
9228
9229 The use of front end inlining with @option{-gnatN} generates similar
9230 additional dependencies.
9231
9232 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9233 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9234 can be used to prevent
9235 all inlining. This switch overrides all other conditions and ensures
9236 that no inlining occurs. The extra dependences resulting from
9237 @option{-gnatn} will still be active, even if
9238 this switch is used to suppress the resulting inlining actions.
9239
9240 Note regarding the use of @option{-O3}: There is no difference in inlining
9241 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9242 pragma @code{Inline} assuming the use of @option{-gnatn}
9243 or @option{-gnatN} (the switches that activate inlining). If you have used
9244 pragma @code{Inline} in appropriate cases, then it is usually much better
9245 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9246 in this case only has the effect of inlining subprograms you did not
9247 think should be inlined. We often find that the use of @option{-O3} slows
9248 down code by performing excessive inlining, leading to increased instruction
9249 cache pressure from the increased code size. So the bottom line here is
9250 that you should not automatically assume that @option{-O3} is better than
9251 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9252 it actually improves performance.
9253
9254 @node Optimization and Strict Aliasing
9255 @subsection Optimization and Strict Aliasing
9256 @cindex Aliasing
9257 @cindex Strict Aliasing
9258 @cindex No_Strict_Aliasing
9259
9260 @noindent
9261 The strong typing capabilities of Ada allow an optimizer to generate
9262 efficient code in situations where other languages would be forced to
9263 make worst case assumptions preventing such optimizations. Consider
9264 the following example:
9265
9266 @smallexample @c ada
9267 @cartouche
9268 procedure R is
9269    type Int1 is new Integer;
9270    type Int2 is new Integer;
9271    type Int1A is access Int1;
9272    type Int2A is access Int2;
9273    Int1V : Int1A;
9274    Int2V : Int2A;
9275    ...
9276
9277 begin
9278    ...
9279    for J in Data'Range loop
9280       if Data (J) = Int1V.all then
9281          Int2V.all := Int2V.all + 1;
9282       end if;
9283    end loop;
9284    ...
9285 end R;
9286 @end cartouche
9287 @end smallexample
9288
9289 @noindent
9290 In this example, since the variable @code{Int1V} can only access objects
9291 of type @code{Int1}, and @code{Int2V} can only access objects of type
9292 @code{Int2}, there is no possibility that the assignment to
9293 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9294 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9295 for all iterations of the loop and avoid the extra memory reference
9296 required to dereference it each time through the loop.
9297
9298 This kind of optimziation, called strict aliasing analysis, is
9299 triggered by specifying an optimization level of @option{-O2} or
9300 higher and allows @code{GNAT} to generate more efficient code
9301 when access values are involved.
9302
9303 However, although this optimization is always correct in terms of
9304 the formal semantics of the Ada Reference Manual, difficulties can
9305 arise if features like @code{Unchecked_Conversion} are used to break
9306 the typing system. Consider the following complete program example:
9307
9308 @smallexample @c ada
9309 @cartouche
9310 package p1 is
9311    type int1 is new integer;
9312    type int2 is new integer;
9313    type a1 is access int1;
9314    type a2 is access int2;
9315 end p1;
9316
9317 with p1; use p1;
9318 package p2 is
9319    function to_a2 (Input : a1) return a2;
9320 end p2;
9321
9322 with Unchecked_Conversion;
9323 package body p2 is
9324    function to_a2 (Input : a1) return a2 is
9325       function to_a2u is
9326         new Unchecked_Conversion (a1, a2);
9327    begin
9328       return to_a2u (Input);
9329    end to_a2;
9330 end p2;
9331
9332 with p2; use p2;
9333 with p1; use p1;
9334 with Text_IO; use Text_IO;
9335 procedure m is
9336    v1 : a1 := new int1;
9337    v2 : a2 := to_a2 (v1);
9338 begin
9339    v1.all := 1;
9340    v2.all := 0;
9341    put_line (int1'image (v1.all));
9342 end;
9343 @end cartouche
9344 @end smallexample
9345
9346 @noindent
9347 This program prints out 0 in @code{-O0} or @code{-O1}
9348 mode, but it prints out 1 in @code{-O2} mode. That's
9349 because in strict aliasing mode, the compiler can and
9350 does assume that the assignment to @code{v2.all} could not
9351 affect the value of @code{v1.all}, since different types
9352 are involved.
9353
9354 This behavior is not a case of non-conformance with the standard, since
9355 the Ada RM specifies that an unchecked conversion where the resulting
9356 bit pattern is not a correct value of the target type can result in an
9357 abnormal value and attempting to reference an abnormal value makes the
9358 execution of a program erroneous.  That's the case here since the result
9359 does not point to an object of type @code{int2}.  This means that the
9360 effect is entirely unpredictable.
9361
9362 However, although that explanation may satisfy a language
9363 lawyer, in practice an applications programmer expects an
9364 unchecked conversion involving pointers to create true
9365 aliases and the behavior of printing 1 seems plain wrong.
9366 In this case, the strict aliasing optimization is unwelcome.
9367
9368 Indeed the compiler recognizes this possibility, and the
9369 unchecked conversion generates a warning:
9370
9371 @smallexample
9372 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9373 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9374 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9375 @end smallexample
9376
9377 @noindent
9378 Unfortunately the problem is recognized when compiling the body of
9379 package @code{p2}, but the actual "bad" code is generated while
9380 compiling the body of @code{m} and this latter compilation does not see
9381 the suspicious @code{Unchecked_Conversion}.
9382
9383 As implied by the warning message, there are approaches you can use to
9384 avoid the unwanted strict aliasing optimization in a case like this.
9385
9386 One possibility is to simply avoid the use of @code{-O2}, but
9387 that is a bit drastic, since it throws away a number of useful
9388 optimizations that do not involve strict aliasing assumptions.
9389
9390 A less drastic approach is to compile the program using the
9391 option @code{-fno-strict-aliasing}. Actually it is only the
9392 unit containing the dereferencing of the suspicious pointer
9393 that needs to be compiled. So in this case, if we compile
9394 unit @code{m} with this switch, then we get the expected
9395 value of zero printed. Analyzing which units might need
9396 the switch can be painful, so a more reasonable approach
9397 is to compile the entire program with options @code{-O2}
9398 and @code{-fno-strict-aliasing}. If the performance is
9399 satisfactory with this combination of options, then the
9400 advantage is that the entire issue of possible "wrong"
9401 optimization due to strict aliasing is avoided.
9402
9403 To avoid the use of compiler switches, the configuration
9404 pragma @code{No_Strict_Aliasing} with no parameters may be
9405 used to specify that for all access types, the strict
9406 aliasing optimization should be suppressed.
9407
9408 However, these approaches are still overkill, in that they causes
9409 all manipulations of all access values to be deoptimized. A more
9410 refined approach is to concentrate attention on the specific
9411 access type identified as problematic.
9412
9413 First, if a careful analysis of uses of the pointer shows
9414 that there are no possible problematic references, then
9415 the warning can be suppressed by bracketing the
9416 instantiation of @code{Unchecked_Conversion} to turn
9417 the warning off:
9418
9419 @smallexample @c ada
9420    pragma Warnings (Off);
9421    function to_a2u is
9422      new Unchecked_Conversion (a1, a2);
9423    pragma Warnings (On);
9424 @end smallexample
9425
9426 @noindent
9427 Of course that approach is not appropriate for this particular
9428 example, since indeed there is a problematic reference. In this
9429 case we can take one of two other approaches.
9430
9431 The first possibility is to move the instantiation of unchecked
9432 conversion to the unit in which the type is declared. In
9433 this example, we would move the instantiation of
9434 @code{Unchecked_Conversion} from the body of package
9435 @code{p2} to the spec of package @code{p1}. Now the
9436 warning disappears. That's because any use of the
9437 access type knows there is a suspicious unchecked
9438 conversion, and the strict aliasing optimization
9439 is automatically suppressed for the type.
9440
9441 If it is not practical to move the unchecked conversion to the same unit
9442 in which the destination access type is declared (perhaps because the
9443 source type is not visible in that unit), you may use pragma
9444 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9445 same declarative sequence as the declaration of the access type:
9446
9447 @smallexample @c ada
9448    type a2 is access int2;
9449    pragma No_Strict_Aliasing (a2);
9450 @end smallexample
9451
9452 @noindent
9453 Here again, the compiler now knows that the strict aliasing optimization
9454 should be suppressed for any reference to type @code{a2} and the
9455 expected behavior is obtained.
9456
9457 Finally, note that although the compiler can generate warnings for
9458 simple cases of unchecked conversions, there are tricker and more
9459 indirect ways of creating type incorrect aliases which the compiler
9460 cannot detect. Examples are the use of address overlays and unchecked
9461 conversions involving composite types containing access types as
9462 components. In such cases, no warnings are generated, but there can
9463 still be aliasing problems. One safe coding practice is to forbid the
9464 use of address clauses for type overlaying, and to allow unchecked
9465 conversion only for primitive types. This is not really a significant
9466 restriction since any possible desired effect can be achieved by
9467 unchecked conversion of access values.
9468
9469 @ifset vms
9470 @node Coverage Analysis
9471 @subsection Coverage Analysis
9472
9473 @noindent
9474 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9475 the user to determine the distribution of execution time across a program,
9476 @pxref{Profiling} for details of usage.
9477 @end ifset
9478
9479 @node Reducing the Size of Ada Executables with gnatelim
9480 @section Reducing the Size of Ada Executables with @code{gnatelim}
9481 @findex gnatelim
9482
9483 @noindent
9484 This section describes @command{gnatelim}, a tool which detects unused
9485 subprograms and helps the compiler to create a smaller executable for your
9486 program.
9487
9488 @menu
9489 * About gnatelim::
9490 * Running gnatelim::
9491 * Correcting the List of Eliminate Pragmas::
9492 * Making Your Executables Smaller::
9493 * Summary of the gnatelim Usage Cycle::
9494 @end menu
9495
9496 @node About gnatelim
9497 @subsection About @code{gnatelim}
9498
9499 @noindent
9500 When a program shares a set of Ada
9501 packages with other programs, it may happen that this program uses
9502 only a fraction of the subprograms defined in these packages. The code
9503 created for these unused subprograms increases the size of the executable.
9504
9505 @code{gnatelim} tracks unused subprograms in an Ada program and
9506 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9507 subprograms that are declared but never called. By placing the list of
9508 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9509 recompiling your program, you may decrease the size of its executable,
9510 because the compiler will not generate the code for 'eliminated' subprograms.
9511 See GNAT Reference Manual for more information about this pragma.
9512
9513 @code{gnatelim} needs as its input data the name of the main subprogram
9514 and a bind file for a main subprogram.
9515
9516 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9517 the main subprogram. @code{gnatelim} can work with both Ada and C
9518 bind files; when both are present, it uses the Ada bind file.
9519 The following commands will build the program and create the bind file:
9520
9521 @smallexample
9522 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9523 $ gnatbind main_prog
9524 @end smallexample
9525
9526 Note that @code{gnatelim} needs neither object nor ALI files.
9527
9528 @node Running gnatelim
9529 @subsection Running @code{gnatelim}
9530
9531 @noindent
9532 @code{gnatelim} has the following command-line interface:
9533
9534 @smallexample
9535 $ gnatelim [options] name
9536 @end smallexample
9537
9538 @noindent
9539 @code{name} should be a name of a source file that contains the main subprogram
9540 of a program (partition).
9541
9542 @code{gnatelim} has the following switches:
9543
9544 @table @option
9545 @c !sort!
9546 @item ^-q^/QUIET^
9547 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9548 Quiet mode: by default @code{gnatelim} outputs to the standard error
9549 stream the number of program units left to be processed. This option turns
9550 this trace off.
9551
9552 @item ^-v^/VERBOSE^
9553 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9554 Verbose mode: @code{gnatelim} version information is printed as Ada
9555 comments to the standard output stream. Also, in addition to the number of
9556 program units left @code{gnatelim} will output the name of the current unit
9557 being processed.
9558
9559 @item ^-a^/ALL^
9560 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9561 Also look for subprograms from the GNAT run time that can be eliminated. Note
9562 that when @file{gnat.adc} is produced using this switch, the entire program
9563 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9564
9565 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9566 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9567 When looking for source files also look in directory @var{dir}. Specifying
9568 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9569 sources in the current directory.
9570
9571 @item ^-b^/BIND_FILE=^@var{bind_file}
9572 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9573 Specifies @var{bind_file} as the bind file to process. If not set, the name
9574 of the bind file is computed from the full expanded Ada name
9575 of a main subprogram.
9576
9577 @item ^-C^/CONFIG_FILE=^@var{config_file}
9578 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9579 Specifies a file @var{config_file} that contains configuration pragmas. The
9580 file must be specified with full path.
9581
9582 @item ^--GCC^/COMPILER^=@var{compiler_name}
9583 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9584 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9585 available on the path.
9586
9587 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9588 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9589 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9590 available on the path.
9591 @end table
9592
9593 @noindent
9594 @code{gnatelim} sends its output to the standard output stream, and all the
9595 tracing and debug information is sent to the standard error stream.
9596 In order to produce a proper GNAT configuration file
9597 @file{gnat.adc}, redirection must be used:
9598
9599 @smallexample
9600 @ifset vms
9601 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9602 @end ifset
9603 @ifclear vms
9604 $ gnatelim main_prog.adb > gnat.adc
9605 @end ifclear
9606 @end smallexample
9607
9608 @ifclear vms
9609 @noindent
9610 or
9611
9612 @smallexample
9613 $ gnatelim main_prog.adb >> gnat.adc
9614 @end smallexample
9615
9616 @noindent
9617 in order to append the @code{gnatelim} output to the existing contents of
9618 @file{gnat.adc}.
9619 @end ifclear
9620
9621 @node Correcting the List of Eliminate Pragmas
9622 @subsection Correcting the List of Eliminate Pragmas
9623
9624 @noindent
9625 In some rare cases @code{gnatelim} may try to eliminate
9626 subprograms that are actually called in the program. In this case, the
9627 compiler will generate an error message of the form:
9628
9629 @smallexample
9630 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9631 @end smallexample
9632
9633 @noindent
9634 You will need to manually remove the wrong @code{Eliminate} pragmas from
9635 the @file{gnat.adc} file. You should recompile your program
9636 from scratch after that, because you need a consistent @file{gnat.adc} file
9637 during the entire compilation.
9638
9639 @node Making Your Executables Smaller
9640 @subsection Making Your Executables Smaller
9641
9642 @noindent
9643 In order to get a smaller executable for your program you now have to
9644 recompile the program completely with the new @file{gnat.adc} file
9645 created by @code{gnatelim} in your current directory:
9646
9647 @smallexample
9648 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9649 @end smallexample
9650
9651 @noindent
9652 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9653 recompile everything
9654 with the set of pragmas @code{Eliminate} that you have obtained with
9655 @command{gnatelim}).
9656
9657 Be aware that the set of @code{Eliminate} pragmas is specific to each
9658 program. It is not recommended to merge sets of @code{Eliminate}
9659 pragmas created for different programs in one @file{gnat.adc} file.
9660
9661 @node Summary of the gnatelim Usage Cycle
9662 @subsection Summary of the gnatelim Usage Cycle
9663
9664 @noindent
9665 Here is a quick summary of the steps to be taken in order to reduce
9666 the size of your executables with @code{gnatelim}. You may use
9667 other GNAT options to control the optimization level,
9668 to produce the debugging information, to set search path, etc.
9669
9670 @enumerate
9671 @item
9672 Produce a bind file
9673
9674 @smallexample
9675 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9676 $ gnatbind main_prog
9677 @end smallexample
9678
9679 @item
9680 Generate a list of @code{Eliminate} pragmas
9681 @smallexample
9682 @ifset vms
9683 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9684 @end ifset
9685 @ifclear vms
9686 $ gnatelim main_prog >[>] gnat.adc
9687 @end ifclear
9688 @end smallexample
9689
9690 @item
9691 Recompile the application
9692
9693 @smallexample
9694 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9695 @end smallexample
9696
9697 @end enumerate
9698
9699 @c ********************************
9700 @node Renaming Files Using gnatchop
9701 @chapter Renaming Files Using @code{gnatchop}
9702 @findex gnatchop
9703
9704 @noindent
9705 This chapter discusses how to handle files with multiple units by using
9706 the @code{gnatchop} utility. This utility is also useful in renaming
9707 files to meet the standard GNAT default file naming conventions.
9708
9709 @menu
9710 * Handling Files with Multiple Units::
9711 * Operating gnatchop in Compilation Mode::
9712 * Command Line for gnatchop::
9713 * Switches for gnatchop::
9714 * Examples of gnatchop Usage::
9715 @end menu
9716
9717 @node Handling Files with Multiple Units
9718 @section Handling Files with Multiple Units
9719
9720 @noindent
9721 The basic compilation model of GNAT requires that a file submitted to the
9722 compiler have only one unit and there be a strict correspondence
9723 between the file name and the unit name.
9724
9725 The @code{gnatchop} utility allows both of these rules to be relaxed,
9726 allowing GNAT to process files which contain multiple compilation units
9727 and files with arbitrary file names. @code{gnatchop}
9728 reads the specified file and generates one or more output files,
9729 containing one unit per file. The unit and the file name correspond,
9730 as required by GNAT.
9731
9732 If you want to permanently restructure a set of ``foreign'' files so that
9733 they match the GNAT rules, and do the remaining development using the
9734 GNAT structure, you can simply use @command{gnatchop} once, generate the
9735 new set of files and work with them from that point on.
9736
9737 Alternatively, if you want to keep your files in the ``foreign'' format,
9738 perhaps to maintain compatibility with some other Ada compilation
9739 system, you can set up a procedure where you use @command{gnatchop} each
9740 time you compile, regarding the source files that it writes as temporary
9741 files that you throw away.
9742
9743 @node Operating gnatchop in Compilation Mode
9744 @section Operating gnatchop in Compilation Mode
9745
9746 @noindent
9747 The basic function of @code{gnatchop} is to take a file with multiple units
9748 and split it into separate files. The boundary between files is reasonably
9749 clear, except for the issue of comments and pragmas. In default mode, the
9750 rule is that any pragmas between units belong to the previous unit, except
9751 that configuration pragmas always belong to the following unit. Any comments
9752 belong to the following unit. These rules
9753 almost always result in the right choice of
9754 the split point without needing to mark it explicitly and most users will
9755 find this default to be what they want. In this default mode it is incorrect to
9756 submit a file containing only configuration pragmas, or one that ends in
9757 configuration pragmas, to @code{gnatchop}.
9758
9759 However, using a special option to activate ``compilation mode'',
9760 @code{gnatchop}
9761 can perform another function, which is to provide exactly the semantics
9762 required by the RM for handling of configuration pragmas in a compilation.
9763 In the absence of configuration pragmas (at the main file level), this
9764 option has no effect, but it causes such configuration pragmas to be handled
9765 in a quite different manner.
9766
9767 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9768 only configuration pragmas, then this file is appended to the
9769 @file{gnat.adc} file in the current directory. This behavior provides
9770 the required behavior described in the RM for the actions to be taken
9771 on submitting such a file to the compiler, namely that these pragmas
9772 should apply to all subsequent compilations in the same compilation
9773 environment. Using GNAT, the current directory, possibly containing a
9774 @file{gnat.adc} file is the representation
9775 of a compilation environment. For more information on the
9776 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
9777
9778 Second, in compilation mode, if @code{gnatchop}
9779 is given a file that starts with
9780 configuration pragmas, and contains one or more units, then these
9781 configuration pragmas are prepended to each of the chopped files. This
9782 behavior provides the required behavior described in the RM for the
9783 actions to be taken on compiling such a file, namely that the pragmas
9784 apply to all units in the compilation, but not to subsequently compiled
9785 units.
9786
9787 Finally, if configuration pragmas appear between units, they are appended
9788 to the previous unit. This results in the previous unit being illegal,
9789 since the compiler does not accept configuration pragmas that follow
9790 a unit. This provides the required RM behavior that forbids configuration
9791 pragmas other than those preceding the first compilation unit of a
9792 compilation.
9793
9794 For most purposes, @code{gnatchop} will be used in default mode. The
9795 compilation mode described above is used only if you need exactly
9796 accurate behavior with respect to compilations, and you have files
9797 that contain multiple units and configuration pragmas. In this
9798 circumstance the use of @code{gnatchop} with the compilation mode
9799 switch provides the required behavior, and is for example the mode
9800 in which GNAT processes the ACVC tests.
9801
9802 @node Command Line for gnatchop
9803 @section Command Line for @code{gnatchop}
9804
9805 @noindent
9806 The @code{gnatchop} command has the form:
9807
9808 @smallexample
9809 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9810       [@var{directory}]
9811 @end smallexample
9812
9813 @noindent
9814 The only required argument is the file name of the file to be chopped.
9815 There are no restrictions on the form of this file name. The file itself
9816 contains one or more Ada units, in normal GNAT format, concatenated
9817 together. As shown, more than one file may be presented to be chopped.
9818
9819 When run in default mode, @code{gnatchop} generates one output file in
9820 the current directory for each unit in each of the files.
9821
9822 @var{directory}, if specified, gives the name of the directory to which
9823 the output files will be written. If it is not specified, all files are
9824 written to the current directory.
9825
9826 For example, given a
9827 file called @file{hellofiles} containing
9828
9829 @smallexample @c ada
9830 @group
9831 @cartouche
9832 procedure hello;
9833
9834 with Text_IO; use Text_IO;
9835 procedure hello is
9836 begin
9837    Put_Line ("Hello");
9838 end hello;
9839 @end cartouche
9840 @end group
9841 @end smallexample
9842
9843 @noindent
9844 the command
9845
9846 @smallexample
9847 $ gnatchop ^hellofiles^HELLOFILES.^
9848 @end smallexample
9849
9850 @noindent
9851 generates two files in the current directory, one called
9852 @file{hello.ads} containing the single line that is the procedure spec,
9853 and the other called @file{hello.adb} containing the remaining text. The
9854 original file is not affected. The generated files can be compiled in
9855 the normal manner.
9856
9857 @noindent
9858 When gnatchop is invoked on a file that is empty or that contains only empty
9859 lines and/or comments, gnatchop will not fail, but will not produce any
9860 new sources.
9861
9862 For example, given a
9863 file called @file{toto.txt} containing
9864
9865 @smallexample @c ada
9866 @group
9867 @cartouche
9868 --  Just a comment
9869 @end cartouche
9870 @end group
9871 @end smallexample
9872
9873 @noindent
9874 the command
9875
9876 @smallexample
9877 $ gnatchop ^toto.txt^TOT.TXT^
9878 @end smallexample
9879
9880 @noindent
9881 will not produce any new file and will result in the following warnings:
9882
9883 @smallexample
9884 toto.txt:1:01: warning: empty file, contains no compilation units
9885 no compilation units found
9886 no source files written
9887 @end smallexample
9888
9889 @node Switches for gnatchop
9890 @section Switches for @code{gnatchop}
9891
9892 @noindent
9893 @command{gnatchop} recognizes the following switches:
9894
9895 @table @option
9896 @c !sort!
9897
9898 @item ^-c^/COMPILATION^
9899 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9900 Causes @code{gnatchop} to operate in compilation mode, in which
9901 configuration pragmas are handled according to strict RM rules. See
9902 previous section for a full description of this mode.
9903
9904 @ifclear vms
9905 @item -gnatxxx
9906 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9907 used to parse the given file. Not all @code{xxx} options make sense,
9908 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9909 process a source file that uses Latin-2 coding for identifiers.
9910 @end ifclear
9911
9912 @item ^-h^/HELP^
9913 Causes @code{gnatchop} to generate a brief help summary to the standard
9914 output file showing usage information.
9915
9916 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9917 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9918 Limit generated file names to the specified number @code{mm}
9919 of characters.
9920 This is useful if the
9921 resulting set of files is required to be interoperable with systems
9922 which limit the length of file names.
9923 @ifset vms
9924 If no value is given, or
9925 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9926 a default of 39, suitable for OpenVMS Alpha
9927 Systems, is assumed
9928 @end ifset
9929 @ifclear vms
9930 No space is allowed between the @option{-k} and the numeric value. The numeric
9931 value may be omitted in which case a default of @option{-k8},
9932 suitable for use
9933 with DOS-like file systems, is used. If no @option{-k} switch
9934 is present then
9935 there is no limit on the length of file names.
9936 @end ifclear
9937
9938 @item ^-p^/PRESERVE^
9939 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9940 Causes the file ^modification^creation^ time stamp of the input file to be
9941 preserved and used for the time stamp of the output file(s). This may be
9942 useful for preserving coherency of time stamps in an environment where
9943 @code{gnatchop} is used as part of a standard build process.
9944
9945 @item ^-q^/QUIET^
9946 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9947 Causes output of informational messages indicating the set of generated
9948 files to be suppressed. Warnings and error messages are unaffected.
9949
9950 @item ^-r^/REFERENCE^
9951 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9952 @findex Source_Reference
9953 Generate @code{Source_Reference} pragmas. Use this switch if the output
9954 files are regarded as temporary and development is to be done in terms
9955 of the original unchopped file. This switch causes
9956 @code{Source_Reference} pragmas to be inserted into each of the
9957 generated files to refers back to the original file name and line number.
9958 The result is that all error messages refer back to the original
9959 unchopped file.
9960 In addition, the debugging information placed into the object file (when
9961 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
9962 specified)
9963 also refers back to this original file so that tools like profilers and
9964 debuggers will give information in terms of the original unchopped file.
9965
9966 If the original file to be chopped itself contains
9967 a @code{Source_Reference}
9968 pragma referencing a third file, then gnatchop respects
9969 this pragma, and the generated @code{Source_Reference} pragmas
9970 in the chopped file refer to the original file, with appropriate
9971 line numbers. This is particularly useful when @code{gnatchop}
9972 is used in conjunction with @code{gnatprep} to compile files that
9973 contain preprocessing statements and multiple units.
9974
9975 @item ^-v^/VERBOSE^
9976 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9977 Causes @code{gnatchop} to operate in verbose mode. The version
9978 number and copyright notice are output, as well as exact copies of
9979 the gnat1 commands spawned to obtain the chop control information.
9980
9981 @item ^-w^/OVERWRITE^
9982 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9983 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9984 fatal error if there is already a file with the same name as a
9985 file it would otherwise output, in other words if the files to be
9986 chopped contain duplicated units. This switch bypasses this
9987 check, and causes all but the last instance of such duplicated
9988 units to be skipped.
9989
9990 @ifclear vms
9991 @item --GCC=xxxx
9992 @cindex @option{--GCC=} (@code{gnatchop})
9993 Specify the path of the GNAT parser to be used. When this switch is used,
9994 no attempt is made to add the prefix to the GNAT parser executable.
9995 @end ifclear
9996 @end table
9997
9998 @node Examples of gnatchop Usage
9999 @section Examples of @code{gnatchop} Usage
10000
10001 @table @code
10002 @ifset vms
10003 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10004 @end ifset
10005 @ifclear vms
10006 @item gnatchop -w hello_s.ada prerelease/files
10007 @end ifclear
10008
10009 Chops the source file @file{hello_s.ada}. The output files will be
10010 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10011 overwriting any
10012 files with matching names in that directory (no files in the current
10013 directory are modified).
10014
10015 @item gnatchop ^archive^ARCHIVE.^
10016 Chops the source file @file{^archive^ARCHIVE.^}
10017 into the current directory. One
10018 useful application of @code{gnatchop} is in sending sets of sources
10019 around, for example in email messages. The required sources are simply
10020 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10021 command), and then
10022 @code{gnatchop} is used at the other end to reconstitute the original
10023 file names.
10024
10025 @item gnatchop file1 file2 file3 direc
10026 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10027 the resulting files in the directory @file{direc}. Note that if any units
10028 occur more than once anywhere within this set of files, an error message
10029 is generated, and no files are written. To override this check, use the
10030 @option{^-w^/OVERWRITE^} switch,
10031 in which case the last occurrence in the last file will
10032 be the one that is output, and earlier duplicate occurrences for a given
10033 unit will be skipped.
10034 @end table
10035
10036 @node Configuration Pragmas
10037 @chapter Configuration Pragmas
10038 @cindex Configuration pragmas
10039 @cindex Pragmas, configuration
10040
10041 @noindent
10042 In Ada 95, configuration pragmas include those pragmas described as
10043 such in the Ada 95 Reference Manual, as well as
10044 implementation-dependent pragmas that are configuration pragmas. See the
10045 individual descriptions of pragmas in the GNAT Reference Manual for
10046 details on these additional GNAT-specific configuration pragmas. Most
10047 notably, the pragma @code{Source_File_Name}, which allows
10048 specifying non-default names for source files, is a configuration
10049 pragma. The following is a complete list of configuration pragmas
10050 recognized by @code{GNAT}:
10051
10052 @smallexample
10053    Ada_83
10054    Ada_95
10055    Ada_05
10056    C_Pass_By_Copy
10057    Component_Alignment
10058    Detect_Blocking
10059    Discard_Names
10060    Elaboration_Checks
10061    Eliminate
10062    Extend_System
10063    Extensions_Allowed
10064    External_Name_Casing
10065    Float_Representation
10066    Initialize_Scalars
10067    License
10068    Locking_Policy
10069    Long_Float
10070    Normalize_Scalars
10071    Polling
10072    Profile
10073    Profile_Warnings
10074    Propagate_Exceptions
10075    Queuing_Policy
10076    Ravenscar
10077    Restricted_Run_Time
10078    Restrictions
10079    Restrictions_Warnings
10080    Reviewable
10081    Source_File_Name
10082    Style_Checks
10083    Suppress
10084    Task_Dispatching_Policy
10085    Universal_Data
10086    Unsuppress
10087    Use_VADS_Size
10088    Warnings
10089    Validity_Checks
10090 @end smallexample
10091
10092 @menu
10093 * Handling of Configuration Pragmas::
10094 * The Configuration Pragmas Files::
10095 @end menu
10096
10097 @node Handling of Configuration Pragmas
10098 @section Handling of Configuration Pragmas
10099
10100 Configuration pragmas may either appear at the start of a compilation
10101 unit, in which case they apply only to that unit, or they may apply to
10102 all compilations performed in a given compilation environment.
10103
10104 GNAT also provides the @code{gnatchop} utility to provide an automatic
10105 way to handle configuration pragmas following the semantics for
10106 compilations (that is, files with multiple units), described in the RM.
10107 See @ref{Operating gnatchop in Compilation Mode} for details.
10108 However, for most purposes, it will be more convenient to edit the
10109 @file{gnat.adc} file that contains configuration pragmas directly,
10110 as described in the following section.
10111
10112 @node The Configuration Pragmas Files
10113 @section The Configuration Pragmas Files
10114 @cindex @file{gnat.adc}
10115
10116 @noindent
10117 In GNAT a compilation environment is defined by the current
10118 directory at the time that a compile command is given. This current
10119 directory is searched for a file whose name is @file{gnat.adc}. If
10120 this file is present, it is expected to contain one or more
10121 configuration pragmas that will be applied to the current compilation.
10122 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10123 considered.
10124
10125 Configuration pragmas may be entered into the @file{gnat.adc} file
10126 either by running @code{gnatchop} on a source file that consists only of
10127 configuration pragmas, or more conveniently  by
10128 direct editing of the @file{gnat.adc} file, which is a standard format
10129 source file.
10130
10131 In addition to @file{gnat.adc}, one additional file containing configuration
10132 pragmas may be applied to the current compilation using the switch
10133 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10134 contains only configuration pragmas. These configuration pragmas are
10135 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10136 is present and switch @option{-gnatA} is not used).
10137
10138 It is allowed to specify several switches @option{-gnatec}, however only
10139 the last one on the command line will be taken into account.
10140
10141 If you are using project file, a separate mechanism is provided using
10142 project attributes, see @ref{Specifying Configuration Pragmas} for more
10143 details.
10144
10145 @ifset vms
10146 Of special interest to GNAT OpenVMS Alpha is the following
10147 configuration pragma:
10148
10149 @smallexample @c ada
10150 @cartouche
10151 pragma Extend_System (Aux_DEC);
10152 @end cartouche
10153 @end smallexample
10154
10155 @noindent
10156 In the presence of this pragma, GNAT adds to the definition of the
10157 predefined package SYSTEM all the additional types and subprograms that are
10158 defined in DEC Ada. See @ref{Compatibility with DEC Ada} for details.
10159 @end ifset
10160
10161 @node Handling Arbitrary File Naming Conventions Using gnatname
10162 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10163 @cindex Arbitrary File Naming Conventions
10164
10165 @menu
10166 * Arbitrary File Naming Conventions::
10167 * Running gnatname::
10168 * Switches for gnatname::
10169 * Examples of gnatname Usage::
10170 @end menu
10171
10172 @node Arbitrary File Naming Conventions
10173 @section Arbitrary File Naming Conventions
10174
10175 @noindent
10176 The GNAT compiler must be able to know the source file name of a compilation
10177 unit.  When using the standard GNAT default file naming conventions
10178 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10179 does not need additional information.
10180
10181 @noindent
10182 When the source file names do not follow the standard GNAT default file naming
10183 conventions, the GNAT compiler must be given additional information through
10184 a configuration pragmas file (@pxref{Configuration Pragmas})
10185 or a project file.
10186 When the non standard file naming conventions are well-defined,
10187 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10188 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10189 if the file naming conventions are irregular or arbitrary, a number
10190 of pragma @code{Source_File_Name} for individual compilation units
10191 must be defined.
10192 To help maintain the correspondence between compilation unit names and
10193 source file names within the compiler,
10194 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10195 set of files.
10196
10197 @node Running gnatname
10198 @section Running @code{gnatname}
10199
10200 @noindent
10201 The usual form of the @code{gnatname} command is
10202
10203 @smallexample
10204 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10205 @end smallexample
10206
10207 @noindent
10208 All of the arguments are optional. If invoked without any argument,
10209 @code{gnatname} will display its usage.
10210
10211 @noindent
10212 When used with at least one naming pattern, @code{gnatname} will attempt to
10213 find all the compilation units in files that follow at least one of the
10214 naming patterns. To find these compilation units,
10215 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10216 regular files.
10217
10218 @noindent
10219 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10220 Each Naming Pattern is enclosed between double quotes.
10221 A Naming Pattern is a regular expression similar to the wildcard patterns
10222 used in file names by the Unix shells or the DOS prompt.
10223
10224 @noindent
10225 Examples of Naming Patterns are
10226
10227 @smallexample
10228    "*.[12].ada"
10229    "*.ad[sb]*"
10230    "body_*"    "spec_*"
10231 @end smallexample
10232
10233 @noindent
10234 For a more complete description of the syntax of Naming Patterns,
10235 see the second kind of regular expressions described in @file{g-regexp.ads}
10236 (the ``Glob'' regular expressions).
10237
10238 @noindent
10239 When invoked with no switches, @code{gnatname} will create a configuration
10240 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10241 @code{Source_File_Name} for each file that contains a valid Ada unit.
10242
10243 @node Switches for gnatname
10244 @section Switches for @code{gnatname}
10245
10246 @noindent
10247 Switches for @code{gnatname} must precede any specified Naming Pattern.
10248
10249 @noindent
10250 You may specify any of the following switches to @code{gnatname}:
10251
10252 @table @option
10253 @c !sort!
10254
10255 @item ^-c^/CONFIG_FILE=^@file{file}
10256 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10257 Create a configuration pragmas file @file{file} (instead of the default
10258 @file{gnat.adc}).
10259 @ifclear vms
10260 There may be zero, one or more space between @option{-c} and
10261 @file{file}.
10262 @end ifclear
10263 @file{file} may include directory information. @file{file} must be
10264 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10265 When a switch @option{^-c^/CONFIG_FILE^} is
10266 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10267
10268 @item ^-d^/SOURCE_DIRS=^@file{dir}
10269 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10270 Look for source files in directory @file{dir}. There may be zero, one or more
10271 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10272 When a switch @option{^-d^/SOURCE_DIRS^}
10273 is specified, the current working directory will not be searched for source
10274 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10275 or @option{^-D^/DIR_FILES^} switch.
10276 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10277 If @file{dir} is a relative path, it is relative to the directory of
10278 the configuration pragmas file specified with switch
10279 @option{^-c^/CONFIG_FILE^},
10280 or to the directory of the project file specified with switch
10281 @option{^-P^/PROJECT_FILE^} or,
10282 if neither switch @option{^-c^/CONFIG_FILE^}
10283 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10284 current working directory. The directory
10285 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10286
10287 @item ^-D^/DIRS_FILE=^@file{file}
10288 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10289 Look for source files in all directories listed in text file @file{file}.
10290 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10291 and @file{file}.
10292 @file{file} must be an existing, readable text file.
10293 Each non empty line in @file{file} must be a directory.
10294 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10295 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10296 @file{file}.
10297
10298 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10299 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10300 Foreign patterns. Using this switch, it is possible to add sources of languages
10301 other than Ada to the list of sources of a project file.
10302 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10303 For example,
10304 @smallexample
10305 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10306 @end smallexample
10307 @noindent
10308 will look for Ada units in all files with the @file{.ada} extension,
10309 and will add to the list of file for project @file{prj.gpr} the C files
10310 with extension ".^c^C^".
10311
10312 @item ^-h^/HELP^
10313 @cindex @option{^-h^/HELP^} (@code{gnatname})
10314 Output usage (help) information. The output is written to @file{stdout}.
10315
10316 @item ^-P^/PROJECT_FILE=^@file{proj}
10317 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10318 Create or update project file @file{proj}. There may be zero, one or more space
10319 between @option{-P} and @file{proj}. @file{proj} may include directory
10320 information. @file{proj} must be writable.
10321 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10322 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10323 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10324
10325 @item ^-v^/VERBOSE^
10326 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10327 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10328 This includes name of the file written, the name of the directories to search
10329 and, for each file in those directories whose name matches at least one of
10330 the Naming Patterns, an indication of whether the file contains a unit,
10331 and if so the name of the unit.
10332
10333 @item ^-v -v^/VERBOSE /VERBOSE^
10334 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10335 Very Verbose mode. In addition to the output produced in verbose mode,
10336 for each file in the searched directories whose name matches none of
10337 the Naming Patterns, an indication is given that there is no match.
10338
10339 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10340 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10341 Excluded patterns. Using this switch, it is possible to exclude some files
10342 that would match the name patterns. For example,
10343 @smallexample
10344 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10345 @end smallexample
10346 @noindent
10347 will look for Ada units in all files with the @file{.ada} extension,
10348 except those whose names end with @file{_nt.ada}.
10349
10350 @end table
10351
10352 @node Examples of gnatname Usage
10353 @section Examples of @code{gnatname} Usage
10354
10355 @ifset vms
10356 @smallexample
10357 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10358 @end smallexample
10359 @end ifset
10360
10361 @ifclear vms
10362 @smallexample
10363 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10364 @end smallexample
10365 @end ifclear
10366
10367 @noindent
10368 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10369 and be writable. In addition, the directory
10370 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10371 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10372
10373 @ifclear vms
10374 Note the optional spaces after @option{-c} and @option{-d}.
10375 @end ifclear
10376
10377 @smallexample
10378 @ifclear vms
10379 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10380   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10381 @end ifclear
10382 @ifset vms
10383 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10384   /EXCLUDED_PATTERN=*_nt_body.ada
10385   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10386   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10387 @end ifset
10388 @end smallexample
10389
10390 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10391 even in conjunction with one or several switches
10392 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10393 are used in this example.
10394
10395 @c *****************************************
10396 @c * G N A T  P r o j e c t  M a n a g e r *
10397 @c *****************************************
10398 @node GNAT Project Manager
10399 @chapter GNAT Project Manager
10400
10401 @menu
10402 * Introduction::
10403 * Examples of Project Files::
10404 * Project File Syntax::
10405 * Objects and Sources in Project Files::
10406 * Importing Projects::
10407 * Project Extension::
10408 * Project Hierarchy Extension::
10409 * External References in Project Files::
10410 * Packages in Project Files::
10411 * Variables from Imported Projects::
10412 * Naming Schemes::
10413 * Library Projects::
10414 * Stand-alone Library Projects::
10415 * Switches Related to Project Files::
10416 * Tools Supporting Project Files::
10417 * An Extended Example::
10418 * Project File Complete Syntax::
10419 @end menu
10420
10421 @c ****************
10422 @c * Introduction *
10423 @c ****************
10424
10425 @node Introduction
10426 @section Introduction
10427
10428 @noindent
10429 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10430 you to manage complex builds involving a number of source files, directories,
10431 and compilation options for different system configurations. In particular,
10432 project files allow you to specify:
10433 @itemize @bullet
10434 @item
10435 The directory or set of directories containing the source files, and/or the
10436 names of the specific source files themselves
10437 @item
10438 The directory in which the compiler's output
10439 (@file{ALI} files, object files, tree files) is to be placed
10440 @item
10441 The directory in which the executable programs is to be placed
10442 @item
10443 ^Switch^Switch^ settings for any of the project-enabled tools
10444 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10445 @code{gnatfind}); you can apply these settings either globally or to individual
10446 compilation units.
10447 @item
10448 The source files containing the main subprogram(s) to be built
10449 @item
10450 The source programming language(s) (currently Ada and/or C)
10451 @item
10452 Source file naming conventions; you can specify these either globally or for
10453 individual compilation units
10454 @end itemize
10455
10456 @menu
10457 * Project Files::
10458 @end menu
10459
10460 @node Project Files
10461 @subsection Project Files
10462
10463 @noindent
10464 Project files are written in a syntax close to that of Ada, using  familiar
10465 notions such as packages, context clauses, declarations, default values,
10466 assignments, and inheritance. Finally, project files can be built
10467 hierarchically from other project files, simplifying complex system
10468 integration and project reuse.
10469
10470 A @dfn{project} is a specific set of values for various compilation properties.
10471 The settings for a given project are described by means of
10472 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10473 Property values in project files are either strings or lists of strings.
10474 Properties that are not explicitly set receive default values.  A project
10475 file may interrogate the values of @dfn{external variables} (user-defined
10476 command-line switches or environment variables), and it may specify property
10477 settings conditionally, based on the value of such variables.
10478
10479 In simple cases, a project's source files depend only on other source files
10480 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10481 used in
10482 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10483 the Project Manager also allows more sophisticated arrangements,
10484 where the source files in one project depend on source files in other
10485 projects:
10486 @itemize @bullet
10487 @item
10488 One project can @emph{import} other projects containing needed source files.
10489 @item
10490 You can organize GNAT projects in a hierarchy: a @emph{child} project
10491 can extend a @emph{parent} project, inheriting the parent's source files and
10492 optionally overriding any of them with alternative versions
10493 @end itemize
10494
10495 @noindent
10496 More generally, the Project Manager lets you structure large development
10497 efforts into hierarchical subsystems, where build decisions are delegated
10498 to the subsystem level, and thus different compilation environments
10499 (^switch^switch^ settings) used for different subsystems.
10500
10501 The Project Manager is invoked through the
10502 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10503 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10504 @ifclear vms
10505 There may be zero, one or more spaces between @option{-P} and
10506 @option{@emph{projectfile}}.
10507 @end ifclear
10508 If you want to define (on the command line) an external variable that is
10509 queried by the project file, you must use the
10510 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10511 The Project Manager parses and interprets the project file, and drives the
10512 invoked tool based on the project settings.
10513
10514 The Project Manager supports a wide range of development strategies,
10515 for systems of all sizes.  Here are some typical practices that are
10516 easily handled:
10517 @itemize @bullet
10518 @item
10519 Using a common set of source files, but generating object files in different
10520 directories via different ^switch^switch^ settings
10521 @item
10522 Using a mostly-shared set of source files, but with different versions of
10523 some unit or units
10524 @end itemize
10525
10526 @noindent
10527 The destination of an executable can be controlled inside a project file
10528 using the @option{^-o^-o^}
10529 ^switch^switch^.
10530 In the absence of such a ^switch^switch^ either inside
10531 the project file or on the command line, any executable files generated by
10532 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10533 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10534 in the object directory of the project.
10535
10536 You can use project files to achieve some of the effects of a source
10537 versioning system (for example, defining separate projects for
10538 the different sets of sources that comprise different releases) but the
10539 Project Manager is independent of any source configuration management tools
10540 that might be used by the developers.
10541
10542 The next section introduces the main features of GNAT's project facility
10543 through a sequence of examples; subsequent sections will present the syntax
10544 and semantics in more detail. A more formal description of the project
10545 facility appears in the GNAT Reference Manual.
10546
10547 @c *****************************
10548 @c * Examples of Project Files *
10549 @c *****************************
10550
10551 @node Examples of Project Files
10552 @section Examples of Project Files
10553 @noindent
10554 This section illustrates some of the typical uses of project files and
10555 explains their basic structure and behavior.
10556
10557 @menu
10558 * Common Sources with Different ^Switches^Switches^ and Directories::
10559 * Using External Variables::
10560 * Importing Other Projects::
10561 * Extending a Project::
10562 @end menu
10563
10564 @node Common Sources with Different ^Switches^Switches^ and Directories
10565 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10566
10567 @menu
10568 * Source Files::
10569 * Specifying the Object Directory::
10570 * Specifying the Exec Directory::
10571 * Project File Packages::
10572 * Specifying ^Switch^Switch^ Settings::
10573 * Main Subprograms::
10574 * Executable File Names::
10575 * Source File Naming Conventions::
10576 * Source Language(s)::
10577 @end menu
10578
10579 @noindent
10580 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10581 @file{proc.adb} are in the @file{/common} directory.  The file
10582 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10583 package @code{Pack}.  We want to compile these source files under two sets
10584 of ^switches^switches^:
10585 @itemize @bullet
10586 @item
10587 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10588 and the @option{^-gnata^-gnata^},
10589 @option{^-gnato^-gnato^},
10590 and @option{^-gnatE^-gnatE^} switches to the
10591 compiler; the compiler's output is to appear in @file{/common/debug}
10592 @item
10593 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10594 to the compiler; the compiler's output is to appear in @file{/common/release}
10595 @end itemize
10596
10597 @noindent
10598 The GNAT project files shown below, respectively @file{debug.gpr} and
10599 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10600
10601 Schematically:
10602 @smallexample
10603 @group
10604 ^/common^[COMMON]^
10605   debug.gpr
10606   release.gpr
10607   pack.ads
10608   pack.adb
10609   proc.adb
10610 @end group
10611 @group
10612 ^/common/debug^[COMMON.DEBUG]^
10613   proc.ali, proc.o
10614   pack.ali, pack.o
10615 @end group
10616 @group
10617 ^/common/release^[COMMON.RELEASE]^
10618   proc.ali, proc.o
10619   pack.ali, pack.o
10620 @end group
10621 @end smallexample
10622 Here are the corresponding project files:
10623
10624 @smallexample @c projectfile
10625 @group
10626 project Debug is
10627   for Object_Dir use "debug";
10628   for Main use ("proc");
10629
10630   package Builder is
10631     for ^Default_Switches^Default_Switches^ ("Ada")
10632         use ("^-g^-g^");
10633     for Executable ("proc.adb") use "proc1";
10634   end Builder;
10635 @end group
10636
10637 @group
10638   package Compiler is
10639     for ^Default_Switches^Default_Switches^ ("Ada")
10640        use ("-fstack-check",
10641             "^-gnata^-gnata^",
10642             "^-gnato^-gnato^",
10643             "^-gnatE^-gnatE^");
10644   end Compiler;
10645 end Debug;
10646 @end group
10647 @end smallexample
10648
10649 @smallexample @c projectfile
10650 @group
10651 project Release is
10652   for Object_Dir use "release";
10653   for Exec_Dir use ".";
10654   for Main use ("proc");
10655
10656   package Compiler is
10657     for ^Default_Switches^Default_Switches^ ("Ada")
10658         use ("^-O2^-O2^");
10659   end Compiler;
10660 end Release;
10661 @end group
10662 @end smallexample
10663
10664 @noindent
10665 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10666 insensitive), and analogously the project defined by @file{release.gpr} is
10667 @code{"Release"}.  For consistency the file should have the same name as the
10668 project, and the project file's extension should be @code{"gpr"}. These
10669 conventions are not required, but a warning is issued if they are not followed.
10670
10671 If the current directory is @file{^/temp^[TEMP]^}, then the command
10672 @smallexample
10673 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10674 @end smallexample
10675
10676 @noindent
10677 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10678 as well as the @code{^proc1^PROC1.EXE^} executable,
10679 using the ^switch^switch^ settings defined in the project file.
10680
10681 Likewise, the command
10682 @smallexample
10683 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10684 @end smallexample
10685
10686 @noindent
10687 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10688 and the @code{^proc^PROC.EXE^}
10689 executable in @file{^/common^[COMMON]^},
10690 using the ^switch^switch^ settings from the project file.
10691
10692 @node Source Files
10693 @unnumberedsubsubsec Source Files
10694
10695 @noindent
10696 If a project file does not explicitly specify a set of source directories or
10697 a set of source files, then by default the project's source files are the
10698 Ada source files in the project file directory.  Thus @file{pack.ads},
10699 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10700
10701 @node Specifying the Object Directory
10702 @unnumberedsubsubsec Specifying the Object Directory
10703
10704 @noindent
10705 Several project properties are modeled by Ada-style @emph{attributes};
10706 a property is defined by supplying the equivalent of an Ada attribute
10707 definition clause in the project file.
10708 A project's object directory is another such a property; the corresponding
10709 attribute is @code{Object_Dir}, and its value is also a string expression,
10710 specified either as absolute or relative. In the later case,
10711 it is relative to the project file directory. Thus the compiler's
10712 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10713 (for the @code{Debug} project)
10714 and to @file{^/common/release^[COMMON.RELEASE]^}
10715 (for the @code{Release} project).
10716 If @code{Object_Dir} is not specified, then the default is the project file
10717 directory itself.
10718
10719 @node Specifying the Exec Directory
10720 @unnumberedsubsubsec Specifying the Exec Directory
10721
10722 @noindent
10723 A project's exec directory is another property; the corresponding
10724 attribute is @code{Exec_Dir}, and its value is also a string expression,
10725 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10726 then the default is the object directory (which may also be the project file
10727 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10728 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10729 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10730 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10731
10732 @node Project File Packages
10733 @unnumberedsubsubsec Project File Packages
10734
10735 @noindent
10736 A GNAT tool that is integrated with the Project Manager is modeled by a
10737 corresponding package in the project file. In the example above,
10738 The @code{Debug} project defines the packages @code{Builder}
10739 (for @command{gnatmake}) and @code{Compiler};
10740 the @code{Release} project defines only the @code{Compiler} package.
10741
10742 The Ada-like package syntax is not to be taken literally.  Although packages in
10743 project files bear a surface resemblance to packages in Ada source code, the
10744 notation is simply a way to convey a grouping of properties for a named
10745 entity.  Indeed, the package names permitted in project files are restricted
10746 to a predefined set, corresponding to the project-aware tools, and the contents
10747 of packages are limited to a small set of constructs.
10748 The packages in the example above contain attribute definitions.
10749
10750 @node Specifying ^Switch^Switch^ Settings
10751 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10752
10753 @noindent
10754 ^Switch^Switch^ settings for a project-aware tool can be specified through
10755 attributes in the package that corresponds to the tool.
10756 The example above illustrates one of the relevant attributes,
10757 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10758 in both project files.
10759 Unlike simple attributes like @code{Source_Dirs},
10760 @code{^Default_Switches^Default_Switches^} is
10761 known as an @emph{associative array}.  When you define this attribute, you must
10762 supply an ``index'' (a literal string), and the effect of the attribute
10763 definition is to set the value of the array at the specified index.
10764 For the @code{^Default_Switches^Default_Switches^} attribute,
10765 the index is a programming language (in our case, Ada),
10766 and the value specified (after @code{use}) must be a list
10767 of string expressions.
10768
10769 The attributes permitted in project files are restricted to a predefined set.
10770 Some may appear at project level, others in packages.
10771 For any attribute that is an associative array, the index must always be a
10772 literal string, but the restrictions on this string (e.g., a file name or a
10773 language name) depend on the individual attribute.
10774 Also depending on the attribute, its specified value will need to be either a
10775 string or a string list.
10776
10777 In the @code{Debug} project, we set the switches for two tools,
10778 @command{gnatmake} and the compiler, and thus we include the two corresponding
10779 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10780 attribute with index @code{"Ada"}.
10781 Note that the package corresponding to
10782 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10783 similar, but only includes the @code{Compiler} package.
10784
10785 In project @code{Debug} above, the ^switches^switches^ starting with
10786 @option{-gnat} that are specified in package @code{Compiler}
10787 could have been placed in package @code{Builder}, since @command{gnatmake}
10788 transmits all such ^switches^switches^ to the compiler.
10789
10790 @node Main Subprograms
10791 @unnumberedsubsubsec Main Subprograms
10792
10793 @noindent
10794 One of the specifiable properties of a project is a list of files that contain
10795 main subprograms.  This property is captured in the @code{Main} attribute,
10796 whose value is a list of strings.  If a project defines the @code{Main}
10797 attribute, it is not necessary to identify the main subprogram(s) when
10798 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
10799
10800 @node Executable File Names
10801 @unnumberedsubsubsec Executable File Names
10802
10803 @noindent
10804 By default, the executable file name corresponding to a main source is
10805 deduced from the main source file name. Through the attributes
10806 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10807 it is possible to change this default.
10808 In project @code{Debug} above, the executable file name
10809 for main source @file{^proc.adb^PROC.ADB^} is
10810 @file{^proc1^PROC1.EXE^}.
10811 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10812 of the the executable files, when no attribute @code{Executable} applies:
10813 its value replace the platform-specific executable suffix.
10814 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10815 specify a non default executable file name when several mains are built at once
10816 in a single @command{gnatmake} command.
10817
10818 @node Source File Naming Conventions
10819 @unnumberedsubsubsec Source File Naming Conventions
10820
10821 @noindent
10822 Since the project files above do not specify any source file naming
10823 conventions, the GNAT defaults are used.  The mechanism for defining source
10824 file naming conventions -- a package named @code{Naming} --
10825 is described below (@pxref{Naming Schemes}).
10826
10827 @node Source Language(s)
10828 @unnumberedsubsubsec Source Language(s)
10829
10830 @noindent
10831 Since the project files do not specify a @code{Languages} attribute, by
10832 default the GNAT tools assume that the language of the project file is Ada.
10833 More generally, a project can comprise source files
10834 in Ada, C, and/or other languages.
10835
10836 @node Using External Variables
10837 @subsection Using External Variables
10838
10839 @noindent
10840 Instead of supplying different project files for debug and release, we can
10841 define a single project file that queries an external variable (set either
10842 on the command line or via an ^environment variable^logical name^) in order to
10843 conditionally define the appropriate settings.  Again, assume that the
10844 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10845 located in directory @file{^/common^[COMMON]^}.  The following project file,
10846 @file{build.gpr}, queries the external variable named @code{STYLE} and
10847 defines an object directory and ^switch^switch^ settings based on whether
10848 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10849 the default is @code{"deb"}.
10850
10851 @smallexample @c projectfile
10852 @group
10853 project Build is
10854   for Main use ("proc");
10855
10856   type Style_Type is ("deb", "rel");
10857   Style : Style_Type := external ("STYLE", "deb");
10858
10859   case Style is
10860     when "deb" =>
10861       for Object_Dir use "debug";
10862
10863     when "rel" =>
10864       for Object_Dir use "release";
10865       for Exec_Dir use ".";
10866   end case;
10867 @end group
10868
10869 @group
10870   package Builder is
10871
10872     case Style is
10873       when "deb" =>
10874         for ^Default_Switches^Default_Switches^ ("Ada")
10875             use ("^-g^-g^");
10876         for Executable ("proc") use "proc1";
10877       when others =>
10878         null;
10879     end case;
10880
10881   end Builder;
10882 @end group
10883
10884 @group
10885   package Compiler is
10886
10887     case Style is
10888       when "deb" =>
10889         for ^Default_Switches^Default_Switches^ ("Ada")
10890             use ("^-gnata^-gnata^",
10891                  "^-gnato^-gnato^",
10892                  "^-gnatE^-gnatE^");
10893
10894       when "rel" =>
10895         for ^Default_Switches^Default_Switches^ ("Ada")
10896             use ("^-O2^-O2^");
10897     end case;
10898
10899   end Compiler;
10900
10901 end Build;
10902 @end group
10903 @end smallexample
10904
10905 @noindent
10906 @code{Style_Type} is an example of a @emph{string type}, which is the project
10907 file analog of an Ada enumeration type but whose components are string literals
10908 rather than identifiers.  @code{Style} is declared as a variable of this type.
10909
10910 The form @code{external("STYLE", "deb")} is known as an
10911 @emph{external reference}; its first argument is the name of an
10912 @emph{external variable}, and the second argument is a default value to be
10913 used if the external variable doesn't exist.  You can define an external
10914 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10915 or you can use ^an environment variable^a logical name^
10916 as an external variable.
10917
10918 Each @code{case} construct is expanded by the Project Manager based on the
10919 value of @code{Style}. Thus the command
10920 @ifclear vms
10921 @smallexample
10922 gnatmake -P/common/build.gpr -XSTYLE=deb
10923 @end smallexample
10924 @end ifclear
10925
10926 @ifset vms
10927 @smallexample
10928 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10929 @end smallexample
10930 @end ifset
10931
10932 @noindent
10933 is equivalent to the @command{gnatmake} invocation using the project file
10934 @file{debug.gpr} in the earlier example.  So is the command
10935 @smallexample
10936 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10937 @end smallexample
10938
10939 @noindent
10940 since @code{"deb"} is the default for @code{STYLE}.
10941
10942 Analogously,
10943
10944 @ifclear vms
10945 @smallexample
10946 gnatmake -P/common/build.gpr -XSTYLE=rel
10947 @end smallexample
10948 @end ifclear
10949
10950 @ifset vms
10951 @smallexample
10952 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10953 @end smallexample
10954 @end ifset
10955
10956 @noindent
10957 is equivalent to the @command{gnatmake} invocation using the project file
10958 @file{release.gpr} in the earlier example.
10959
10960 @node Importing Other Projects
10961 @subsection Importing Other Projects
10962
10963 @noindent
10964 A compilation unit in a source file in one project may depend on compilation
10965 units in source files in other projects.  To compile this unit under
10966 control of a project file, the
10967 dependent project must @emph{import} the projects containing the needed source
10968 files.
10969 This effect is obtained using syntax similar to an Ada @code{with} clause,
10970 but where @code{with}ed entities are strings that denote project files.
10971
10972 As an example, suppose that the two projects @code{GUI_Proj} and
10973 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10974 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10975 and @file{^/comm^[COMM]^}, respectively.
10976 Suppose that the source files for @code{GUI_Proj} are
10977 @file{gui.ads} and @file{gui.adb}, and that the source files for
10978 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10979 files is located in its respective project file directory.  Schematically:
10980
10981 @smallexample
10982 @group
10983 ^/gui^[GUI]^
10984   gui_proj.gpr
10985   gui.ads
10986   gui.adb
10987 @end group
10988
10989 @group
10990 ^/comm^[COMM]^
10991   comm_proj.gpr
10992   comm.ads
10993   comm.adb
10994 @end group
10995 @end smallexample
10996
10997 @noindent
10998 We want to develop an application in directory @file{^/app^[APP]^} that
10999 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11000 the corresponding project files (e.g. the ^switch^switch^ settings
11001 and object directory).
11002 Skeletal code for a main procedure might be something like the following:
11003
11004 @smallexample @c ada
11005 @group
11006 with GUI, Comm;
11007 procedure App_Main is
11008    ...
11009 begin
11010    ...
11011 end App_Main;
11012 @end group
11013 @end smallexample
11014
11015 @noindent
11016 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11017 effect:
11018
11019 @smallexample @c projectfile
11020 @group
11021 with "/gui/gui_proj", "/comm/comm_proj";
11022 project App_Proj is
11023    for Main use ("app_main");
11024 end App_Proj;
11025 @end group
11026 @end smallexample
11027
11028 @noindent
11029 Building an executable is achieved through the command:
11030 @smallexample
11031 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11032 @end smallexample
11033 @noindent
11034 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11035 in the directory where @file{app_proj.gpr} resides.
11036
11037 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11038 (as illustrated above) the @code{with} clause can omit the extension.
11039
11040 Our example specified an absolute path for each imported project file.
11041 Alternatively, the directory name of an imported object can be omitted
11042 if either
11043 @itemize @bullet
11044 @item
11045 The imported project file is in the same directory as the importing project
11046 file, or
11047 @item
11048 You have defined ^an environment variable^a logical name^
11049 that includes the directory containing
11050 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11051 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11052 directory names separated by colons (semicolons on Windows).
11053 @end itemize
11054
11055 @noindent
11056 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11057 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11058 as follows:
11059
11060 @smallexample @c projectfile
11061 @group
11062 with "gui_proj", "comm_proj";
11063 project App_Proj is
11064    for Main use ("app_main");
11065 end App_Proj;
11066 @end group
11067 @end smallexample
11068
11069 @noindent
11070 Importing other projects can create ambiguities.
11071 For example, the same unit might be present in different imported projects, or
11072 it might be present in both the importing project and in an imported project.
11073 Both of these conditions are errors.  Note that in the current version of
11074 the Project Manager, it is illegal to have an ambiguous unit even if the
11075 unit is never referenced by the importing project.  This restriction may be
11076 relaxed in a future release.
11077
11078 @node Extending a Project
11079 @subsection Extending a Project
11080
11081 @noindent
11082 In large software systems it is common to have multiple
11083 implementations of a common interface; in Ada terms, multiple versions of a
11084 package body for the same specification.  For example, one implementation
11085 might be safe for use in tasking programs, while another might only be used
11086 in sequential applications.  This can be modeled in GNAT using the concept
11087 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11088 another project (the ``parent'') then by default all source files of the
11089 parent project are inherited by the child, but the child project can
11090 override any of the parent's source files with new versions, and can also
11091 add new files.  This facility is the project analog of a type extension in
11092 Object-Oriented Programming.  Project hierarchies are permitted (a child
11093 project may be the parent of yet another project), and a project that
11094 inherits one project can also import other projects.
11095
11096 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11097 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11098 @file{pack.adb}, and @file{proc.adb}:
11099
11100 @smallexample
11101 @group
11102 ^/seq^[SEQ]^
11103   pack.ads
11104   pack.adb
11105   proc.adb
11106   seq_proj.gpr
11107 @end group
11108 @end smallexample
11109
11110 @noindent
11111 Note that the project file can simply be empty (that is, no attribute or
11112 package is defined):
11113
11114 @smallexample @c projectfile
11115 @group
11116 project Seq_Proj is
11117 end Seq_Proj;
11118 @end group
11119 @end smallexample
11120
11121 @noindent
11122 implying that its source files are all the Ada source files in the project
11123 directory.
11124
11125 Suppose we want to supply an alternate version of @file{pack.adb}, in
11126 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11127 @file{pack.ads} and @file{proc.adb}.  We can define a project
11128 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11129
11130 @smallexample
11131 @group
11132 ^/tasking^[TASKING]^
11133   pack.adb
11134   tasking_proj.gpr
11135 @end group
11136
11137 @group
11138 project Tasking_Proj extends "/seq/seq_proj" is
11139 end Tasking_Proj;
11140 @end group
11141 @end smallexample
11142
11143 @noindent
11144 The version of @file{pack.adb} used in a build depends on which project file
11145 is specified.
11146
11147 Note that we could have obtained the desired behavior using project import
11148 rather than project inheritance; a @code{base} project would contain the
11149 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11150 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11151 would import @code{base} and add a different version of @file{pack.adb}.  The
11152 choice depends on whether other sources in the original project need to be
11153 overridden.  If they do, then project extension is necessary, otherwise,
11154 importing is sufficient.
11155
11156 @noindent
11157 In a project file that extends another project file, it is possible to
11158 indicate that an inherited source is not part of the sources of the extending
11159 project. This is necessary sometimes when a package spec has been overloaded
11160 and no longer requires a body: in this case, it is necessary to indicate that
11161 the inherited body is not part of the sources of the project, otherwise there
11162 will be a compilation error when compiling the spec.
11163
11164 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11165 Its value is a string list: a list of file names.
11166
11167 @smallexample @c @projectfile
11168 project B extends "a" is
11169    for Source_Files use ("pkg.ads");
11170    --  New spec of Pkg does not need a completion
11171    for Locally_Removed_Files use ("pkg.adb");
11172 end B;
11173 @end smallexample
11174
11175 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11176 is still needed: if it is possible to build using @command{gnatmake} when such
11177 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11178 it is possible to remove the source completely from a system that includes
11179 project P.
11180
11181 @c ***********************
11182 @c * Project File Syntax *
11183 @c ***********************
11184
11185 @node Project File Syntax
11186 @section Project File Syntax
11187
11188 @menu
11189 * Basic Syntax::
11190 * Packages::
11191 * Expressions::
11192 * String Types::
11193 * Variables::
11194 * Attributes::
11195 * Associative Array Attributes::
11196 * case Constructions::
11197 @end menu
11198
11199 @noindent
11200 This section describes the structure of project files.
11201
11202 A project may be an @emph{independent project}, entirely defined by a single
11203 project file. Any Ada source file in an independent project depends only
11204 on the predefined library and other Ada source files in the same project.
11205
11206 @noindent
11207 A project may also @dfn{depend on} other projects, in either or both of
11208 the following ways:
11209 @itemize @bullet
11210 @item It may import any number of projects
11211 @item It may extend at most one other project
11212 @end itemize
11213
11214 @noindent
11215 The dependence relation is a directed acyclic graph (the subgraph reflecting
11216 the ``extends'' relation is a tree).
11217
11218 A project's @dfn{immediate sources} are the source files directly defined by
11219 that project, either implicitly by residing in the project file's directory,
11220 or explicitly through any of the source-related attributes described below.
11221 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11222 of @var{proj} together with the immediate sources (unless overridden) of any
11223 project on which @var{proj} depends (either directly or indirectly).
11224
11225 @node Basic Syntax
11226 @subsection Basic Syntax
11227
11228 @noindent
11229 As seen in the earlier examples, project files have an Ada-like syntax.
11230 The minimal project file is:
11231 @smallexample @c projectfile
11232 @group
11233 project Empty is
11234
11235 end Empty;
11236 @end group
11237 @end smallexample
11238
11239 @noindent
11240 The identifier @code{Empty} is the name of the project.
11241 This project name must be present after the reserved
11242 word @code{end} at the end of the project file, followed by a semi-colon.
11243
11244 Any name in a project file, such as the project name or a variable name,
11245 has the same syntax as an Ada identifier.
11246
11247 The reserved words of project files are the Ada reserved words plus
11248 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11249 reserved words currently used in project file syntax are:
11250
11251 @itemize @bullet
11252 @item
11253 @code{case}
11254 @item
11255 @code{end}
11256 @item
11257 @code{for}
11258 @item
11259 @code{is}
11260 @item
11261 @code{others}
11262 @item
11263 @code{package}
11264 @item
11265 @code{renames}
11266 @item
11267 @code{type}
11268 @item
11269 @code{use}
11270 @item
11271 @code{when}
11272 @item
11273 @code{with}
11274 @end itemize
11275
11276 @noindent
11277 Comments in project files have the same syntax as in Ada, two consecutives
11278 hyphens through the end of the line.
11279
11280 @node Packages
11281 @subsection Packages
11282
11283 @noindent
11284 A project file may contain @emph{packages}. The name of a package must be one
11285 of the identifiers from the following list. A package
11286 with a given name may only appear once in a project file. Package names are
11287 case insensitive. The following package names are legal:
11288
11289 @itemize @bullet
11290 @item
11291 @code{Naming}
11292 @item
11293 @code{Builder}
11294 @item
11295 @code{Compiler}
11296 @item
11297 @code{Binder}
11298 @item
11299 @code{Linker}
11300 @item
11301 @code{Finder}
11302 @item
11303 @code{Cross_Reference}
11304 @item
11305 @code{Eliminate}
11306 @item
11307 @code{Pretty_Printer}
11308 @item
11309 @code{Metrics}
11310 @item
11311 @code{gnatls}
11312 @item
11313 @code{gnatstub}
11314 @item
11315 @code{IDE}
11316 @item
11317 @code{Language_Processing}
11318 @end itemize
11319
11320 @noindent
11321 In its simplest form, a package may be empty:
11322
11323 @smallexample @c projectfile
11324 @group
11325 project Simple is
11326   package Builder is
11327   end Builder;
11328 end Simple;
11329 @end group
11330 @end smallexample
11331
11332 @noindent
11333 A package may contain @emph{attribute declarations},
11334 @emph{variable declarations} and @emph{case constructions}, as will be
11335 described below.
11336
11337 When there is ambiguity between a project name and a package name,
11338 the name always designates the project. To avoid possible confusion, it is
11339 always a good idea to avoid naming a project with one of the
11340 names allowed for packages or any name that starts with @code{gnat}.
11341
11342 @node Expressions
11343 @subsection Expressions
11344
11345 @noindent
11346 An @emph{expression} is either a @emph{string expression} or a
11347 @emph{string list expression}.
11348
11349 A @emph{string expression} is either a @emph{simple string expression} or a
11350 @emph{compound string expression}.
11351
11352 A @emph{simple string expression} is one of the following:
11353 @itemize @bullet
11354 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11355 @item A string-valued variable reference (@pxref{Variables})
11356 @item A string-valued attribute reference (@pxref{Attributes})
11357 @item An external reference (@pxref{External References in Project Files})
11358 @end itemize
11359
11360 @noindent
11361 A @emph{compound string expression} is a concatenation of string expressions,
11362 using the operator @code{"&"}
11363 @smallexample
11364        Path & "/" & File_Name & ".ads"
11365 @end smallexample
11366
11367 @noindent
11368 A @emph{string list expression} is either a
11369 @emph{simple string list expression} or a
11370 @emph{compound string list expression}.
11371
11372 A @emph{simple string list expression} is one of the following:
11373 @itemize @bullet
11374 @item A parenthesized list of zero or more string expressions,
11375 separated by commas
11376 @smallexample
11377    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11378    Empty_List := ();
11379 @end smallexample
11380 @item A string list-valued variable reference
11381 @item A string list-valued attribute reference
11382 @end itemize
11383
11384 @noindent
11385 A @emph{compound string list expression} is the concatenation (using
11386 @code{"&"}) of a simple string list expression and an expression.  Note that
11387 each term in a compound string list expression, except the first, may be
11388 either a string expression or a string list expression.
11389
11390 @smallexample @c projectfile
11391 @group
11392    File_Name_List := () & File_Name; --  One string in this list
11393    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11394    --  Two strings
11395    Big_List := File_Name_List & Extended_File_Name_List;
11396    --  Concatenation of two string lists: three strings
11397    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11398    --  Illegal: must start with a string list
11399 @end group
11400 @end smallexample
11401
11402 @node String Types
11403 @subsection String Types
11404
11405 @noindent
11406 A @emph{string type declaration} introduces a discrete set of string literals.
11407 If a string variable is declared to have this type, its value
11408 is restricted to the given set of literals.
11409
11410 Here is an example of a string type declaration:
11411
11412 @smallexample @c projectfile
11413    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11414 @end smallexample
11415
11416 @noindent
11417 Variables of a string type are called @emph{typed variables}; all other
11418 variables are called @emph{untyped variables}. Typed variables are
11419 particularly useful in @code{case} constructions, to support conditional
11420 attribute declarations.
11421 (@pxref{case Constructions}).
11422
11423 The string literals in the list are case sensitive and must all be different.
11424 They may include any graphic characters allowed in Ada, including spaces.
11425
11426 A string type may only be declared at the project level, not inside a package.
11427
11428 A string type may be referenced by its name if it has been declared in the same
11429 project file, or by an expanded name whose prefix is the name of the project
11430 in which it is declared.
11431
11432 @node Variables
11433 @subsection Variables
11434
11435 @noindent
11436 A variable may be declared at the project file level, or within a package.
11437 Here are some examples of variable declarations:
11438
11439 @smallexample @c projectfile
11440 @group
11441    This_OS : OS := external ("OS"); --  a typed variable declaration
11442    That_OS := "GNU/Linux";          --  an untyped variable declaration
11443 @end group
11444 @end smallexample
11445
11446 @noindent
11447 The syntax of a @emph{typed variable declaration} is identical to the Ada
11448 syntax for an object declaration. By contrast, the syntax of an untyped
11449 variable declaration is identical to an Ada assignment statement. In fact,
11450 variable declarations in project files have some of the characteristics of
11451 an assignment, in that successive declarations for the same variable are
11452 allowed. Untyped variable declarations do establish the expected kind of the
11453 variable (string or string list), and successive declarations for it must
11454 respect the initial kind.
11455
11456 @noindent
11457 A string variable declaration (typed or untyped) declares a variable
11458 whose value is a string. This variable may be used as a string expression.
11459 @smallexample @c projectfile
11460    File_Name       := "readme.txt";
11461    Saved_File_Name := File_Name & ".saved";
11462 @end smallexample
11463
11464 @noindent
11465 A string list variable declaration declares a variable whose value is a list
11466 of strings. The list may contain any number (zero or more) of strings.
11467
11468 @smallexample @c projectfile
11469    Empty_List := ();
11470    List_With_One_Element := ("^-gnaty^-gnaty^");
11471    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11472    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11473                  "pack2.ada", "util_.ada", "util.ada");
11474 @end smallexample
11475
11476 @noindent
11477 The same typed variable may not be declared more than once at project level,
11478 and it may not be declared more than once in any package; it is in effect
11479 a constant.
11480
11481 The same untyped variable may be declared several times. Declarations are
11482 elaborated in the order in which they appear, so  the new value replaces
11483 the old one, and any subsequent reference to the variable uses the new value.
11484 However, as noted above, if a variable has been declared as a string, all
11485 subsequent
11486 declarations must give it a string value. Similarly, if a variable has
11487 been declared as a string list, all subsequent declarations
11488 must give it a string list value.
11489
11490 A @emph{variable reference} may take several forms:
11491
11492 @itemize @bullet
11493 @item The simple variable name, for a variable in the current package (if any)
11494 or in the current project
11495 @item An expanded name, whose prefix is a context name.
11496 @end itemize
11497
11498 @noindent
11499 A @emph{context} may be one of the following:
11500
11501 @itemize @bullet
11502 @item The name of an existing package in the current project
11503 @item The name of an imported project of the current project
11504 @item The name of an ancestor project (i.e., a project extended by the current
11505 project, either directly or indirectly)
11506 @item An expanded name whose prefix is an imported/parent project name, and
11507 whose selector is a package name in that project.
11508 @end itemize
11509
11510 @noindent
11511 A variable reference may be used in an expression.
11512
11513 @node Attributes
11514 @subsection Attributes
11515
11516 @noindent
11517 A project (and its packages) may have @emph{attributes} that define
11518 the project's properties.  Some attributes have values that are strings;
11519 others have values that are string lists.
11520
11521 There are two categories of attributes: @emph{simple attributes}
11522 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11523
11524 Legal project attribute names, and attribute names for each legal package are
11525 listed below. Attributes names are case-insensitive.
11526
11527 The following attributes are defined on projects (all are simple attributes):
11528
11529 @multitable @columnfractions .4 .3
11530 @item @emph{Attribute Name}
11531 @tab @emph{Value}
11532 @item @code{Source_Files}
11533 @tab string list
11534 @item @code{Source_Dirs}
11535 @tab string list
11536 @item @code{Source_List_File}
11537 @tab string
11538 @item @code{Object_Dir}
11539 @tab string
11540 @item @code{Exec_Dir}
11541 @tab string
11542 @item @code{Locally_Removed_Files}
11543 @tab string list
11544 @item @code{Main}
11545 @tab string list
11546 @item @code{Languages}
11547 @tab string list
11548 @item @code{Main_Language}
11549 @tab string
11550 @item @code{Library_Dir}
11551 @tab string
11552 @item @code{Library_Name}
11553 @tab string
11554 @item @code{Library_Kind}
11555 @tab string
11556 @item @code{Library_Version}
11557 @tab string
11558 @item @code{Library_Interface}
11559 @tab string
11560 @item @code{Library_Auto_Init}
11561 @tab string
11562 @item @code{Library_Options}
11563 @tab string list
11564 @item @code{Library_GCC}
11565 @tab string
11566 @end multitable
11567
11568 @noindent
11569 The following attributes are defined for package  @code{Naming}
11570 (@pxref{Naming Schemes}):
11571
11572 @multitable @columnfractions .4 .2 .2 .2
11573 @item Attribute Name @tab Category @tab Index @tab Value
11574 @item @code{Spec_Suffix}
11575 @tab associative array
11576 @tab language name
11577 @tab string
11578 @item @code{Body_Suffix}
11579 @tab associative array
11580 @tab language name
11581 @tab string
11582 @item @code{Separate_Suffix}
11583 @tab simple attribute
11584 @tab n/a
11585 @tab string
11586 @item @code{Casing}
11587 @tab simple attribute
11588 @tab n/a
11589 @tab string
11590 @item @code{Dot_Replacement}
11591 @tab simple attribute
11592 @tab n/a
11593 @tab string
11594 @item @code{Spec}
11595 @tab associative array
11596 @tab Ada unit name
11597 @tab string
11598 @item @code{Body}
11599 @tab associative array
11600 @tab Ada unit name
11601 @tab string
11602 @item @code{Specification_Exceptions}
11603 @tab associative array
11604 @tab language name
11605 @tab string list
11606 @item @code{Implementation_Exceptions}
11607 @tab associative array
11608 @tab language name
11609 @tab string list
11610 @end multitable
11611
11612 @noindent
11613 The following attributes are defined for packages @code{Builder},
11614 @code{Compiler}, @code{Binder},
11615 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11616 (@pxref{^Switches^Switches^ and Project Files}).
11617
11618 @multitable @columnfractions .4 .2 .2 .2
11619 @item Attribute Name @tab Category @tab Index @tab Value
11620 @item @code{^Default_Switches^Default_Switches^}
11621 @tab associative array
11622 @tab language name
11623 @tab string list
11624 @item @code{^Switches^Switches^}
11625 @tab associative array
11626 @tab file name
11627 @tab string list
11628 @end multitable
11629
11630 @noindent
11631 In addition, package @code{Compiler} has a single string attribute
11632 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11633 string attribute @code{Global_Configuration_Pragmas}.
11634
11635 @noindent
11636 Each simple attribute has a default value: the empty string (for string-valued
11637 attributes) and the empty list (for string list-valued attributes).
11638
11639 An attribute declaration defines a new value for an attribute.
11640
11641 Examples of simple attribute declarations:
11642
11643 @smallexample @c projectfile
11644    for Object_Dir use "objects";
11645    for Source_Dirs use ("units", "test/drivers");
11646 @end smallexample
11647
11648 @noindent
11649 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11650 attribute definition clause in Ada.
11651
11652 Attributes references may be appear in expressions.
11653 The general form for such a reference is @code{<entity>'<attribute>}:
11654 Associative array attributes are functions. Associative
11655 array attribute references must have an argument that is a string literal.
11656
11657 Examples are:
11658
11659 @smallexample @c projectfile
11660   project'Object_Dir
11661   Naming'Dot_Replacement
11662   Imported_Project'Source_Dirs
11663   Imported_Project.Naming'Casing
11664   Builder'^Default_Switches^Default_Switches^("Ada")
11665 @end smallexample
11666
11667 @noindent
11668 The prefix of an attribute may be:
11669 @itemize @bullet
11670 @item @code{project} for an attribute of the current project
11671 @item The name of an existing package of the current project
11672 @item The name of an imported project
11673 @item The name of a parent project that is extended by the current project
11674 @item An expanded name whose prefix is imported/parent project name,
11675       and whose selector is a package name
11676 @end itemize
11677
11678 @noindent
11679 Example:
11680 @smallexample @c projectfile
11681 @group
11682    project Prj is
11683      for Source_Dirs use project'Source_Dirs & "units";
11684      for Source_Dirs use project'Source_Dirs & "test/drivers"
11685    end Prj;
11686 @end group
11687 @end smallexample
11688
11689 @noindent
11690 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11691 has the default value: an empty string list. After this declaration,
11692 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11693 After the second attribute declaration @code{Source_Dirs} is a string list of
11694 two elements: @code{"units"} and @code{"test/drivers"}.
11695
11696 Note: this example is for illustration only. In practice,
11697 the project file would contain only one attribute declaration:
11698
11699 @smallexample @c projectfile
11700    for Source_Dirs use ("units", "test/drivers");
11701 @end smallexample
11702
11703 @node Associative Array Attributes
11704 @subsection Associative Array Attributes
11705
11706 @noindent
11707 Some attributes are defined as @emph{associative arrays}. An associative
11708 array may be regarded as a function that takes a string as a parameter
11709 and delivers a string or string list value as its result.
11710
11711 Here are some examples of single associative array attribute associations:
11712
11713 @smallexample @c projectfile
11714    for Body ("main") use "Main.ada";
11715    for ^Switches^Switches^ ("main.ada")
11716        use ("^-v^-v^",
11717             "^-gnatv^-gnatv^");
11718    for ^Switches^Switches^ ("main.ada")
11719             use Builder'^Switches^Switches^ ("main.ada")
11720               & "^-g^-g^";
11721 @end smallexample
11722
11723 @noindent
11724 Like untyped variables and simple attributes, associative array attributes
11725 may be declared several times. Each declaration supplies a new value for the
11726 attribute, and replaces the previous setting.
11727
11728 @noindent
11729 An associative array attribute may be declared as a full associative array
11730 declaration, with the value of the same attribute in an imported or extended
11731 project.
11732
11733 @smallexample @c projectfile
11734    package Builder is
11735       for Default_Switches use Default.Builder'Default_Switches;
11736    end Builder;
11737 @end smallexample
11738
11739 @noindent
11740 In this example, @code{Default} must be either an project imported by the
11741 current project, or the project that the current project extends. If the
11742 attribute is in a package (in this case, in package @code{Builder}), the same
11743 package needs to be specified.
11744
11745 @noindent
11746 A full associative array declaration replaces any other declaration for the
11747 attribute, including other full associative array declaration. Single
11748 associative array associations may be declare after a full associative
11749 declaration, modifying the value for a single association of the attribute.
11750
11751 @node case Constructions
11752 @subsection @code{case} Constructions
11753
11754 @noindent
11755 A @code{case} construction is used in a project file to effect conditional
11756 behavior.
11757 Here is a typical example:
11758
11759 @smallexample @c projectfile
11760 @group
11761 project MyProj is
11762    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11763
11764    OS : OS_Type := external ("OS", "GNU/Linux");
11765 @end group
11766
11767 @group
11768    package Compiler is
11769      case OS is
11770        when "GNU/Linux" | "Unix" =>
11771          for ^Default_Switches^Default_Switches^ ("Ada")
11772              use ("^-gnath^-gnath^");
11773        when "NT" =>
11774          for ^Default_Switches^Default_Switches^ ("Ada")
11775              use ("^-gnatP^-gnatP^");
11776        when others =>
11777      end case;
11778    end Compiler;
11779 end MyProj;
11780 @end group
11781 @end smallexample
11782
11783 @noindent
11784 The syntax of a @code{case} construction is based on the Ada case statement
11785 (although there is no @code{null} construction for empty alternatives).
11786
11787 The case expression must a typed string variable.
11788 Each alternative comprises the reserved word @code{when}, either a list of
11789 literal strings separated by the @code{"|"} character or the reserved word
11790 @code{others},  and the @code{"=>"} token.
11791 Each literal string must belong to the string type that is the type of the
11792 case variable.
11793 An @code{others} alternative, if present, must occur last.
11794
11795 After each @code{=>}, there are zero or more constructions.  The only
11796 constructions allowed in a case construction are other case constructions and
11797 attribute declarations. String type declarations, variable declarations and
11798 package declarations are not allowed.
11799
11800 The value of the case variable is often given by an external reference
11801 (@pxref{External References in Project Files}).
11802
11803 @c ****************************************
11804 @c * Objects and Sources in Project Files *
11805 @c ****************************************
11806
11807 @node Objects and Sources in Project Files
11808 @section Objects and Sources in Project Files
11809
11810 @menu
11811 * Object Directory::
11812 * Exec Directory::
11813 * Source Directories::
11814 * Source File Names::
11815 @end menu
11816
11817 @noindent
11818 Each project has exactly one object directory and one or more source
11819 directories. The source directories must contain at least one source file,
11820 unless  the project file explicitly specifies that no source files are present
11821 (@pxref{Source File Names}).
11822
11823 @node Object Directory
11824 @subsection Object Directory
11825
11826 @noindent
11827 The object directory for a project is the directory containing the compiler's
11828 output (such as @file{ALI} files and object files) for the project's immediate
11829 sources.
11830
11831 The object directory is given by the value of the attribute @code{Object_Dir}
11832 in the project file.
11833
11834 @smallexample @c projectfile
11835    for Object_Dir use "objects";
11836 @end smallexample
11837
11838 @noindent
11839 The attribute @var{Object_Dir} has a string value, the path name of the object
11840 directory. The path name may be absolute or relative to the directory of the
11841 project file. This directory must already exist, and be readable and writable.
11842
11843 By default, when the attribute @code{Object_Dir} is not given an explicit value
11844 or when its value is the empty string, the object directory is the same as the
11845 directory containing the project file.
11846
11847 @node Exec Directory
11848 @subsection Exec Directory
11849
11850 @noindent
11851 The exec directory for a project is the directory containing the executables
11852 for the project's main subprograms.
11853
11854 The exec directory is given by the value of the attribute @code{Exec_Dir}
11855 in the project file.
11856
11857 @smallexample @c projectfile
11858    for Exec_Dir use "executables";
11859 @end smallexample
11860
11861 @noindent
11862 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11863 directory. The path name may be absolute or relative to the directory of the
11864 project file. This directory must already exist, and be writable.
11865
11866 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11867 or when its value is the empty string, the exec directory is the same as the
11868 object directory of the project file.
11869
11870 @node Source Directories
11871 @subsection Source Directories
11872
11873 @noindent
11874 The source directories of a project are specified by the project file
11875 attribute @code{Source_Dirs}.
11876
11877 This attribute's value is a string list. If the attribute is not given an
11878 explicit value, then there is only one source directory, the one where the
11879 project file resides.
11880
11881 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11882 as in
11883
11884 @smallexample @c projectfile
11885     for Source_Dirs use ();
11886 @end smallexample
11887
11888 @noindent
11889 indicates that the project contains no source files.
11890
11891 Otherwise, each string in the string list designates one or more
11892 source directories.
11893
11894 @smallexample @c projectfile
11895    for Source_Dirs use ("sources", "test/drivers");
11896 @end smallexample
11897
11898 @noindent
11899 If a string in the list ends with @code{"/**"},  then the directory whose path
11900 name precedes the two asterisks, as well as all its subdirectories
11901 (recursively), are source directories.
11902
11903 @smallexample @c projectfile
11904    for Source_Dirs use ("/system/sources/**");
11905 @end smallexample
11906
11907 @noindent
11908 Here the directory @code{/system/sources} and all of its subdirectories
11909 (recursively) are source directories.
11910
11911 To specify that the source directories are the directory of the project file
11912 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11913 @smallexample @c projectfile
11914    for Source_Dirs use ("./**");
11915 @end smallexample
11916
11917 @noindent
11918 Each of the source directories must exist and be readable.
11919
11920 @node Source File Names
11921 @subsection Source File Names
11922
11923 @noindent
11924 In a project that contains source files, their names may be specified by the
11925 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11926 (a string). Source file names never include any directory information.
11927
11928 If the attribute @code{Source_Files} is given an explicit value, then each
11929 element of the list is a source file name.
11930
11931 @smallexample @c projectfile
11932    for Source_Files use ("main.adb");
11933    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11934 @end smallexample
11935
11936 @noindent
11937 If the attribute @code{Source_Files} is not given an explicit value,
11938 but the attribute @code{Source_List_File} is given a string value,
11939 then the source file names are contained in the text file whose path name
11940 (absolute or relative to the directory of the project file) is the
11941 value of the attribute @code{Source_List_File}.
11942
11943 Each line in the file that is not empty or is not a comment
11944 contains a source file name.
11945
11946 @smallexample @c projectfile
11947    for Source_List_File use "source_list.txt";
11948 @end smallexample
11949
11950 @noindent
11951 By default, if neither the attribute @code{Source_Files} nor the attribute
11952 @code{Source_List_File} is given an explicit value, then each file in the
11953 source directories that conforms to the project's naming scheme
11954 (@pxref{Naming Schemes}) is an immediate source of the project.
11955
11956 A warning is issued if both attributes @code{Source_Files} and
11957 @code{Source_List_File} are given explicit values. In this case, the attribute
11958 @code{Source_Files} prevails.
11959
11960 Each source file name must be the name of one existing source file
11961 in one of the source directories.
11962
11963 A @code{Source_Files} attribute whose value is an empty list
11964 indicates that there are no source files in the project.
11965
11966 If the order of the source directories is known statically, that is if
11967 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11968 be several files with the same source file name. In this case, only the file
11969 in the first directory is considered as an immediate source of the project
11970 file. If the order of the source directories is not known statically, it is
11971 an error to have several files with the same source file name.
11972
11973 Projects can be specified to have no Ada source
11974 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11975 list, or the @code{"Ada"} may be absent from @code{Languages}:
11976
11977 @smallexample @c projectfile
11978    for Source_Dirs use ();
11979    for Source_Files use ();
11980    for Languages use ("C", "C++");
11981 @end smallexample
11982
11983 @noindent
11984 Otherwise, a project must contain at least one immediate source.
11985
11986 Projects with no source files are useful as template packages
11987 (@pxref{Packages in Project Files}) for other projects; in particular to
11988 define a package @code{Naming} (@pxref{Naming Schemes}).
11989
11990 @c ****************************
11991 @c * Importing Projects *
11992 @c ****************************
11993
11994 @node  Importing Projects
11995 @section Importing Projects
11996
11997 @noindent
11998 An immediate source of a project P may depend on source files that
11999 are neither immediate sources of P nor in the predefined library.
12000 To get this effect, P must @emph{import} the projects that contain the needed
12001 source files.
12002
12003 @smallexample @c projectfile
12004 @group
12005   with "project1", "utilities.gpr";
12006   with "/namings/apex.gpr";
12007   project Main is
12008     ...
12009 @end group
12010 @end smallexample
12011
12012 @noindent
12013 As can be seen in this example, the syntax for importing projects is similar
12014 to the syntax for importing compilation units in Ada. However, project files
12015 use literal strings instead of names, and the @code{with} clause identifies
12016 project files rather than packages.
12017
12018 Each literal string is the file name or path name (absolute or relative) of a
12019 project file. If a string is simply a file name, with no path, then its
12020 location is determined by the @emph{project path}:
12021
12022 @itemize @bullet
12023 @item
12024 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
12025 then the project path includes all the directories in this
12026 ^environment variable^logical name^, plus the directory of the project file.
12027
12028 @item
12029 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
12030 exist, then the project path contains only one directory, namely the one where
12031 the project file is located.
12032 @end itemize
12033
12034 @noindent
12035 If a relative pathname is used, as in
12036
12037 @smallexample @c projectfile
12038   with "tests/proj";
12039 @end smallexample
12040
12041 @noindent
12042 then the path is relative to the directory where the importing project file is
12043 located. Any symbolic link will be fully resolved in the directory
12044 of the importing project file before the imported project file is examined.
12045
12046 If the @code{with}'ed project file name does not have an extension,
12047 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12048 then the file name as specified in the @code{with} clause (no extension) will
12049 be used. In the above example, if a file @code{project1.gpr} is found, then it
12050 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12051 then it will be used; if neither file exists, this is an error.
12052
12053 A warning is issued if the name of the project file does not match the
12054 name of the project; this check is case insensitive.
12055
12056 Any source file that is an immediate source of the imported project can be
12057 used by the immediate sources of the importing project, transitively. Thus
12058 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12059 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12060 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12061 because if and when @code{B} ceases to import @code{C}, some sources in
12062 @code{A} will no longer compile.
12063
12064 A side effect of this capability is that normally cyclic dependencies are not
12065 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12066 is not allowed to import @code{A}. However, there are cases when cyclic
12067 dependencies would be beneficial. For these cases, another form of import
12068 between projects exists, the @code{limited with}: a project @code{A} that
12069 imports a project @code{B} with a straigh @code{with} may also be imported,
12070 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12071 to @code{A} include at least one @code{limited with}.
12072
12073 @smallexample @c 0projectfile
12074 with "../b/b.gpr";
12075 with "../c/c.gpr";
12076 project A is
12077 end A;
12078
12079 limited with "../a/a.gpr";
12080 project B is
12081 end B;
12082
12083 with "../d/d.gpr";
12084 project C is
12085 end C;
12086
12087 limited with "../a/a.gpr";
12088 project D is
12089 end D;
12090 @end smallexample
12091
12092 @noindent
12093 In the above legal example, there are two project cycles:
12094 @itemize @bullet
12095 @item A-> B-> A
12096 @item A -> C -> D -> A
12097 @end itemize
12098
12099 @noindent
12100 In each of these cycle there is one @code{limited with}: import of @code{A}
12101 from @code{B} and import of @code{A} from @code{D}.
12102
12103 The difference between straight @code{with} and @code{limited with} is that
12104 the name of a project imported with a @code{limited with} cannot be used in the
12105 project that imports it. In particular, its packages cannot be renamed and
12106 its variables cannot be referred to.
12107
12108 An exception to the above rules for @code{limited with} is that for the main
12109 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12110 @code{limited with} is equivalent to a straight @code{with}. For example,
12111 in the example above, projects @code{B} and @code{D} could not be main
12112 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12113 each have a @code{limited with} that is the only one in a cycle of importing
12114 projects.
12115
12116 @c *********************
12117 @c * Project Extension *
12118 @c *********************
12119
12120 @node Project Extension
12121 @section Project Extension
12122
12123 @noindent
12124 During development of a large system, it is sometimes necessary to use
12125 modified versions of some of the source files, without changing the original
12126 sources. This can be achieved through the @emph{project extension} facility.
12127
12128 @smallexample @c projectfile
12129    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12130 @end smallexample
12131
12132 @noindent
12133 A project extension declaration introduces an extending project
12134 (the @emph{child}) and a project being extended (the @emph{parent}).
12135
12136 By default, a child project inherits all the sources of its parent.
12137 However, inherited sources can be overridden: a unit in a parent is hidden
12138 by a unit of the same name in the child.
12139
12140 Inherited sources are considered to be sources (but not immediate sources)
12141 of the child project; see @ref{Project File Syntax}.
12142
12143 An inherited source file retains any switches specified in the parent project.
12144
12145 For example if the project @code{Utilities} contains the specification and the
12146 body of an Ada package @code{Util_IO}, then the project
12147 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12148 The original body of @code{Util_IO} will not be considered in program builds.
12149 However, the package specification will still be found in the project
12150 @code{Utilities}.
12151
12152 A child project can have only one parent but it may import any number of other
12153 projects.
12154
12155 A project is not allowed to import directly or indirectly at the same time a
12156 child project and any of its ancestors.
12157
12158 @c *******************************
12159 @c * Project Hierarchy Extension *
12160 @c *******************************
12161
12162 @node Project Hierarchy Extension
12163 @section Project Hierarchy Extension
12164
12165 @noindent
12166 When extending a large system spanning multiple projects, it is often
12167 inconvenient to extend every project in the hierarchy that is impacted by a
12168 small change introduced. In such cases, it is possible to create a virtual
12169 extension of entire hierarchy using @code{extends all} relationship.
12170
12171 When the project is extended using @code{extends all} inheritance, all projects
12172 that are imported by it, both directly and indirectly, are considered virtually
12173 extended. That is, the Project Manager creates "virtual projects"
12174 that extend every project in the hierarchy; all these virtual projects have
12175 no sources of their own and have as object directory the object directory of
12176 the root of "extending all" project.
12177
12178 It is possible to explicitly extend one or more projects in the hierarchy
12179 in order to modify the sources. These extending projects must be imported by
12180 the "extending all" project, which will replace the corresponding virtual
12181 projects with the explicit ones.
12182
12183 When building such a project hierarchy extension, the Project Manager will
12184 ensure that both modified sources and sources in virtual extending projects
12185 that depend on them, are recompiled.
12186
12187 By means of example, consider the following hierarchy of projects.
12188
12189 @enumerate
12190 @item
12191 project A, containing package P1
12192 @item
12193 project B importing A and containing package P2 which depends on P1
12194 @item
12195 project C importing B and containing package P3 which depends on P2
12196 @end enumerate
12197
12198 @noindent
12199 We want to modify packages P1 and P3.
12200
12201 This project hierarchy will need to be extended as follows:
12202
12203 @enumerate
12204 @item
12205 Create project A1 that extends A, placing modified P1 there:
12206
12207 @smallexample @c 0projectfile
12208 project A1 extends "(...)/A" is
12209 end A1;
12210 @end smallexample
12211
12212 @item
12213 Create project C1 that "extends all" C and imports A1, placing modified
12214 P3 there:
12215
12216 @smallexample @c 0projectfile
12217 with "(...)/A1";
12218 project C1 extends all "(...)/C" is
12219 end C1;
12220 @end smallexample
12221 @end enumerate
12222
12223 When you build project C1, your entire modified project space will be
12224 recompiled, including the virtual project B1 that has been impacted by the
12225 "extending all" inheritance of project C.
12226
12227 Note that if a Library Project in the hierarchy is virtually extended,
12228 the virtual project that extends the Library Project is not a Library Project.
12229
12230 @c ****************************************
12231 @c * External References in Project Files *
12232 @c ****************************************
12233
12234 @node  External References in Project Files
12235 @section External References in Project Files
12236
12237 @noindent
12238 A project file may contain references to external variables; such references
12239 are called @emph{external references}.
12240
12241 An external variable is either defined as part of the environment (an
12242 environment variable in Unix, for example) or else specified on the command
12243 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12244 If both, then the command line value is used.
12245
12246 The value of an external reference is obtained by means of the built-in
12247 function @code{external}, which returns a string value.
12248 This function has two forms:
12249 @itemize @bullet
12250 @item @code{external (external_variable_name)}
12251 @item @code{external (external_variable_name, default_value)}
12252 @end itemize
12253
12254 @noindent
12255 Each parameter must be a string literal.  For example:
12256
12257 @smallexample @c projectfile
12258    external ("USER")
12259    external ("OS", "GNU/Linux")
12260 @end smallexample
12261
12262 @noindent
12263 In the form with one parameter, the function returns the value of
12264 the external variable given as parameter. If this name is not present in the
12265 environment, the function returns an empty string.
12266
12267 In the form with two string parameters, the second argument is
12268 the value returned when the variable given as the first argument is not
12269 present in the environment. In the example above, if @code{"OS"} is not
12270 the name of ^an environment variable^a logical name^ and is not passed on
12271 the command line, then the returned value is @code{"GNU/Linux"}.
12272
12273 An external reference may be part of a string expression or of a string
12274 list expression, and can therefore appear in a variable declaration or
12275 an attribute declaration.
12276
12277 @smallexample @c projectfile
12278 @group
12279    type Mode_Type is ("Debug", "Release");
12280    Mode : Mode_Type := external ("MODE");
12281    case Mode is
12282      when "Debug" =>
12283         ...
12284 @end group
12285 @end smallexample
12286
12287 @c *****************************
12288 @c * Packages in Project Files *
12289 @c *****************************
12290
12291 @node  Packages in Project Files
12292 @section Packages in Project Files
12293
12294 @noindent
12295 A @emph{package} defines the settings for project-aware tools within a
12296 project.
12297 For each such tool one can declare a package; the names for these
12298 packages are preset (@pxref{Packages}).
12299 A package may contain variable declarations, attribute declarations, and case
12300 constructions.
12301
12302 @smallexample @c projectfile
12303 @group
12304    project Proj is
12305       package Builder is  -- used by gnatmake
12306          for ^Default_Switches^Default_Switches^ ("Ada")
12307              use ("^-v^-v^",
12308                   "^-g^-g^");
12309       end Builder;
12310    end Proj;
12311 @end group
12312 @end smallexample
12313
12314 @noindent
12315 The syntax of package declarations mimics that of package in Ada.
12316
12317 Most of the packages have an attribute
12318 @code{^Default_Switches^Default_Switches^}.
12319 This attribute is an associative array, and its value is a string list.
12320 The index of the associative array is the name of a programming language (case
12321 insensitive). This attribute indicates the ^switch^switch^
12322 or ^switches^switches^ to be used
12323 with the corresponding tool.
12324
12325 Some packages also have another attribute, @code{^Switches^Switches^},
12326 an associative array whose value is a string list.
12327 The index is the name of a source file.
12328 This attribute indicates the ^switch^switch^
12329 or ^switches^switches^ to be used by the corresponding
12330 tool when dealing with this specific file.
12331
12332 Further information on these ^switch^switch^-related attributes is found in
12333 @ref{^Switches^Switches^ and Project Files}.
12334
12335 A package may be declared as a @emph{renaming} of another package; e.g., from
12336 the project file for an imported project.
12337
12338 @smallexample @c projectfile
12339 @group
12340   with "/global/apex.gpr";
12341   project Example is
12342     package Naming renames Apex.Naming;
12343     ...
12344   end Example;
12345 @end group
12346 @end smallexample
12347
12348 @noindent
12349 Packages that are renamed in other project files often come from project files
12350 that have no sources: they are just used as templates. Any modification in the
12351 template will be reflected automatically in all the project files that rename
12352 a package from the template.
12353
12354 In addition to the tool-oriented packages, you can also declare a package
12355 named @code{Naming} to establish specialized source file naming conventions
12356 (@pxref{Naming Schemes}).
12357
12358 @c ************************************
12359 @c * Variables from Imported Projects *
12360 @c ************************************
12361
12362 @node Variables from Imported Projects
12363 @section Variables from Imported Projects
12364
12365 @noindent
12366 An attribute or variable defined in an imported or parent project can
12367 be used in expressions in the importing / extending project.
12368 Such an attribute or variable is denoted by an expanded name whose prefix
12369 is either the name of the project or the expanded name of a package within
12370 a project.
12371
12372 @smallexample @c projectfile
12373 @group
12374   with "imported";
12375   project Main extends "base" is
12376      Var1 := Imported.Var;
12377      Var2 := Base.Var & ".new";
12378 @end group
12379
12380 @group
12381      package Builder is
12382         for ^Default_Switches^Default_Switches^ ("Ada")
12383             use Imported.Builder.Ada_^Switches^Switches^ &
12384                 "^-gnatg^-gnatg^" &
12385                 "^-v^-v^";
12386      end Builder;
12387 @end group
12388
12389 @group
12390      package Compiler is
12391         for ^Default_Switches^Default_Switches^ ("Ada")
12392             use Base.Compiler.Ada_^Switches^Switches^;
12393      end Compiler;
12394   end Main;
12395 @end group
12396 @end smallexample
12397
12398 @noindent
12399 In this example:
12400
12401 @itemize @bullet
12402 @item
12403 The value of @code{Var1} is a copy of the variable @code{Var} defined
12404 in the project file @file{"imported.gpr"}
12405 @item
12406 the value of @code{Var2} is a copy of the value of variable @code{Var}
12407 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12408 @item
12409 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12410 @code{Builder} is a string list that includes in its value a copy of the value
12411 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12412 in project file @file{imported.gpr} plus two new elements:
12413 @option{"^-gnatg^-gnatg^"}
12414 and @option{"^-v^-v^"};
12415 @item
12416 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12417 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12418 defined in the @code{Compiler} package in project file @file{base.gpr},
12419 the project being extended.
12420 @end itemize
12421
12422 @c ******************
12423 @c * Naming Schemes *
12424 @c ******************
12425
12426 @node  Naming Schemes
12427 @section Naming Schemes
12428
12429 @noindent
12430 Sometimes an Ada software system is ported from a foreign compilation
12431 environment to GNAT, and the file names do not use the default GNAT
12432 conventions. Instead of changing all the file names (which for a variety
12433 of reasons might not be possible), you can define the relevant file
12434 naming scheme in the @code{Naming} package in your project file.
12435
12436 @noindent
12437 Note that the use of pragmas described in
12438 @ref{Alternative File Naming Schemes} by mean of a configuration
12439 pragmas file is not supported when using project files. You must use
12440 the features described in this paragraph. You can however use specify
12441 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12442
12443 @ifclear vms
12444 For example, the following
12445 package models the Apex file naming rules:
12446
12447 @smallexample @c projectfile
12448 @group
12449   package Naming is
12450     for Casing               use "lowercase";
12451     for Dot_Replacement      use ".";
12452     for Spec_Suffix ("Ada")  use ".1.ada";
12453     for Body_Suffix ("Ada")  use ".2.ada";
12454   end Naming;
12455 @end group
12456 @end smallexample
12457 @end ifclear
12458
12459 @ifset vms
12460 For example, the following package models the DEC Ada file naming rules:
12461
12462 @smallexample @c projectfile
12463 @group
12464   package Naming is
12465     for Casing               use "lowercase";
12466     for Dot_Replacement      use "__";
12467     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12468     for Body_Suffix ("Ada")  use ".^ada^ada^";
12469   end Naming;
12470 @end group
12471 @end smallexample
12472
12473 @noindent
12474 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12475 names in lower case)
12476 @end ifset
12477
12478 @noindent
12479 You can define the following attributes in package @code{Naming}:
12480
12481 @table @code
12482
12483 @item @var{Casing}
12484 This must be a string with one of the three values @code{"lowercase"},
12485 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12486
12487 @noindent
12488 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12489
12490 @item @var{Dot_Replacement}
12491 This must be a string whose value satisfies the following conditions:
12492
12493 @itemize @bullet
12494 @item It must not be empty
12495 @item It cannot start or end with an alphanumeric character
12496 @item It cannot be a single underscore
12497 @item It cannot start with an underscore followed by an alphanumeric
12498 @item It cannot contain a dot @code{'.'} except if the entire string
12499 is @code{"."}
12500 @end itemize
12501
12502 @noindent
12503 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12504
12505 @item @var{Spec_Suffix}
12506 This is an associative array (indexed by the programming language name, case
12507 insensitive) whose value is a string that must satisfy the following
12508 conditions:
12509
12510 @itemize @bullet
12511 @item It must not be empty
12512 @item It must include at least one dot
12513 @end itemize
12514 @noindent
12515 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12516 @code{"^.ads^.ADS^"}.
12517
12518 @item @var{Body_Suffix}
12519 This is an associative array (indexed by the programming language name, case
12520 insensitive) whose value is a string that must satisfy the following
12521 conditions:
12522
12523 @itemize @bullet
12524 @item It must not be empty
12525 @item It must include at least one dot
12526 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12527 @end itemize
12528 @noindent
12529 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12530 @code{"^.adb^.ADB^"}.
12531
12532 @item @var{Separate_Suffix}
12533 This must be a string whose value satisfies the same conditions as
12534 @code{Body_Suffix}.
12535
12536 @noindent
12537 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12538 value as @code{Body_Suffix ("Ada")}.
12539
12540 @item @var{Spec}
12541 @noindent
12542 You can use the associative array attribute @code{Spec}  to define
12543 the source file name for an individual Ada compilation unit's spec. The array
12544 index must be a string literal that identifies the Ada unit (case insensitive).
12545 The value of this attribute must be a string that identifies the file that
12546 contains this unit's spec (case sensitive or insensitive depending on the
12547 operating system).
12548
12549 @smallexample @c projectfile
12550    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12551 @end smallexample
12552
12553 @item @var{Body}
12554
12555 You can use the associative array attribute @code{Body} to
12556 define the source file name for an individual Ada compilation unit's body
12557 (possibly a subunit).  The array index must be a string literal that identifies
12558 the Ada unit (case insensitive).  The value of this attribute must be a string
12559 that identifies the file that contains this unit's body or subunit (case
12560 sensitive or insensitive depending on the operating system).
12561
12562 @smallexample @c projectfile
12563    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12564 @end smallexample
12565 @end table
12566
12567 @c ********************
12568 @c * Library Projects *
12569 @c ********************
12570
12571 @node Library Projects
12572 @section Library Projects
12573
12574 @noindent
12575 @emph{Library projects} are projects whose object code is placed in a library.
12576 (Note that this facility is not yet supported on all platforms)
12577
12578 To create a library project, you need to define in its project file
12579 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12580 Additionally, you may define the library-related attributes
12581 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12582 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12583
12584 The @code{Library_Name} attribute has a string value. There is no restriction
12585 on the name of a library. It is the responsability of the developer to
12586 choose a name that will be accepted by the platform. It is recommanded to
12587 choose names that could be Ada identifiers; such names are almost guaranteed
12588 to be acceptable on all platforms.
12589
12590 The @code{Library_Dir} attribute has a string value that designates the path
12591 (absolute or relative) of the directory where the library will reside.
12592 It must designate an existing directory, and this directory must be
12593 different from the project's object directory. It also needs to be writable.
12594 The directory should only be used for one library; the reason is that all
12595 files contained in this directory may be deleted by the Project Manager.
12596
12597 If both @code{Library_Name} and @code{Library_Dir} are specified and
12598 are legal, then the project file defines a library project.  The optional
12599 library-related attributes are checked only for such project files.
12600
12601 The @code{Library_Kind} attribute has a string value that must be one of the
12602 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12603 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12604 attribute is not specified, the library is a static library, that is
12605 an archive of object files that can be potentially linked into an
12606 static executable. Otherwise, the library may be dynamic or
12607 relocatable, that is a library that is loaded only at the start of execution.
12608
12609 If you need to build both a static and a dynamic library, you should use two
12610 different object directories, since in some cases some extra code needs to
12611 be generated for the latter. For such cases, it is recommended to either use
12612 two different project files, or a single one which uses external variables
12613 to indicate what kind of library should be build.
12614
12615 The @code{Library_Version} attribute has a string value whose interpretation
12616 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12617 used only for dynamic/relocatable libraries as the internal name of the
12618 library (the @code{"soname"}). If the library file name (built from the
12619 @code{Library_Name}) is different from the @code{Library_Version}, then the
12620 library file will be a symbolic link to the actual file whose name will be
12621 @code{Library_Version}.
12622
12623 Example (on Unix):
12624
12625 @smallexample @c projectfile
12626 @group
12627 project Plib is
12628
12629    Version := "1";
12630
12631    for Library_Dir use "lib_dir";
12632    for Library_Name use "dummy";
12633    for Library_Kind use "relocatable";
12634    for Library_Version use "libdummy.so." & Version;
12635
12636 end Plib;
12637 @end group
12638 @end smallexample
12639
12640 @noindent
12641 Directory @file{lib_dir} will contain the internal library file whose name
12642 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12643 @file{libdummy.so.1}.
12644
12645 When @command{gnatmake} detects that a project file
12646 is a library project file, it will check all immediate sources of the project
12647 and rebuild the library if any of the sources have been recompiled.
12648
12649 Standard project files can import library project files. In such cases,
12650 the libraries will only be rebuild if some of its sources are recompiled
12651 because they are in the closure of some other source in an importing project.
12652 Sources of the library project files that are not in such a closure will
12653 not be checked, unless the full library is checked, because one of its sources
12654 needs to be recompiled.
12655
12656 For instance, assume the project file @code{A} imports the library project file
12657 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12658 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12659 @file{l2.ads}, @file{l2.adb}.
12660
12661 If @file{l1.adb} has been modified, then the library associated with @code{L}
12662 will be rebuild when compiling all the immediate sources of @code{A} only
12663 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12664 @code{"with L1;"}.
12665
12666 To be sure that all the sources in the library associated with @code{L} are
12667 up to date, and that all the sources of parject @code{A} are also up to date,
12668 the following two commands needs to be used:
12669
12670 @smallexample
12671 gnatmake -Pl.gpr
12672 gnatmake -Pa.gpr
12673 @end smallexample
12674
12675 When a library is built or rebuilt, an attempt is made first to delete all
12676 files in the library directory.
12677 All @file{ALI} files will also be copied from the object directory to the
12678 library directory. To build executables, @command{gnatmake} will use the
12679 library rather than the individual object files.
12680
12681 @ifclear vms
12682 It is also possible to create library project files for third-party libraries
12683 that are precompiled and cannot be compiled locally thanks to the
12684 @code{externally_built} attribute. (See @ref{Installing a library}).
12685 @end ifclear
12686
12687 @c *******************************
12688 @c * Stand-alone Library Projects *
12689 @c *******************************
12690
12691 @node Stand-alone Library Projects
12692 @section Stand-alone Library Projects
12693
12694 @noindent
12695 A Stand-alone Library is a library that contains the necessary code to
12696 elaborate the Ada units that are included in the library. A Stand-alone
12697 Library is suitable to be used in an executable when the main is not
12698 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12699 subprogram.
12700
12701 A Stand-alone Library Project is a Library Project where the library is
12702 a Stand-alone Library.
12703
12704 To be a Stand-alone Library Project, in addition to the two attributes
12705 that make a project a Library Project (@code{Library_Name} and
12706 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12707 @code{Library_Interface} must be defined.
12708
12709 @smallexample @c projectfile
12710 @group
12711    for Library_Dir use "lib_dir";
12712    for Library_Name use "dummy";
12713    for Library_Interface use ("int1", "int1.child");
12714 @end group
12715 @end smallexample
12716
12717 Attribute @code{Library_Interface} has a non empty string list value,
12718 each string in the list designating a unit contained in an immediate source
12719 of the project file.
12720
12721 When a Stand-alone Library is built, first the binder is invoked to build
12722 a package whose name depends on the library name
12723 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12724 This binder-generated package includes initialization and
12725 finalization procedures whose
12726 names depend on the library name (dummyinit and dummyfinal in the example
12727 above). The object corresponding to this package is included in the library.
12728
12729 A dynamic or relocatable Stand-alone Library is automatically initialized
12730 if automatic initialization of Stand-alone Libraries is supported on the
12731 platform and if attribute @code{Library_Auto_Init} is not specified or
12732 is specified with the value "true". A static Stand-alone Library is never
12733 automatically initialized.
12734
12735 Single string attribute @code{Library_Auto_Init} may be specified with only
12736 two possible values: "false" or "true" (case-insensitive). Specifying
12737 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12738 initialization of dynamic or relocatable libraries.
12739
12740 When a non automatically initialized Stand-alone Library is used
12741 in an executable, its initialization procedure must be called before
12742 any service of the library is used.
12743 When the main subprogram is in Ada, it may mean that the initialization
12744 procedure has to be called during elaboration of another package.
12745
12746 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12747 (those that are listed in attribute @code{Library_Interface}) are copied to
12748 the Library Directory. As a consequence, only the Interface Units may be
12749 imported from Ada units outside of the library. If other units are imported,
12750 the binding phase will fail.
12751
12752 When a Stand-Alone Library is bound, the switches that are specified in
12753 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12754 used in the call to @command{gnatbind}.
12755
12756 The string list attribute @code{Library_Options} may be used to specified
12757 additional switches to the call to @command{gcc} to link the library.
12758
12759 The attribute @code{Library_Src_Dir}, may be specified for a
12760 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12761 single string value. Its value must be the path (absolute or relative to the
12762 project directory) of an existing directory. This directory cannot be the
12763 object directory or one of the source directories, but it can be the same as
12764 the library directory. The sources of the Interface
12765 Units of the library, necessary to an Ada client of the library, will be
12766 copied to the designated directory, called Interface Copy directory.
12767 These sources includes the specs of the Interface Units, but they may also
12768 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12769 are used, or when there is a generic units in the spec. Before the sources
12770 are copied to the Interface Copy directory, an attempt is made to delete all
12771 files in the Interface Copy directory.
12772
12773 @c *************************************
12774 @c * Switches Related to Project Files *
12775 @c *************************************
12776 @node Switches Related to Project Files
12777 @section Switches Related to Project Files
12778
12779 @noindent
12780 The following switches are used by GNAT tools that support project files:
12781
12782 @table @option
12783
12784 @item ^-P^/PROJECT_FILE=^@var{project}
12785 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12786 Indicates the name of a project file. This project file will be parsed with
12787 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12788 if any, and using the external references indicated
12789 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12790 @ifclear vms
12791 There may zero, one or more spaces between @option{-P} and @var{project}.
12792 @end ifclear
12793
12794 @noindent
12795 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12796
12797 @noindent
12798 Since the Project Manager parses the project file only after all the switches
12799 on the command line are checked, the order of the switches
12800 @option{^-P^/PROJECT_FILE^},
12801 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12802 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12803
12804 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12805 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12806 Indicates that external variable @var{name} has the value @var{value}.
12807 The Project Manager will use this value for occurrences of
12808 @code{external(name)} when parsing the project file.
12809
12810 @ifclear vms
12811 @noindent
12812 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12813 put between quotes.
12814 @smallexample
12815   -XOS=NT
12816   -X"user=John Doe"
12817 @end smallexample
12818 @end ifclear
12819
12820 @noindent
12821 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12822 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12823 @var{name}, only the last one is used.
12824
12825 @noindent
12826 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12827 takes precedence over the value of the same name in the environment.
12828
12829 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12830 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12831 @c Previous line uses code vs option command, to stay less than 80 chars
12832 Indicates the verbosity of the parsing of GNAT project files.
12833
12834 @ifclear vms
12835 @option{-vP0} means Default;
12836 @option{-vP1} means Medium;
12837 @option{-vP2} means High.
12838 @end ifclear
12839
12840 @ifset vms
12841 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12842 HIGH.
12843 @end ifset
12844
12845 @noindent
12846 The default is ^Default^DEFAULT^: no output for syntactically correct
12847 project files.
12848 @noindent
12849 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12850 only the last one is used.
12851
12852 @end table
12853
12854 @c **********************************
12855 @c * Tools Supporting Project Files *
12856 @c **********************************
12857
12858 @node  Tools Supporting Project Files
12859 @section Tools Supporting Project Files
12860
12861 @menu
12862 * gnatmake and Project Files::
12863 * The GNAT Driver and Project Files::
12864 @ifclear vms
12865 * Glide and Project Files::
12866 @end ifclear
12867 @end menu
12868
12869 @node gnatmake and Project Files
12870 @subsection gnatmake and Project Files
12871
12872 @noindent
12873 This section covers several topics related to @command{gnatmake} and
12874 project files: defining ^switches^switches^ for @command{gnatmake}
12875 and for the tools that it invokes; specifying configuration pragmas;
12876 the use of the @code{Main} attribute; building and rebuilding library project
12877 files.
12878
12879 @menu
12880 * ^Switches^Switches^ and Project Files::
12881 * Specifying Configuration Pragmas::
12882 * Project Files and Main Subprograms::
12883 * Library Project Files::
12884 @end menu
12885
12886 @node ^Switches^Switches^ and Project Files
12887 @subsubsection ^Switches^Switches^ and Project Files
12888
12889 @ifset vms
12890 It is not currently possible to specify VMS style qualifiers in the project
12891 files; only Unix style ^switches^switches^ may be specified.
12892 @end ifset
12893
12894 @noindent
12895 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12896 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12897 attribute, a @code{^Switches^Switches^} attribute, or both;
12898 as their names imply, these ^switch^switch^-related
12899 attributes affect the ^switches^switches^ that are used for each of these GNAT
12900 components when
12901 @command{gnatmake} is invoked.  As will be explained below, these
12902 component-specific ^switches^switches^ precede
12903 the ^switches^switches^ provided on the @command{gnatmake} command line.
12904
12905 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12906 array indexed by language name (case insensitive) whose value is a string list.
12907 For example:
12908
12909 @smallexample @c projectfile
12910 @group
12911 package Compiler is
12912   for ^Default_Switches^Default_Switches^ ("Ada")
12913       use ("^-gnaty^-gnaty^",
12914            "^-v^-v^");
12915 end Compiler;
12916 @end group
12917 @end smallexample
12918
12919 @noindent
12920 The @code{^Switches^Switches^} attribute is also an associative array,
12921 indexed by a file name (which may or may not be case sensitive, depending
12922 on the operating system) whose value is a string list.  For example:
12923
12924 @smallexample @c projectfile
12925 @group
12926 package Builder is
12927    for ^Switches^Switches^ ("main1.adb")
12928        use ("^-O2^-O2^");
12929    for ^Switches^Switches^ ("main2.adb")
12930        use ("^-g^-g^");
12931 end Builder;
12932 @end group
12933 @end smallexample
12934
12935 @noindent
12936 For the @code{Builder} package, the file names must designate source files
12937 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12938 file names must designate @file{ALI} or source files for main subprograms.
12939 In each case just the file name without an explicit extension is acceptable.
12940
12941 For each tool used in a program build (@command{gnatmake}, the compiler, the
12942 binder, and the linker), the corresponding package @dfn{contributes} a set of
12943 ^switches^switches^ for each file on which the tool is invoked, based on the
12944 ^switch^switch^-related attributes defined in the package.
12945 In particular, the ^switches^switches^
12946 that each of these packages contributes for a given file @var{f} comprise:
12947
12948 @itemize @bullet
12949 @item
12950 the value of attribute @code{^Switches^Switches^ (@var{f})},
12951 if it is specified in the package for the given file,
12952 @item
12953 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12954 if it is specified in the package.
12955 @end itemize
12956
12957 @noindent
12958 If neither of these attributes is defined in the package, then the package does
12959 not contribute any ^switches^switches^ for the given file.
12960
12961 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12962 two sets, in the following order: those contributed for the file
12963 by the @code{Builder} package;
12964 and the switches passed on the command line.
12965
12966 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12967 the ^switches^switches^ passed to the tool comprise three sets,
12968 in the following order:
12969
12970 @enumerate
12971 @item
12972 the applicable ^switches^switches^ contributed for the file
12973 by the @code{Builder} package in the project file supplied on the command line;
12974
12975 @item
12976 those contributed for the file by the package (in the relevant project file --
12977 see below) corresponding to the tool; and
12978
12979 @item
12980 the applicable switches passed on the command line.
12981 @end enumerate
12982
12983 @noindent
12984 The term @emph{applicable ^switches^switches^} reflects the fact that
12985 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12986 tools, depending on the individual ^switch^switch^.
12987
12988 @command{gnatmake} may invoke the compiler on source files from different
12989 projects. The Project Manager will use the appropriate project file to
12990 determine the @code{Compiler} package for each source file being compiled.
12991 Likewise for the @code{Binder} and @code{Linker} packages.
12992
12993 As an example, consider the following package in a project file:
12994
12995 @smallexample @c projectfile
12996 @group
12997 project Proj1 is
12998    package Compiler is
12999       for ^Default_Switches^Default_Switches^ ("Ada")
13000           use ("^-g^-g^");
13001       for ^Switches^Switches^ ("a.adb")
13002           use ("^-O1^-O1^");
13003       for ^Switches^Switches^ ("b.adb")
13004           use ("^-O2^-O2^",
13005                "^-gnaty^-gnaty^");
13006    end Compiler;
13007 end Proj1;
13008 @end group
13009 @end smallexample
13010
13011 @noindent
13012 If @command{gnatmake} is invoked with this project file, and it needs to
13013 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13014 @file{a.adb} will be compiled with the ^switch^switch^
13015 @option{^-O1^-O1^},
13016 @file{b.adb} with ^switches^switches^
13017 @option{^-O2^-O2^}
13018 and @option{^-gnaty^-gnaty^},
13019 and @file{c.adb} with @option{^-g^-g^}.
13020
13021 The following example illustrates the ordering of the ^switches^switches^
13022 contributed by different packages:
13023
13024 @smallexample @c projectfile
13025 @group
13026 project Proj2 is
13027    package Builder is
13028       for ^Switches^Switches^ ("main.adb")
13029           use ("^-g^-g^",
13030                "^-O1^-)1^",
13031                "^-f^-f^");
13032    end Builder;
13033 @end group
13034
13035 @group
13036    package Compiler is
13037       for ^Switches^Switches^ ("main.adb")
13038           use ("^-O2^-O2^");
13039    end Compiler;
13040 end Proj2;
13041 @end group
13042 @end smallexample
13043
13044 @noindent
13045 If you issue the command:
13046
13047 @smallexample
13048     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13049 @end smallexample
13050
13051 @noindent
13052 then the compiler will be invoked on @file{main.adb} with the following
13053 sequence of ^switches^switches^
13054
13055 @smallexample
13056    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13057 @end smallexample
13058
13059 with the last @option{^-O^-O^}
13060 ^switch^switch^ having precedence over the earlier ones;
13061 several other ^switches^switches^
13062 (such as @option{^-c^-c^}) are added implicitly.
13063
13064 The ^switches^switches^
13065 @option{^-g^-g^}
13066 and @option{^-O1^-O1^} are contributed by package
13067 @code{Builder},  @option{^-O2^-O2^} is contributed
13068 by the package @code{Compiler}
13069 and @option{^-O0^-O0^} comes from the command line.
13070
13071 The @option{^-g^-g^}
13072 ^switch^switch^ will also be passed in the invocation of
13073 @command{Gnatlink.}
13074
13075 A final example illustrates switch contributions from packages in different
13076 project files:
13077
13078 @smallexample @c projectfile
13079 @group
13080 project Proj3 is
13081    for Source_Files use ("pack.ads", "pack.adb");
13082    package Compiler is
13083       for ^Default_Switches^Default_Switches^ ("Ada")
13084           use ("^-gnata^-gnata^");
13085    end Compiler;
13086 end Proj3;
13087 @end group
13088
13089 @group
13090 with "Proj3";
13091 project Proj4 is
13092    for Source_Files use ("foo_main.adb", "bar_main.adb");
13093    package Builder is
13094       for ^Switches^Switches^ ("foo_main.adb")
13095           use ("^-s^-s^",
13096                "^-g^-g^");
13097    end Builder;
13098 end Proj4;
13099 @end group
13100
13101 @group
13102 -- Ada source file:
13103 with Pack;
13104 procedure Foo_Main is
13105    ...
13106 end Foo_Main;
13107 @end group
13108 @end smallexample
13109
13110 If the command is
13111 @smallexample
13112 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13113 @end smallexample
13114
13115 @noindent
13116 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13117 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13118 @option{^-gnato^-gnato^} (passed on the command line).
13119 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13120 are @option{^-g^-g^} from @code{Proj4.Builder},
13121 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13122 and @option{^-gnato^-gnato^} from the command line.
13123
13124 @noindent
13125 When using @command{gnatmake} with project files, some ^switches^switches^ or
13126 arguments may be expressed as relative paths. As the working directory where
13127 compilation occurs may change, these relative paths are converted to absolute
13128 paths. For the ^switches^switches^ found in a project file, the relative paths
13129 are relative to the project file directory, for the switches on the command
13130 line, they are relative to the directory where @command{gnatmake} is invoked.
13131 The ^switches^switches^ for which this occurs are:
13132 ^-I^-I^,
13133 ^-A^-A^,
13134 ^-L^-L^,
13135 ^-aO^-aO^,
13136 ^-aL^-aL^,
13137 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13138 ^switch^switch^
13139 ^-o^-o^, object files specified in package @code{Linker} or after
13140 -largs on the command line). The exception to this rule is the ^switch^switch^
13141 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13142
13143 @node Specifying Configuration Pragmas
13144 @subsubsection Specifying Configuration Pragmas
13145
13146 When using @command{gnatmake} with project files, if there exists a file
13147 @file{gnat.adc} that contains configuration pragmas, this file will be
13148 ignored.
13149
13150 Configuration pragmas can be defined by means of the following attributes in
13151 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13152 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13153
13154 Both these attributes are single string attributes. Their values is the path
13155 name of a file containing configuration pragmas. If a path name is relative,
13156 then it is relative to the project directory of the project file where the
13157 attribute is defined.
13158
13159 When compiling a source, the configuration pragmas used are, in order,
13160 those listed in the file designated by attribute
13161 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13162 project file, if it is specified, and those listed in the file designated by
13163 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13164 the project file of the source, if it exists.
13165
13166 @node Project Files and Main Subprograms
13167 @subsubsection Project Files and Main Subprograms
13168
13169 @noindent
13170 When using a project file, you can invoke @command{gnatmake}
13171 with one or several main subprograms, by specifying their source files on the
13172 command line.
13173
13174 @smallexample
13175     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13176 @end smallexample
13177
13178 @noindent
13179 Each of these needs to be a source file of the same project, except
13180 when the switch ^-u^/UNIQUE^ is used.
13181
13182 @noindent
13183 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13184 same project, one of the project in the tree rooted at the project specified
13185 on the command line. The package @code{Builder} of this common project, the
13186 "main project" is the one that is considered by @command{gnatmake}.
13187
13188 @noindent
13189 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13190 imported directly or indirectly by the project specified on the command line.
13191 Note that if such a source file is not part of the project specified on the
13192 command line, the ^switches^switches^ found in package @code{Builder} of the
13193 project specified on the command line, if any, that are transmitted
13194 to the compiler will still be used, not those found in the project file of
13195 the source file.
13196
13197 @noindent
13198 When using a project file, you can also invoke @command{gnatmake} without
13199 explicitly specifying any main, and the effect depends on whether you have
13200 defined the @code{Main} attribute.  This attribute has a string list value,
13201 where each element in the list is the name of a source file (the file
13202 extension is optional) that contains a unit that can be a main subprogram.
13203
13204 If the @code{Main} attribute is defined in a project file as a non-empty
13205 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13206 line, then invoking @command{gnatmake} with this project file but without any
13207 main on the command line is equivalent to invoking @command{gnatmake} with all
13208 the file names in the @code{Main} attribute on the command line.
13209
13210 Example:
13211 @smallexample @c projectfile
13212 @group
13213    project Prj is
13214       for Main use ("main1", "main2", "main3");
13215    end Prj;
13216 @end group
13217 @end smallexample
13218
13219 @noindent
13220 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13221 is equivalent to
13222 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13223
13224 When the project attribute @code{Main} is not specified, or is specified
13225 as an empty string list, or when the switch @option{-u} is used on the command
13226 line, then invoking @command{gnatmake} with no main on the command line will
13227 result in all immediate sources of the project file being checked, and
13228 potentially recompiled. Depending on the presence of the switch @option{-u},
13229 sources from other project files on which the immediate sources of the main
13230 project file depend are also checked and potentially recompiled. In other
13231 words, the @option{-u} switch is applied to all of the immediate sources of the
13232 main project file.
13233
13234 When no main is specified on the command line and attribute @code{Main} exists
13235 and includes several mains, or when several mains are specified on the
13236 command line, the default ^switches^switches^ in package @code{Builder} will
13237 be used for all mains, even if there are specific ^switches^switches^
13238 specified for one or several mains.
13239
13240 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13241 the specific ^switches^switches^ for each main, if they are specified.
13242
13243 @node Library Project Files
13244 @subsubsection Library Project Files
13245
13246 @noindent
13247 When @command{gnatmake} is invoked with a main project file that is a library
13248 project file, it is not allowed to specify one or more mains on the command
13249 line.
13250
13251 @noindent
13252 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13253 ^-l^/ACTION=LINK^ have special meanings.
13254
13255 @itemize @bullet
13256 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13257 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13258 library.
13259
13260 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13261 to @command{gnatmake} that the binder generated file should be compiled
13262 (in the case of a stand-alone library) and that the library should be built.
13263
13264 @end itemize
13265
13266 @node The GNAT Driver and Project Files
13267 @subsection The GNAT Driver and Project Files
13268
13269 @noindent
13270 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13271 are project-aware:
13272 @command{^gnatbind^gnatbind^},
13273 @command{^gnatfind^gnatfind^},
13274 @command{^gnatlink^gnatlink^},
13275 @command{^gnatls^gnatls^},
13276 @command{^gnatelim^gnatelim^},
13277 @command{^gnatpp^gnatpp^},
13278 @command{^gnatmetric^gnatmetric^},
13279 @command{^gnatstub^gnatstub^},
13280 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13281 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13282 They must be invoked through the @command{gnat} driver.
13283
13284 The @command{gnat} driver is a front-end that accepts a number of commands and
13285 call the corresponding tool. It has been designed initially for VMS to convert
13286 VMS style qualifiers to Unix style switches, but it is now available to all
13287 the GNAT supported platforms.
13288
13289 On non VMS platforms, the @command{gnat} driver accepts the following commands
13290 (case insensitive):
13291
13292 @itemize @bullet
13293 @item
13294 BIND to invoke @command{^gnatbind^gnatbind^}
13295 @item
13296 CHOP to invoke @command{^gnatchop^gnatchop^}
13297 @item
13298 CLEAN to invoke @command{^gnatclean^gnatclean^}
13299 @item
13300 COMP or COMPILE to invoke the compiler
13301 @item
13302 ELIM to invoke @command{^gnatelim^gnatelim^}
13303 @item
13304 FIND to invoke @command{^gnatfind^gnatfind^}
13305 @item
13306 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13307 @item
13308 LINK to invoke @command{^gnatlink^gnatlink^}
13309 @item
13310 LS or LIST to invoke @command{^gnatls^gnatls^}
13311 @item
13312 MAKE to invoke @command{^gnatmake^gnatmake^}
13313 @item
13314 NAME to invoke @command{^gnatname^gnatname^}
13315 @item
13316 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13317 @item
13318 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13319 @item
13320 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13321 @item
13322 STUB to invoke @command{^gnatstub^gnatstub^}
13323 @item
13324 XREF to invoke @command{^gnatxref^gnatxref^}
13325 @end itemize
13326
13327 @noindent
13328 (note that the compiler is invoked using the command
13329 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13330
13331 @noindent
13332 On non VMS platforms, between @command{gnat} and the command, two
13333 special switches may be used:
13334
13335 @itemize @bullet
13336 @item
13337 @command{-v} to display the invocation of the tool.
13338 @item
13339 @command{-dn} to prevent the @command{gnat} driver from removing
13340 the temporary files it has created. These temporary files are
13341 configuration files and temporary file list files.
13342 @end itemize
13343
13344 @noindent
13345 The command may be followed by switches and arguments for the invoked
13346 tool.
13347
13348 @smallexample
13349   gnat bind -C main.ali
13350   gnat ls -a main
13351   gnat chop foo.txt
13352 @end smallexample
13353
13354 @noindent
13355 Switches may also be put in text files, one switch per line, and the text
13356 files may be specified with their path name preceded by '@@'.
13357
13358 @smallexample
13359    gnat bind @@args.txt main.ali
13360 @end smallexample
13361
13362 @noindent
13363 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13364 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13365 (@option{^-P^/PROJECT_FILE^},
13366 @option{^-X^/EXTERNAL_REFERENCE^} and
13367 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13368 the switches of the invoking tool.
13369
13370 @noindent
13371 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13372 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13373 the immediate sources of the specified project file.
13374
13375 @noindent
13376 When GNAT METRIC is used with a project file, but with no source
13377 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13378 with all the immediate sources of the specified project file and with
13379 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13380 of the project.
13381
13382 @noindent
13383 For each of the following commands, there is optionally a corresponding
13384 package in the main project.
13385
13386 @itemize @bullet
13387 @item
13388 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13389
13390 @item
13391 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13392
13393 @item
13394 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13395
13396 @item
13397 package @code{Eliminate} for command ELIM (invoking
13398 @code{^gnatelim^gnatelim^})
13399
13400 @item
13401 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13402
13403 @item
13404 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13405
13406 @item
13407 package @code{Metrics} for command METRIC
13408 (invoking @code{^gnatmetric^gnatmetric^})
13409
13410 @item
13411 package @code{Pretty_Printer} for command PP or PRETTY
13412 (invoking @code{^gnatpp^gnatpp^})
13413
13414 @item
13415 package @code{Gnatstub} for command STUB
13416 (invoking @code{^gnatstub^gnatstub^})
13417
13418 @item
13419 package @code{Cross_Reference} for command XREF (invoking
13420 @code{^gnatxref^gnatxref^})
13421
13422 @end itemize
13423
13424 @noindent
13425 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13426 a simple variable with a string list value. It contains ^switches^switches^
13427 for the invocation of @code{^gnatls^gnatls^}.
13428
13429 @smallexample @c projectfile
13430 @group
13431 project Proj1 is
13432    package gnatls is
13433       for ^Switches^Switches^
13434           use ("^-a^-a^",
13435                "^-v^-v^");
13436    end gnatls;
13437 end Proj1;
13438 @end group
13439 @end smallexample
13440
13441 @noindent
13442 All other packages have two attribute @code{^Switches^Switches^} and
13443 @code{^Default_Switches^Default_Switches^}.
13444
13445 @noindent
13446 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13447 source file name, that has a string list value: the ^switches^switches^ to be
13448 used when the tool corresponding to the package is invoked for the specific
13449 source file.
13450
13451 @noindent
13452 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13453 indexed by  the programming language that has a string list value.
13454 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13455 ^switches^switches^ for the invocation of the tool corresponding
13456 to the package, except if a specific @code{^Switches^Switches^} attribute
13457 is specified for the source file.
13458
13459 @smallexample @c projectfile
13460 @group
13461 project Proj is
13462
13463    for Source_Dirs use ("./**");
13464
13465    package gnatls is
13466       for ^Switches^Switches^ use
13467           ("^-a^-a^",
13468            "^-v^-v^");
13469    end gnatls;
13470 @end group
13471 @group
13472
13473    package Compiler is
13474       for ^Default_Switches^Default_Switches^ ("Ada")
13475           use ("^-gnatv^-gnatv^",
13476                "^-gnatwa^-gnatwa^");
13477    end Binder;
13478 @end group
13479 @group
13480
13481    package Binder is
13482       for ^Default_Switches^Default_Switches^ ("Ada")
13483           use ("^-C^-C^",
13484                "^-e^-e^");
13485    end Binder;
13486 @end group
13487 @group
13488
13489    package Linker is
13490       for ^Default_Switches^Default_Switches^ ("Ada")
13491           use ("^-C^-C^");
13492       for ^Switches^Switches^ ("main.adb")
13493           use ("^-C^-C^",
13494                "^-v^-v^",
13495                "^-v^-v^");
13496    end Linker;
13497 @end group
13498 @group
13499
13500    package Finder is
13501       for ^Default_Switches^Default_Switches^ ("Ada")
13502            use ("^-a^-a^",
13503                 "^-f^-f^");
13504    end Finder;
13505 @end group
13506 @group
13507
13508    package Cross_Reference is
13509       for ^Default_Switches^Default_Switches^ ("Ada")
13510           use ("^-a^-a^",
13511                "^-f^-f^",
13512                "^-d^-d^",
13513                "^-u^-u^");
13514    end Cross_Reference;
13515 end Proj;
13516 @end group
13517 @end smallexample
13518
13519 @noindent
13520 With the above project file, commands such as
13521
13522 @smallexample
13523    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13524    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13525    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13526    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13527    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13528 @end smallexample
13529
13530 @noindent
13531 will set up the environment properly and invoke the tool with the switches
13532 found in the package corresponding to the tool:
13533 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13534 except @code{^Switches^Switches^ ("main.adb")}
13535 for @code{^gnatlink^gnatlink^}.
13536
13537 @ifclear vms
13538 @node Glide and Project Files
13539 @subsection Glide and Project Files
13540
13541 @noindent
13542 Glide will automatically recognize the @file{.gpr} extension for
13543 project files, and will
13544 convert them to its own internal format automatically. However, it
13545 doesn't provide a syntax-oriented editor for modifying these
13546 files.
13547 The project file will be loaded as text when you select the menu item
13548 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13549 You can edit this text and save the @file{gpr} file;
13550 when you next select this project file in Glide it
13551 will be automatically reloaded.
13552 @end ifclear
13553
13554 @c **********************
13555 @node An Extended Example
13556 @section An Extended Example
13557
13558 @noindent
13559 Suppose that we have two programs, @var{prog1} and @var{prog2},
13560 whose sources are in corresponding directories. We would like
13561 to build them with a single @command{gnatmake} command, and we want to place
13562 their object files into @file{build} subdirectories of the source directories.
13563 Furthermore, we want to have to have two separate subdirectories
13564 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13565 the object files compiled with different set of compilation flags.
13566
13567 In other words, we have the following structure:
13568
13569 @smallexample
13570 @group
13571    main
13572      |- prog1
13573      |    |- build
13574      |         | debug
13575      |         | release
13576      |- prog2
13577           |- build
13578                | debug
13579                | release
13580 @end group
13581 @end smallexample
13582
13583 @noindent
13584 Here are the project files that we must place in a directory @file{main}
13585 to maintain this structure:
13586
13587 @enumerate
13588
13589 @item We create a @code{Common} project with a package @code{Compiler} that
13590 specifies the compilation ^switches^switches^:
13591
13592 @smallexample
13593 File "common.gpr":
13594 @group
13595 @b{project} Common @b{is}
13596
13597    @b{for} Source_Dirs @b{use} (); -- No source files
13598 @end group
13599
13600 @group
13601    @b{type} Build_Type @b{is} ("release", "debug");
13602    Build : Build_Type := External ("BUILD", "debug");
13603 @end group
13604 @group
13605    @b{package} Compiler @b{is}
13606       @b{case} Build @b{is}
13607          @b{when} "release" =>
13608            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13609                    @b{use} ("^-O2^-O2^");
13610          @b{when} "debug"   =>
13611            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13612                    @b{use} ("^-g^-g^");
13613       @b{end case};
13614    @b{end} Compiler;
13615
13616 @b{end} Common;
13617 @end group
13618 @end smallexample
13619
13620 @item We create separate projects for the two programs:
13621
13622 @smallexample
13623 @group
13624 File "prog1.gpr":
13625
13626 @b{with} "common";
13627 @b{project} Prog1 @b{is}
13628
13629     @b{for} Source_Dirs @b{use} ("prog1");
13630     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13631
13632     @b{package} Compiler @b{renames} Common.Compiler;
13633
13634 @b{end} Prog1;
13635 @end group
13636 @end smallexample
13637
13638 @smallexample
13639 @group
13640 File "prog2.gpr":
13641
13642 @b{with} "common";
13643 @b{project} Prog2 @b{is}
13644
13645     @b{for} Source_Dirs @b{use} ("prog2");
13646     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13647
13648     @b{package} Compiler @b{renames} Common.Compiler;
13649
13650 @end group
13651 @b{end} Prog2;
13652 @end smallexample
13653
13654 @item We create a wrapping project @code{Main}:
13655
13656 @smallexample
13657 @group
13658 File "main.gpr":
13659
13660 @b{with} "common";
13661 @b{with} "prog1";
13662 @b{with} "prog2";
13663 @b{project} Main @b{is}
13664
13665    @b{package} Compiler @b{renames} Common.Compiler;
13666
13667 @b{end} Main;
13668 @end group
13669 @end smallexample
13670
13671 @item Finally we need to create a dummy procedure that @code{with}s (either
13672 explicitly or implicitly) all the sources of our two programs.
13673
13674 @end enumerate
13675
13676 @noindent
13677 Now we can build the programs using the command
13678
13679 @smallexample
13680    gnatmake ^-P^/PROJECT_FILE=^main dummy
13681 @end smallexample
13682
13683 @noindent
13684 for the Debug mode, or
13685
13686 @ifclear vms
13687 @smallexample
13688    gnatmake -Pmain -XBUILD=release
13689 @end smallexample
13690 @end ifclear
13691
13692 @ifset vms
13693 @smallexample
13694    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13695 @end smallexample
13696 @end ifset
13697
13698 @noindent
13699 for the Release mode.
13700
13701 @c ********************************
13702 @c * Project File Complete Syntax *
13703 @c ********************************
13704
13705 @node Project File Complete Syntax
13706 @section Project File Complete Syntax
13707
13708 @smallexample
13709 project ::=
13710   context_clause project_declaration
13711
13712 context_clause ::=
13713   @{with_clause@}
13714
13715 with_clause ::=
13716   @b{with} path_name @{ , path_name @} ;
13717
13718 path_name ::=
13719    string_literal
13720
13721 project_declaration ::=
13722   simple_project_declaration | project_extension
13723
13724 simple_project_declaration ::=
13725   @b{project} <project_>simple_name @b{is}
13726     @{declarative_item@}
13727   @b{end} <project_>simple_name;
13728
13729 project_extension ::=
13730   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13731     @{declarative_item@}
13732   @b{end} <project_>simple_name;
13733
13734 declarative_item ::=
13735   package_declaration |
13736   typed_string_declaration |
13737   other_declarative_item
13738
13739 package_declaration ::=
13740   package_specification | package_renaming
13741
13742 package_specification ::=
13743   @b{package} package_identifier @b{is}
13744     @{simple_declarative_item@}
13745   @b{end} package_identifier ;
13746
13747 package_identifier ::=
13748   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13749   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13750   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13751
13752 package_renaming ::==
13753   @b{package} package_identifier @b{renames}
13754        <project_>simple_name.package_identifier ;
13755
13756 typed_string_declaration ::=
13757   @b{type} <typed_string_>_simple_name @b{is}
13758    ( string_literal @{, string_literal@} );
13759
13760 other_declarative_item ::=
13761   attribute_declaration |
13762   typed_variable_declaration |
13763   variable_declaration |
13764   case_construction
13765
13766 attribute_declaration ::=
13767   full_associative_array_declaration |
13768   @b{for} attribute_designator @b{use} expression ;
13769
13770 full_associative_array_declaration ::=
13771   @b{for} <associative_array_attribute_>simple_name @b{use}
13772   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13773
13774 attribute_designator ::=
13775   <simple_attribute_>simple_name |
13776   <associative_array_attribute_>simple_name ( string_literal )
13777
13778 typed_variable_declaration ::=
13779   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13780
13781 variable_declaration ::=
13782   <variable_>simple_name := expression;
13783
13784 expression ::=
13785   term @{& term@}
13786
13787 term ::=
13788   literal_string |
13789   string_list |
13790   <variable_>name |
13791   external_value |
13792   attribute_reference
13793
13794 string_literal ::=
13795   (same as Ada)
13796
13797 string_list ::=
13798   ( <string_>expression @{ , <string_>expression @} )
13799
13800 external_value ::=
13801   @b{external} ( string_literal [, string_literal] )
13802
13803 attribute_reference ::=
13804   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13805
13806 attribute_prefix ::=
13807   @b{project} |
13808   <project_>simple_name | package_identifier |
13809   <project_>simple_name . package_identifier
13810
13811 case_construction ::=
13812   @b{case} <typed_variable_>name @b{is}
13813     @{case_item@}
13814   @b{end case} ;
13815
13816 case_item ::=
13817   @b{when} discrete_choice_list =>
13818       @{case_construction | attribute_declaration@}
13819
13820 discrete_choice_list ::=
13821   string_literal @{| string_literal@} |
13822   @b{others}
13823
13824 name ::=
13825   simple_name @{. simple_name@}
13826
13827 simple_name ::=
13828   identifier (same as Ada)
13829
13830 @end smallexample
13831
13832 @node The Cross-Referencing Tools gnatxref and gnatfind
13833 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13834 @findex gnatxref
13835 @findex gnatfind
13836
13837 @noindent
13838 The compiler generates cross-referencing information (unless
13839 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13840 This information indicates where in the source each entity is declared and
13841 referenced. Note that entities in package Standard are not included, but
13842 entities in all other predefined units are included in the output.
13843
13844 Before using any of these two tools, you need to compile successfully your
13845 application, so that GNAT gets a chance to generate the cross-referencing
13846 information.
13847
13848 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13849 information to provide the user with the capability to easily locate the
13850 declaration and references to an entity. These tools are quite similar,
13851 the difference being that @code{gnatfind} is intended for locating
13852 definitions and/or references to a specified entity or entities, whereas
13853 @code{gnatxref} is oriented to generating a full report of all
13854 cross-references.
13855
13856 To use these tools, you must not compile your application using the
13857 @option{-gnatx} switch on the @command{gnatmake} command line
13858 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13859 information will not be generated.
13860
13861 @menu
13862 * gnatxref Switches::
13863 * gnatfind Switches::
13864 * Project Files for gnatxref and gnatfind::
13865 * Regular Expressions in gnatfind and gnatxref::
13866 * Examples of gnatxref Usage::
13867 * Examples of gnatfind Usage::
13868 @end menu
13869
13870 @node gnatxref Switches
13871 @section @code{gnatxref} Switches
13872
13873 @noindent
13874 The command invocation for @code{gnatxref} is:
13875 @smallexample
13876 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13877 @end smallexample
13878
13879 @noindent
13880 where
13881
13882 @table @code
13883 @item sourcefile1, sourcefile2
13884 identifies the source files for which a report is to be generated. The
13885 ``with''ed units will be processed too. You must provide at least one file.
13886
13887 These file names are considered to be regular expressions, so for instance
13888 specifying @file{source*.adb} is the same as giving every file in the current
13889 directory whose name starts with @file{source} and whose extension is
13890 @file{adb}.
13891
13892 You shouldn't specify any directory name, just base names. @command{gnatxref}
13893 and @command{gnatfind} will be able to locate these files by themselves using
13894 the source path. If you specify directories, no result is produced.
13895
13896 @end table
13897
13898 @noindent
13899 The switches can be :
13900 @table @option
13901 @c !sort!
13902 @item ^-a^/ALL_FILES^
13903 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13904 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13905 the read-only files found in the library search path. Otherwise, these files
13906 will be ignored. This option can be used to protect Gnat sources or your own
13907 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13908 much faster, and their output much smaller. Read-only here refers to access
13909 or permissions status in the file system for the current user.
13910
13911 @item -aIDIR
13912 @cindex @option{-aIDIR} (@command{gnatxref})
13913 When looking for source files also look in directory DIR. The order in which
13914 source file search is undertaken is the same as for @command{gnatmake}.
13915
13916 @item -aODIR
13917 @cindex @option{-aODIR} (@command{gnatxref})
13918 When searching for library and object files, look in directory
13919 DIR. The order in which library files are searched is the same as for
13920 @command{gnatmake}.
13921
13922 @item -nostdinc
13923 @cindex @option{-nostdinc} (@command{gnatxref})
13924 Do not look for sources in the system default directory.
13925
13926 @item -nostdlib
13927 @cindex @option{-nostdlib} (@command{gnatxref})
13928 Do not look for library files in the system default directory.
13929
13930 @item --RTS=@var{rts-path}
13931 @cindex @option{--RTS} (@command{gnatxref})
13932 Specifies the default location of the runtime library. Same meaning as the
13933 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13934
13935 @item ^-d^/DERIVED_TYPES^
13936 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13937 If this switch is set @code{gnatxref} will output the parent type
13938 reference for each matching derived types.
13939
13940 @item ^-f^/FULL_PATHNAME^
13941 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13942 If this switch is set, the output file names will be preceded by their
13943 directory (if the file was found in the search path). If this switch is
13944 not set, the directory will not be printed.
13945
13946 @item ^-g^/IGNORE_LOCALS^
13947 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13948 If this switch is set, information is output only for library-level
13949 entities, ignoring local entities. The use of this switch may accelerate
13950 @code{gnatfind} and @code{gnatxref}.
13951
13952 @item -IDIR
13953 @cindex @option{-IDIR} (@command{gnatxref})
13954 Equivalent to @samp{-aODIR -aIDIR}.
13955
13956 @item -pFILE
13957 @cindex @option{-pFILE} (@command{gnatxref})
13958 Specify a project file to use @xref{Project Files}. These project files are
13959 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13960 project files, you should use gnatxref through the GNAT driver
13961 (@command{gnat xref -Pproject}).
13962
13963 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13964 project file in the current directory.
13965
13966 If a project file is either specified or found by the tools, then the content
13967 of the source directory and object directory lines are added as if they
13968 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13969 and @samp{^-aO^OBJECT_SEARCH^}.
13970 @item ^-u^/UNUSED^
13971 Output only unused symbols. This may be really useful if you give your
13972 main compilation unit on the command line, as @code{gnatxref} will then
13973 display every unused entity and 'with'ed package.
13974
13975 @ifclear vms
13976 @item -v
13977 Instead of producing the default output, @code{gnatxref} will generate a
13978 @file{tags} file that can be used by vi. For examples how to use this
13979 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13980 to the standard output, thus you will have to redirect it to a file.
13981 @end ifclear
13982
13983 @end table
13984
13985 @noindent
13986 All these switches may be in any order on the command line, and may even
13987 appear after the file names. They need not be separated by spaces, thus
13988 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13989 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13990
13991 @node gnatfind Switches
13992 @section @code{gnatfind} Switches
13993
13994 @noindent
13995 The command line for @code{gnatfind} is:
13996
13997 @smallexample
13998 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13999       [file1 file2 ...]
14000 @end smallexample
14001
14002 @noindent
14003 where
14004
14005 @table @code
14006 @item pattern
14007 An entity will be output only if it matches the regular expression found
14008 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14009
14010 Omitting the pattern is equivalent to specifying @samp{*}, which
14011 will match any entity. Note that if you do not provide a pattern, you
14012 have to provide both a sourcefile and a line.
14013
14014 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14015 for matching purposes. At the current time there is no support for
14016 8-bit codes other than Latin-1, or for wide characters in identifiers.
14017
14018 @item sourcefile
14019 @code{gnatfind} will look for references, bodies or declarations
14020 of symbols referenced in @file{sourcefile}, at line @samp{line}
14021 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14022 for syntax examples.
14023
14024 @item line
14025 is a decimal integer identifying the line number containing
14026 the reference to the entity (or entities) to be located.
14027
14028 @item column
14029 is a decimal integer identifying the exact location on the
14030 line of the first character of the identifier for the
14031 entity reference. Columns are numbered from 1.
14032
14033 @item file1 file2 ...
14034 The search will be restricted to these source files. If none are given, then
14035 the search will be done for every library file in the search path.
14036 These file must appear only after the pattern or sourcefile.
14037
14038 These file names are considered to be regular expressions, so for instance
14039 specifying 'source*.adb' is the same as giving every file in the current
14040 directory whose name starts with 'source' and whose extension is 'adb'.
14041
14042 The location of the spec of the entity will always be displayed, even if it
14043 isn't in one of file1, file2,... The occurrences of the entity in the
14044 separate units of the ones given on the command line will also be displayed.
14045
14046 Note that if you specify at least one file in this part, @code{gnatfind} may
14047 sometimes not be able to find the body of the subprograms...
14048
14049 @end table
14050
14051 @noindent
14052 At least one of 'sourcefile' or 'pattern' has to be present on
14053 the command line.
14054
14055 The following switches are available:
14056 @table @option
14057 @c !sort!
14058
14059 @item ^-a^/ALL_FILES^
14060 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14061 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14062 the read-only files found in the library search path. Otherwise, these files
14063 will be ignored. This option can be used to protect Gnat sources or your own
14064 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14065 much faster, and their output much smaller. Read-only here refers to access
14066 or permission status in the file system for the current user.
14067
14068 @item -aIDIR
14069 @cindex @option{-aIDIR} (@command{gnatfind})
14070 When looking for source files also look in directory DIR. The order in which
14071 source file search is undertaken is the same as for @command{gnatmake}.
14072
14073 @item -aODIR
14074 @cindex @option{-aODIR} (@command{gnatfind})
14075 When searching for library and object files, look in directory
14076 DIR. The order in which library files are searched is the same as for
14077 @command{gnatmake}.
14078
14079 @item -nostdinc
14080 @cindex @option{-nostdinc} (@command{gnatfind})
14081 Do not look for sources in the system default directory.
14082
14083 @item -nostdlib
14084 @cindex @option{-nostdlib} (@command{gnatfind})
14085 Do not look for library files in the system default directory.
14086
14087 @item --RTS=@var{rts-path}
14088 @cindex @option{--RTS} (@command{gnatfind})
14089 Specifies the default location of the runtime library. Same meaning as the
14090 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14091
14092 @item ^-d^/DERIVED_TYPE_INFORMATION^
14093 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14094 If this switch is set, then @code{gnatfind} will output the parent type
14095 reference for each matching derived types.
14096
14097 @item ^-e^/EXPRESSIONS^
14098 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14099 By default, @code{gnatfind} accept the simple regular expression set for
14100 @samp{pattern}. If this switch is set, then the pattern will be
14101 considered as full Unix-style regular expression.
14102
14103 @item ^-f^/FULL_PATHNAME^
14104 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14105 If this switch is set, the output file names will be preceded by their
14106 directory (if the file was found in the search path). If this switch is
14107 not set, the directory will not be printed.
14108
14109 @item ^-g^/IGNORE_LOCALS^
14110 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14111 If this switch is set, information is output only for library-level
14112 entities, ignoring local entities. The use of this switch may accelerate
14113 @code{gnatfind} and @code{gnatxref}.
14114
14115 @item -IDIR
14116 @cindex @option{-IDIR} (@command{gnatfind})
14117 Equivalent to @samp{-aODIR -aIDIR}.
14118
14119 @item -pFILE
14120 @cindex @option{-pFILE} (@command{gnatfind})
14121 Specify a project file (@pxref{Project Files}) to use.
14122 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14123 project file in the current directory.
14124
14125 If a project file is either specified or found by the tools, then the content
14126 of the source directory and object directory lines are added as if they
14127 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14128 @samp{^-aO^/OBJECT_SEARCH^}.
14129
14130 @item ^-r^/REFERENCES^
14131 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14132 By default, @code{gnatfind} will output only the information about the
14133 declaration, body or type completion of the entities. If this switch is
14134 set, the @code{gnatfind} will locate every reference to the entities in
14135 the files specified on the command line (or in every file in the search
14136 path if no file is given on the command line).
14137
14138 @item ^-s^/PRINT_LINES^
14139 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14140 If this switch is set, then @code{gnatfind} will output the content
14141 of the Ada source file lines were the entity was found.
14142
14143 @item ^-t^/TYPE_HIERARCHY^
14144 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14145 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14146 the specified type. It act like -d option but recursively from parent
14147 type to parent type. When this switch is set it is not possible to
14148 specify more than one file.
14149
14150 @end table
14151
14152 @noindent
14153 All these switches may be in any order on the command line, and may even
14154 appear after the file names. They need not be separated by spaces, thus
14155 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14156 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14157
14158 As stated previously, gnatfind will search in every directory in the
14159 search path. You can force it to look only in the current directory if
14160 you specify @code{*} at the end of the command line.
14161
14162 @node Project Files for gnatxref and gnatfind
14163 @section Project Files for @command{gnatxref} and @command{gnatfind}
14164
14165 @noindent
14166 Project files allow a programmer to specify how to compile its
14167 application, where to find sources, etc.  These files are used
14168 @ifclear vms
14169 primarily by the Glide Ada mode, but they can also be used
14170 @end ifclear
14171 by the two tools
14172 @code{gnatxref} and @code{gnatfind}.
14173
14174 A project file name must end with @file{.gpr}. If a single one is
14175 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14176 extract the information from it. If multiple project files are found, none of
14177 them is read, and you have to use the @samp{-p} switch to specify the one
14178 you want to use.
14179
14180 The following lines can be included, even though most of them have default
14181 values which can be used in most cases.
14182 The lines can be entered in any order in the file.
14183 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14184 each line. If you have multiple instances, only the last one is taken into
14185 account.
14186
14187 @table @code
14188 @item src_dir=DIR
14189 [default: @code{"^./^[]^"}]
14190 specifies a directory where to look for source files. Multiple @code{src_dir}
14191 lines can be specified and they will be searched in the order they
14192 are specified.
14193
14194 @item obj_dir=DIR
14195 [default: @code{"^./^[]^"}]
14196 specifies a directory where to look for object and library files. Multiple
14197 @code{obj_dir} lines can be specified, and they will be searched in the order
14198 they are specified
14199
14200 @item comp_opt=SWITCHES
14201 [default: @code{""}]
14202 creates a variable which can be referred to subsequently by using
14203 the @code{$@{comp_opt@}} notation. This is intended to store the default
14204 switches given to @command{gnatmake} and @command{gcc}.
14205
14206 @item bind_opt=SWITCHES
14207 [default: @code{""}]
14208 creates a variable which can be referred to subsequently by using
14209 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14210 switches given to @command{gnatbind}.
14211
14212 @item link_opt=SWITCHES
14213 [default: @code{""}]
14214 creates a variable which can be referred to subsequently by using
14215 the @samp{$@{link_opt@}} notation. This is intended to store the default
14216 switches given to @command{gnatlink}.
14217
14218 @item main=EXECUTABLE
14219 [default: @code{""}]
14220 specifies the name of the executable for the application. This variable can
14221 be referred to in the following lines by using the @samp{$@{main@}} notation.
14222
14223 @ifset vms
14224 @item comp_cmd=COMMAND
14225 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14226 @end ifset
14227 @ifclear vms
14228 @item comp_cmd=COMMAND
14229 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14230 @end ifclear
14231 specifies the command used to compile a single file in the application.
14232
14233 @ifset vms
14234 @item make_cmd=COMMAND
14235 [default: @code{"GNAT MAKE $@{main@}
14236 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14237 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14238 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14239 @end ifset
14240 @ifclear vms
14241 @item make_cmd=COMMAND
14242 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14243  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14244  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14245 @end ifclear
14246 specifies the command used to recompile the whole application.
14247
14248 @item run_cmd=COMMAND
14249 [default: @code{"$@{main@}"}]
14250 specifies the command used to run the application.
14251
14252 @item debug_cmd=COMMAND
14253 [default: @code{"gdb $@{main@}"}]
14254 specifies the command used to debug the application
14255
14256 @end table
14257
14258 @noindent
14259 @command{gnatxref} and @command{gnatfind} only take into account the
14260 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14261
14262 @node Regular Expressions in gnatfind and gnatxref
14263 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14264
14265 @noindent
14266 As specified in the section about @command{gnatfind}, the pattern can be a
14267 regular expression. Actually, there are to set of regular expressions
14268 which are recognized by the program :
14269
14270 @table @code
14271 @item globbing patterns
14272 These are the most usual regular expression. They are the same that you
14273 generally used in a Unix shell command line, or in a DOS session.
14274
14275 Here is a more formal grammar :
14276 @smallexample
14277 @group
14278 @iftex
14279 @leftskip=.5cm
14280 @end iftex
14281 regexp ::= term
14282 term   ::= elmt            -- matches elmt
14283 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14284 term   ::= *               -- any string of 0 or more characters
14285 term   ::= ?               -- matches any character
14286 term   ::= [char @{char@}] -- matches any character listed
14287 term   ::= [char - char]   -- matches any character in range
14288 @end group
14289 @end smallexample
14290
14291 @item full regular expression
14292 The second set of regular expressions is much more powerful. This is the
14293 type of regular expressions recognized by utilities such a @file{grep}.
14294
14295 The following is the form of a regular expression, expressed in Ada
14296 reference manual style BNF is as follows
14297
14298 @smallexample
14299 @iftex
14300 @leftskip=.5cm
14301 @end iftex
14302 @group
14303 regexp ::= term @{| term@} -- alternation (term or term ...)
14304
14305 term ::= item @{item@}     -- concatenation (item then item)
14306
14307 item ::= elmt              -- match elmt
14308 item ::= elmt *            -- zero or more elmt's
14309 item ::= elmt +            -- one or more elmt's
14310 item ::= elmt ?            -- matches elmt or nothing
14311 @end group
14312 @group
14313 elmt ::= nschar            -- matches given character
14314 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14315 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14316 elmt ::= [char - char]     -- matches chars in given range
14317 elmt ::= \ char            -- matches given character
14318 elmt ::= .                 -- matches any single character
14319 elmt ::= ( regexp )        -- parens used for grouping
14320
14321 char ::= any character, including special characters
14322 nschar ::= any character except ()[].*+?^^^
14323 @end group
14324 @end smallexample
14325
14326 Following are a few examples :
14327
14328 @table @samp
14329 @item abcde|fghi
14330 will match any of the two strings 'abcde' and 'fghi'.
14331
14332 @item abc*d
14333 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14334
14335 @item [a-z]+
14336 will match any string which has only lowercase characters in it (and at
14337 least one character
14338
14339 @end table
14340 @end table
14341
14342 @node Examples of gnatxref Usage
14343 @section Examples of @code{gnatxref} Usage
14344
14345 @subsection General Usage
14346
14347 @noindent
14348 For the following examples, we will consider the following units :
14349
14350 @smallexample @c ada
14351 @group
14352 @cartouche
14353 main.ads:
14354 1: with Bar;
14355 2: package Main is
14356 3:     procedure Foo (B : in Integer);
14357 4:     C : Integer;
14358 5: private
14359 6:     D : Integer;
14360 7: end Main;
14361
14362 main.adb:
14363 1: package body Main is
14364 2:     procedure Foo (B : in Integer) is
14365 3:     begin
14366 4:        C := B;
14367 5:        D := B;
14368 6:        Bar.Print (B);
14369 7:        Bar.Print (C);
14370 8:     end Foo;
14371 9: end Main;
14372
14373 bar.ads:
14374 1: package Bar is
14375 2:     procedure Print (B : Integer);
14376 3: end bar;
14377 @end cartouche
14378 @end group
14379 @end smallexample
14380
14381 @table @code
14382
14383 @noindent
14384 The first thing to do is to recompile your application (for instance, in
14385 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14386 the cross-referencing information.
14387 You can then issue any of the following commands:
14388
14389 @item gnatxref main.adb
14390 @code{gnatxref} generates cross-reference information for main.adb
14391 and every unit 'with'ed by main.adb.
14392
14393 The output would be:
14394 @smallexample
14395 @iftex
14396 @leftskip=0cm
14397 @end iftex
14398 B                                                      Type: Integer
14399   Decl: bar.ads           2:22
14400 B                                                      Type: Integer
14401   Decl: main.ads          3:20
14402   Body: main.adb          2:20
14403   Ref:  main.adb          4:13     5:13     6:19
14404 Bar                                                    Type: Unit
14405   Decl: bar.ads           1:9
14406   Ref:  main.adb          6:8      7:8
14407        main.ads           1:6
14408 C                                                      Type: Integer
14409   Decl: main.ads          4:5
14410   Modi: main.adb          4:8
14411   Ref:  main.adb          7:19
14412 D                                                      Type: Integer
14413   Decl: main.ads          6:5
14414   Modi: main.adb          5:8
14415 Foo                                                    Type: Unit
14416   Decl: main.ads          3:15
14417   Body: main.adb          2:15
14418 Main                                                    Type: Unit
14419   Decl: main.ads          2:9
14420   Body: main.adb          1:14
14421 Print                                                   Type: Unit
14422   Decl: bar.ads           2:15
14423   Ref:  main.adb          6:12     7:12
14424 @end smallexample
14425
14426 @noindent
14427 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14428 its body is in main.adb, line 1, column 14 and is not referenced any where.
14429
14430 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14431 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14432
14433 @item gnatxref package1.adb package2.ads
14434 @code{gnatxref} will generates cross-reference information for
14435 package1.adb, package2.ads and any other package 'with'ed by any
14436 of these.
14437
14438 @end table
14439
14440 @ifclear vms
14441 @subsection Using gnatxref with vi
14442
14443 @code{gnatxref} can generate a tags file output, which can be used
14444 directly from @file{vi}. Note that the standard version of @file{vi}
14445 will not work properly with overloaded symbols. Consider using another
14446 free implementation of @file{vi}, such as @file{vim}.
14447
14448 @smallexample
14449 $ gnatxref -v gnatfind.adb > tags
14450 @end smallexample
14451
14452 @noindent
14453 will generate the tags file for @code{gnatfind} itself (if the sources
14454 are in the search path!).
14455
14456 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14457 (replacing @i{entity} by whatever you are looking for), and vi will
14458 display a new file with the corresponding declaration of entity.
14459 @end ifclear
14460
14461 @node Examples of gnatfind Usage
14462 @section Examples of @code{gnatfind} Usage
14463
14464 @table @code
14465
14466 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14467 Find declarations for all entities xyz referenced at least once in
14468 main.adb. The references are search in every library file in the search
14469 path.
14470
14471 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14472 switch is set)
14473
14474 The output will look like:
14475 @smallexample
14476 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14477 ^directory/^[directory]^main.adb:24:10: xyz <= body
14478 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14479 @end smallexample
14480
14481 @noindent
14482 that is to say, one of the entities xyz found in main.adb is declared at
14483 line 12 of main.ads (and its body is in main.adb), and another one is
14484 declared at line 45 of foo.ads
14485
14486 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14487 This is the same command as the previous one, instead @code{gnatfind} will
14488 display the content of the Ada source file lines.
14489
14490 The output will look like:
14491
14492 @smallexample
14493 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14494    procedure xyz;
14495 ^directory/^[directory]^main.adb:24:10: xyz <= body
14496    procedure xyz is
14497 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14498    xyz : Integer;
14499 @end smallexample
14500
14501 @noindent
14502 This can make it easier to find exactly the location your are looking
14503 for.
14504
14505 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14506 Find references to all entities containing an x that are
14507 referenced on line 123 of main.ads.
14508 The references will be searched only in main.ads and foo.adb.
14509
14510 @item gnatfind main.ads:123
14511 Find declarations and bodies for all entities that are referenced on
14512 line 123 of main.ads.
14513
14514 This is the same as @code{gnatfind "*":main.adb:123}.
14515
14516 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14517 Find the declaration for the entity referenced at column 45 in
14518 line 123 of file main.adb in directory mydir. Note that it
14519 is usual to omit the identifier name when the column is given,
14520 since the column position identifies a unique reference.
14521
14522 The column has to be the beginning of the identifier, and should not
14523 point to any character in the middle of the identifier.
14524
14525 @end table
14526
14527 @c *********************************
14528 @node The GNAT Pretty-Printer gnatpp
14529 @chapter The GNAT Pretty-Printer @command{gnatpp}
14530 @findex gnatpp
14531 @cindex Pretty-Printer
14532
14533 @noindent
14534 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14535 for source reformatting / pretty-printing.
14536 It takes an Ada source file as input and generates a reformatted
14537 version as output.
14538 You can specify various style directives via switches; e.g.,
14539 identifier case conventions, rules of indentation, and comment layout.
14540
14541 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14542 tree for the input source and thus requires the input to be syntactically and
14543 semantically legal.
14544 If this condition is not met, @command{gnatpp} will terminate with an
14545 error message; no output file will be generated.
14546
14547 If the compilation unit
14548 contained in the input source depends semantically upon units located
14549 outside the current directory, you have to provide the source search path
14550 when invoking @command{gnatpp}, if these units are contained in files with
14551 names that do not follow the GNAT file naming rules, you have to provide
14552 the configuration file describing the corresponding naming scheme;
14553 see the description of the @command{gnatpp}
14554 switches below. Another possibility is to use a project file and to
14555 call @command{gnatpp} through the @command{gnat} driver
14556
14557 The @command{gnatpp} command has the form
14558
14559 @smallexample
14560 $ gnatpp [@var{switches}] @var{filename}
14561 @end smallexample
14562
14563 @noindent
14564 where
14565 @itemize @bullet
14566 @item
14567 @var{switches} is an optional sequence of switches defining such properties as
14568 the formatting rules, the source search path, and the destination for the
14569 output source file
14570
14571 @item
14572 @var{filename} is the name (including the extension) of the source file to
14573 reformat; ``wildcards'' or several file names on the same gnatpp command are
14574 allowed.  The file name may contain path information; it does not have to
14575 follow the GNAT file naming rules
14576 @end itemize
14577
14578 @menu
14579 * Switches for gnatpp::
14580 * Formatting Rules::
14581 @end menu
14582
14583 @node Switches for gnatpp
14584 @section Switches for @command{gnatpp}
14585
14586 @noindent
14587 The following subsections describe the various switches accepted by
14588 @command{gnatpp}, organized by category.
14589
14590 @ifclear vms
14591 You specify a switch by supplying a name and generally also a value.
14592 In many cases the values for a switch with a given name are incompatible with
14593 each other
14594 (for example the switch that controls the casing of a reserved word may have
14595 exactly one value: upper case, lower case, or
14596 mixed case) and thus exactly one such switch can be in effect for an
14597 invocation of @command{gnatpp}.
14598 If more than one is supplied, the last one is used.
14599 However, some values for the same switch are mutually compatible.
14600 You may supply several such switches to @command{gnatpp}, but then
14601 each must be specified in full, with both the name and the value.
14602 Abbreviated forms (the name appearing once, followed by each value) are
14603 not permitted.
14604 For example, to set
14605 the alignment of the assignment delimiter both in declarations and in
14606 assignment statements, you must write @option{-A2A3}
14607 (or @option{-A2 -A3}), but not @option{-A23}.
14608 @end ifclear
14609
14610 @ifset vms
14611 In many cases the set of options for a given qualifier are incompatible with
14612 each other (for example the qualifier that controls the casing of a reserved
14613 word may have exactly one option, which specifies either upper case, lower
14614 case, or mixed case), and thus exactly one such option can be in effect for
14615 an invocation of @command{gnatpp}.
14616 If more than one is supplied, the last one is used.
14617 However, some qualifiers have options that are mutually compatible,
14618 and then you may then supply several such options when invoking
14619 @command{gnatpp}.
14620 @end ifset
14621
14622 In most cases, it is obvious whether or not the
14623 ^values for a switch with a given name^options for a given qualifier^
14624 are compatible with each other.
14625 When the semantics might not be evident, the summaries below explicitly
14626 indicate the effect.
14627
14628 @menu
14629 * Alignment Control::
14630 * Casing Control::
14631 * Construct Layout Control::
14632 * General Text Layout Control::
14633 * Other Formatting Options::
14634 * Setting the Source Search Path::
14635 * Output File Control::
14636 * Other gnatpp Switches::
14637 @end menu
14638
14639 @node Alignment Control
14640 @subsection Alignment Control
14641 @cindex Alignment control in @command{gnatpp}
14642
14643 @noindent
14644 Programs can be easier to read if certain constructs are vertically aligned.
14645 By default all alignments are set ON.
14646 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14647 OFF, and then use one or more of the other
14648 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14649 to activate alignment for specific constructs.
14650
14651 @table @option
14652 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14653
14654 @ifset vms
14655 @item /ALIGN=ON
14656 Set all alignments to ON
14657 @end ifset
14658
14659 @item ^-A0^/ALIGN=OFF^
14660 Set all alignments to OFF
14661
14662 @item ^-A1^/ALIGN=COLONS^
14663 Align @code{:} in declarations
14664
14665 @item ^-A2^/ALIGN=DECLARATIONS^
14666 Align @code{:=} in initializations in declarations
14667
14668 @item ^-A3^/ALIGN=STATEMENTS^
14669 Align @code{:=} in assignment statements
14670
14671 @item ^-A4^/ALIGN=ARROWS^
14672 Align @code{=>} in associations
14673
14674 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14675 Align @code{at} keywords in the component clauses in record
14676 representation clauses
14677 @end table
14678
14679 @noindent
14680 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14681 is allowed.
14682
14683 @node Casing Control
14684 @subsection Casing Control
14685 @cindex Casing control in @command{gnatpp}
14686
14687 @noindent
14688 @command{gnatpp} allows you to specify the casing for reserved words,
14689 pragma names, attribute designators and identifiers.
14690 For identifiers you may define a
14691 general rule for name casing but also override this rule
14692 via a set of dictionary files.
14693
14694 Three types of casing are supported: lower case, upper case, and mixed case.
14695 Lower and upper case are self-explanatory (but since some letters in
14696 Latin1 and other GNAT-supported character sets
14697 exist only in lower-case form, an upper case conversion will have no
14698 effect on them.)
14699 ``Mixed case'' means that the first letter, and also each letter immediately
14700 following an underscore, are converted to their uppercase forms;
14701 all the other letters are converted to their lowercase forms.
14702
14703 @table @option
14704 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14705 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14706 Attribute designators are lower case
14707
14708 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14709 Attribute designators are upper case
14710
14711 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14712 Attribute designators are mixed case (this is the default)
14713
14714 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14715 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14716 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14717 lower case (this is the default)
14718
14719 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14720 Keywords are upper case
14721
14722 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14723 @item ^-nD^/NAME_CASING=AS_DECLARED^
14724 Name casing for defining occurrences are as they appear in the source file
14725 (this is the default)
14726
14727 @item ^-nU^/NAME_CASING=UPPER_CASE^
14728 Names are in upper case
14729
14730 @item ^-nL^/NAME_CASING=LOWER_CASE^
14731 Names are in lower case
14732
14733 @item ^-nM^/NAME_CASING=MIXED_CASE^
14734 Names are in mixed case
14735
14736 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14737 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14738 Pragma names are lower case
14739
14740 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14741 Pragma names are upper case
14742
14743 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14744 Pragma names are mixed case (this is the default)
14745
14746 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14747 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14748 Use @var{file} as a @emph{dictionary file} that defines
14749 the casing for a set of specified names,
14750 thereby overriding the effect on these names by
14751 any explicit or implicit
14752 ^-n^/NAME_CASING^ switch.
14753 To supply more than one dictionary file,
14754 use ^several @option{-D} switches^a list of files as options^.
14755
14756 @noindent
14757 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14758 to define the casing for the Ada predefined names and
14759 the names declared in the GNAT libraries.
14760
14761 @item ^-D-^/SPECIFIC_CASING^
14762 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14763 Do not use the default dictionary file;
14764 instead, use the casing
14765 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14766 dictionary file(s)
14767 @end table
14768
14769 @noindent
14770 The structure of a dictionary file, and details on the conventions
14771 used in the default dictionary file, are defined in @ref{Name Casing}.
14772
14773 The @option{^-D-^/SPECIFIC_CASING^} and
14774 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14775 compatible.
14776
14777 @node Construct Layout Control
14778 @subsection Construct Layout Control
14779 @cindex Layout control in @command{gnatpp}
14780
14781 @noindent
14782 This group of @command{gnatpp} switches controls the layout of comments and
14783 complex syntactic constructs.  See @ref{Formatting Comments} for details
14784 on their effect.
14785
14786 @table @option
14787 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14788 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14789 All the comments remain unchanged
14790
14791 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14792 GNAT-style comment line indentation (this is the default).
14793
14794 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14795 Reference-manual comment line indentation.
14796
14797 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14798 GNAT-style comment beginning
14799
14800 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14801 Reformat comment blocks
14802
14803 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14804 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14805 GNAT-style layout (this is the default)
14806
14807 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14808 Compact layout
14809
14810 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14811 Uncompact layout
14812
14813 @item ^-notab^/NOTABS^
14814 All the VT characters are removed from the comment text. All the HT characters
14815 are expanded with the sequences of space characters to get to the next tab
14816 stops.
14817
14818 @end table
14819
14820 @ifclear vms
14821 @noindent
14822 The @option{-c1} and @option{-c2} switches are incompatible.
14823 The @option{-c3} and @option{-c4} switches are compatible with each other and
14824 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14825 the other comment formatting switches.
14826
14827 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14828 @end ifclear
14829
14830 @ifset vms
14831 @noindent
14832 For the @option{/COMMENTS_LAYOUT} qualifier:
14833 @itemize @bullet
14834 @item
14835 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14836 @item
14837 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14838 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14839 @end itemize
14840
14841 @noindent
14842 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14843 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14844 @end ifset
14845
14846 @node General Text Layout Control
14847 @subsection General Text Layout Control
14848
14849 @noindent
14850 These switches allow control over line length and indentation.
14851
14852 @table @option
14853 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14854 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14855 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14856
14857 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14858 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14859 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14860
14861 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14862 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14863 Indentation level for continuation lines (relative to the line being
14864 continued), @i{nnn} from 1 .. 9.
14865 The default
14866 value is one less then the (normal) indentation level, unless the
14867 indentation is set to 1 (in which case the default value for continuation
14868 line indentation is also 1)
14869 @end table
14870
14871 @node Other Formatting Options
14872 @subsection Other Formatting Options
14873
14874 @noindent
14875 These switches control the inclusion of missing end/exit labels, and
14876 the indentation level in @b{case} statements.
14877
14878 @table @option
14879 @item ^-e^/NO_MISSED_LABELS^
14880 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14881 Do not insert missing end/exit labels. An end label is the name of
14882 a construct that may optionally be repeated at the end of the
14883 construct's declaration;
14884 e.g., the names of packages, subprograms, and tasks.
14885 An exit label is the name of a loop that may appear as target
14886 of an exit statement within the loop.
14887 By default, @command{gnatpp} inserts these end/exit labels when
14888 they are absent from the original source. This option suppresses such
14889 insertion, so that the formatted source reflects the original.
14890
14891 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14892 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14893 Insert a Form Feed character after a pragma Page.
14894
14895 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14896 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14897 Do not use an additional indentation level for @b{case} alternatives
14898 and variants if there are @i{nnn} or more (the default
14899 value is 10).
14900 If @i{nnn} is 0, an additional indentation level is
14901 used for @b{case} alternatives and variants regardless of their number.
14902 @end table
14903
14904 @node Setting the Source Search Path
14905 @subsection Setting the Source Search Path
14906
14907 @noindent
14908 To define the search path for the input source file, @command{gnatpp}
14909 uses the same switches as the GNAT compiler, with the same effects.
14910
14911 @table @option
14912 @item ^-I^/SEARCH=^@var{dir}
14913 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14914 The same as the corresponding gcc switch
14915
14916 @item ^-I-^/NOCURRENT_DIRECTORY^
14917 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14918 The same as the corresponding gcc switch
14919
14920 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14921 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14922 The same as the corresponding gcc switch
14923
14924 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14925 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14926 The same as the corresponding gcc switch
14927
14928 @end table
14929
14930 @node Output File Control
14931 @subsection Output File Control
14932
14933 @noindent
14934 By default the output is sent to the file whose name is obtained by appending
14935 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14936 (if the file with this name already exists, it is unconditionally overwritten).
14937 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14938 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14939 as output file.
14940 The output may be redirected by the following switches:
14941
14942 @table @option
14943 @item ^-pipe^/STANDARD_OUTPUT^
14944 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14945 Send the output to @code{Standard_Output}
14946
14947 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14948 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14949 Write the output into @var{output_file}.
14950 If @var{output_file} already exists, @command{gnatpp} terminates without
14951 reading or processing the input file.
14952
14953 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14954 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14955 Write the output into @var{output_file}, overwriting the existing file
14956 (if one is present).
14957
14958 @item ^-r^/REPLACE^
14959 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14960 Replace the input source file with the reformatted output, and copy the
14961 original input source into the file whose name is obtained by appending the
14962 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14963 If a file with this name already exists, @command{gnatpp} terminates without
14964 reading or processing the input file.
14965
14966 @item ^-rf^/OVERRIDING_REPLACE^
14967 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14968 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14969 already exists, it is overwritten.
14970
14971 @item ^-rnb^/NO_BACKUP^
14972 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14973 Replace the input source file with the reformatted output without
14974 creating any backup copy of the input source.
14975 @end table
14976
14977 @noindent
14978 Options @option{^-pipe^/STANDARD_OUTPUT^},
14979 @option{^-o^/OUTPUT^} and
14980 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14981 contains only one file to reformat
14982
14983 @node Other gnatpp Switches
14984 @subsection Other @code{gnatpp} Switches
14985
14986 @noindent
14987 The additional @command{gnatpp} switches are defined in this subsection.
14988
14989 @table @option
14990 @item ^-files @var{filename}^/FILES=@var{output_file}^
14991 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14992 Take the argument source files from the specified file. This file should be an
14993 ordinary textual file containing file names separated by spaces or
14994 line breaks. You can use this switch more then once in the same call to
14995 @command{gnatpp}. You also can combine this switch with explicit list of
14996 files.
14997
14998 @item ^-v^/VERBOSE^
14999 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15000 Verbose mode;
15001 @command{gnatpp} generates version information and then
15002 a trace of the actions it takes to produce or obtain the ASIS tree.
15003
15004 @item ^-w^/WARNINGS^
15005 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15006 Warning mode;
15007 @command{gnatpp} generates a warning whenever it can not provide
15008 a required layout in the result source.
15009 @end table
15010
15011 @node Formatting Rules
15012 @section Formatting Rules
15013
15014 @noindent
15015 The following subsections show how @command{gnatpp} treats ``white space'',
15016 comments, program layout, and name casing.
15017 They provide the detailed descriptions of the switches shown above.
15018
15019 @menu
15020 * White Space and Empty Lines::
15021 * Formatting Comments::
15022 * Construct Layout::
15023 * Name Casing::
15024 @end menu
15025
15026 @node White Space and Empty Lines
15027 @subsection White Space and Empty Lines
15028
15029 @noindent
15030 @command{gnatpp} does not have an option to control space characters.
15031 It will add or remove spaces according to the style illustrated by the
15032 examples in the @cite{Ada Reference Manual}.
15033
15034 The only format effectors
15035 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15036 that will appear in the output file are platform-specific line breaks,
15037 and also format effectors within (but not at the end of) comments.
15038 In particular, each horizontal tab character that is not inside
15039 a comment will be treated as a space and thus will appear in the
15040 output file as zero or more spaces depending on
15041 the reformatting of the line in which it appears.
15042 The only exception is a Form Feed character, which is inserted after a
15043 pragma @code{Page} when @option{-ff} is set.
15044
15045 The output file will contain no lines with trailing ``white space'' (spaces,
15046 format effectors).
15047
15048 Empty lines in the original source are preserved
15049 only if they separate declarations or statements.
15050 In such contexts, a
15051 sequence of two or more empty lines is replaced by exactly one empty line.
15052 Note that a blank line will be removed if it separates two ``comment blocks''
15053 (a comment block is a sequence of whole-line comments).
15054 In order to preserve a visual separation between comment blocks, use an
15055 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15056 Likewise, if for some reason you wish to have a sequence of empty lines,
15057 use a sequence of empty comments instead.
15058
15059 @node Formatting Comments
15060 @subsection Formatting Comments
15061
15062 @noindent
15063 Comments in Ada code are of two kinds:
15064 @itemize @bullet
15065 @item
15066 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15067 ``white space'') on a line
15068
15069 @item
15070 an @emph{end-of-line comment}, which follows some other Ada lexical element
15071 on the same line.
15072 @end itemize
15073
15074 @noindent
15075 The indentation of a whole-line comment is that of either
15076 the preceding or following line in
15077 the formatted source, depending on switch settings as will be described below.
15078
15079 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15080 between the end of the preceding Ada lexical element and the beginning
15081 of the comment as appear in the original source,
15082 unless either the comment has to be split to
15083 satisfy the line length limitation, or else the next line contains a
15084 whole line comment that is considered a continuation of this end-of-line
15085 comment (because it starts at the same position).
15086 In the latter two
15087 cases, the start of the end-of-line comment is moved right to the nearest
15088 multiple of the indentation level.
15089 This may result in a ``line overflow'' (the right-shifted comment extending
15090 beyond the maximum line length), in which case the comment is split as
15091 described below.
15092
15093 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15094 (GNAT-style comment line indentation)
15095 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15096 (reference-manual comment line indentation).
15097 With reference-manual style, a whole-line comment is indented as if it
15098 were a declaration or statement at the same place
15099 (i.e., according to the indentation of the preceding line(s)).
15100 With GNAT style, a whole-line comment that is immediately followed by an
15101 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15102 word @b{begin}, is indented based on the construct that follows it.
15103
15104 For example:
15105 @smallexample @c ada
15106 @cartouche
15107 if A then
15108     null;
15109        -- some comment
15110 else
15111    null;
15112 end if;
15113 @end cartouche
15114 @end smallexample
15115
15116 @noindent
15117 Reference-manual indentation produces:
15118
15119 @smallexample @c ada
15120 @cartouche
15121 if A then
15122    null;
15123    --  some comment
15124 else
15125    null;
15126 end if;
15127 @end cartouche
15128 @end smallexample
15129
15130 @noindent
15131 while GNAT-style indentation produces:
15132
15133 @smallexample @c ada
15134 @cartouche
15135 if A then
15136    null;
15137 --  some comment
15138 else
15139    null;
15140 end if;
15141 @end cartouche
15142 @end smallexample
15143
15144 @noindent
15145 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15146 (GNAT style comment beginning) has the following
15147 effect:
15148
15149 @itemize @bullet
15150 @item
15151 For each whole-line comment that does not end with two hyphens,
15152 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15153 to ensure that there are at least two spaces between these hyphens and the
15154 first non-blank character of the comment.
15155 @end itemize
15156
15157 @noindent
15158 For an end-of-line comment, if in the original source the next line is a
15159 whole-line comment that starts at the same position
15160 as the end-of-line comment,
15161 then the whole-line comment (and all whole-line comments
15162 that follow it and that start at the same position)
15163 will start at this position in the output file.
15164
15165 @noindent
15166 That is, if in the original source we have:
15167
15168 @smallexample @c ada
15169 @cartouche
15170 begin
15171 A := B + C;            --  B must be in the range Low1..High1
15172                        --  C must be in the range Low2..High2
15173              --B+C will be in the range Low1+Low2..High1+High2
15174 X := X + 1;
15175 @end cartouche
15176 @end smallexample
15177
15178 @noindent
15179 Then in the formatted source we get
15180
15181 @smallexample @c ada
15182 @cartouche
15183 begin
15184    A := B + C;            --  B must be in the range Low1..High1
15185                           --  C must be in the range Low2..High2
15186    --  B+C will be in the range Low1+Low2..High1+High2
15187    X := X + 1;
15188 @end cartouche
15189 @end smallexample
15190
15191 @noindent
15192 A comment that exceeds the line length limit will be split.
15193 Unless switch
15194 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15195 the line belongs to a reformattable block, splitting the line generates a
15196 @command{gnatpp} warning.
15197 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15198 comments may be reformatted in typical
15199 word processor style (that is, moving words between lines and putting as
15200 many words in a line as possible).
15201
15202 @node Construct Layout
15203 @subsection Construct Layout
15204
15205 @noindent
15206 In several cases the suggested layout in the Ada Reference Manual includes
15207 an extra level of indentation that many programmers prefer to avoid. The
15208 affected cases include:
15209
15210 @itemize @bullet
15211
15212 @item Record type declaration (RM 3.8)
15213
15214 @item Record representation clause (RM 13.5.1)
15215
15216 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15217
15218 @item Block statement in case if a block has a statement identifier (RM 5.6)
15219 @end itemize
15220
15221 @noindent
15222 In compact mode (when GNAT style layout or compact layout is set),
15223 the pretty printer uses one level of indentation instead
15224 of two. This is achived in the record definition and record representation
15225 clause cases by putting the @code{record} keyword on the same line as the
15226 start of the declaration or representation clause, and in the block and loop
15227 case by putting the block or loop header on the same line as the statement
15228 identifier.
15229
15230 @noindent
15231 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15232 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15233 layout on the one hand, and uncompact layout
15234 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15235 can be illustrated by the following examples:
15236
15237 @iftex
15238 @cartouche
15239 @multitable @columnfractions .5 .5
15240 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15241
15242 @item
15243 @smallexample @c ada
15244 type q is record
15245    a : integer;
15246    b : integer;
15247 end record;
15248 @end smallexample
15249 @tab
15250 @smallexample @c ada
15251 type q is
15252    record
15253       a : integer;
15254       b : integer;
15255    end record;
15256 @end smallexample
15257
15258 @item
15259 @smallexample @c ada
15260 for q use record
15261    a at 0 range  0 .. 31;
15262    b at 4 range  0 .. 31;
15263 end record;
15264 @end smallexample
15265 @tab
15266 @smallexample @c ada
15267 for q use
15268    record
15269       a at 0 range  0 .. 31;
15270       b at 4 range  0 .. 31;
15271    end record;
15272 @end smallexample
15273
15274 @item
15275 @smallexample @c ada
15276 Block : declare
15277    A : Integer := 3;
15278 begin
15279    Proc (A, A);
15280 end Block;
15281 @end smallexample
15282 @tab
15283 @smallexample @c ada
15284 Block :
15285    declare
15286       A : Integer := 3;
15287    begin
15288       Proc (A, A);
15289    end Block;
15290 @end smallexample
15291
15292 @item
15293 @smallexample @c ada
15294 Clear : for J in 1 .. 10 loop
15295    A (J) := 0;
15296 end loop Clear;
15297 @end smallexample
15298 @tab
15299 @smallexample @c ada
15300 Clear :
15301    for J in 1 .. 10 loop
15302       A (J) := 0;
15303    end loop Clear;
15304 @end smallexample
15305 @end multitable
15306 @end cartouche
15307 @end iftex
15308
15309 @ifnottex
15310 @smallexample
15311 @cartouche
15312 GNAT style, compact layout              Uncompact layout
15313
15314 type q is record                        type q is
15315    a : integer;                            record
15316    b : integer;                               a : integer;
15317 end record;                                   b : integer;
15318                                            end record;
15319
15320 for q use record                        for q use
15321    a at 0 range  0 .. 31;                  record
15322    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15323 end record;                                   b at 4 range  0 .. 31;
15324                                            end record;
15325
15326 Block : declare                         Block :
15327    A : Integer := 3;                       declare
15328 begin                                         A : Integer := 3;
15329    Proc (A, A);                            begin
15330 end Block;                                    Proc (A, A);
15331                                            end Block;
15332
15333 Clear : for J in 1 .. 10 loop           Clear :
15334    A (J) := 0;                             for J in 1 .. 10 loop
15335 end loop Clear;                               A (J) := 0;
15336                                            end loop Clear;
15337 @end cartouche
15338 @end smallexample
15339 @end ifnottex
15340
15341 @noindent
15342 A further difference between GNAT style layout and compact layout is that
15343 GNAT style layout inserts empty lines as separation for
15344 compound statements, return statements and bodies.
15345
15346 @node Name Casing
15347 @subsection Name Casing
15348
15349 @noindent
15350 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15351 the same casing as the corresponding defining identifier.
15352
15353 You control the casing for defining occurrences via the
15354 @option{^-n^/NAME_CASING^} switch.
15355 @ifclear vms
15356 With @option{-nD} (``as declared'', which is the default),
15357 @end ifclear
15358 @ifset vms
15359 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15360 @end ifset
15361 defining occurrences appear exactly as in the source file
15362 where they are declared.
15363 The other ^values for this switch^options for this qualifier^ ---
15364 @option{^-nU^UPPER_CASE^},
15365 @option{^-nL^LOWER_CASE^},
15366 @option{^-nM^MIXED_CASE^} ---
15367 result in
15368 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15369 If @command{gnatpp} changes the casing of a defining
15370 occurrence, it analogously changes the casing of all the
15371 usage occurrences of this name.
15372
15373 If the defining occurrence of a name is not in the source compilation unit
15374 currently being processed by @command{gnatpp}, the casing of each reference to
15375 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15376 switch (subject to the dictionary file mechanism described below).
15377 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15378 had affected the
15379 casing for the defining occurrence of the name.
15380
15381 Some names may need to be spelled with casing conventions that are not
15382 covered by the upper-, lower-, and mixed-case transformations.
15383 You can arrange correct casing by placing such names in a
15384 @emph{dictionary file},
15385 and then supplying a @option{^-D^/DICTIONARY^} switch.
15386 The casing of names from dictionary files overrides
15387 any @option{^-n^/NAME_CASING^} switch.
15388
15389 To handle the casing of Ada predefined names and the names from GNAT libraries,
15390 @command{gnatpp} assumes a default dictionary file.
15391 The name of each predefined entity is spelled with the same casing as is used
15392 for the entity in the @cite{Ada Reference Manual}.
15393 The name of each entity in the GNAT libraries is spelled with the same casing
15394 as is used in the declaration of that entity.
15395
15396 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15397 default dictionary file.
15398 Instead, the casing for predefined and GNAT-defined names will be established
15399 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15400 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15401 will appear as just shown,
15402 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15403 To ensure that even such names are rendered in uppercase,
15404 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15405 (or else, less conveniently, place these names in upper case in a dictionary
15406 file).
15407
15408 A dictionary file is
15409 a plain text file; each line in this file can be either a blank line
15410 (containing only space characters and ASCII.HT characters), an Ada comment
15411 line, or the specification of exactly one @emph{casing schema}.
15412
15413 A casing schema is a string that has the following syntax:
15414
15415 @smallexample
15416 @cartouche
15417   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15418
15419   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15420 @end cartouche
15421 @end smallexample
15422
15423 @noindent
15424 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15425 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15426
15427 The casing schema string can be followed by white space and/or an Ada-style
15428 comment; any amount of white space is allowed before the string.
15429
15430 If a dictionary file is passed as
15431 @ifclear vms
15432 the value of a @option{-D@var{file}} switch
15433 @end ifclear
15434 @ifset vms
15435 an option to the @option{/DICTIONARY} qualifier
15436 @end ifset
15437 then for every
15438 simple name and every identifier, @command{gnatpp} checks if the dictionary
15439 defines the casing for the name or for some of its parts (the term ``subword''
15440 is used below to denote the part of a name which is delimited by ``_'' or by
15441 the beginning or end of the word and which does not contain any ``_'' inside):
15442
15443 @itemize @bullet
15444 @item
15445 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15446 the casing defined by the dictionary; no subwords are checked for this word
15447
15448 @item
15449 for every subword @command{gnatpp} checks if the dictionary contains the
15450 corresponding string of the form @code{*@var{simple_identifier}*},
15451 and if it does, the casing of this @var{simple_identifier} is used
15452 for this subword
15453
15454 @item
15455 if the whole name does not contain any ``_'' inside, and if for this name
15456 the dictionaty contains two entries - one of the form @var{identifier},
15457 and another - of the form *@var{simple_identifier}*, then the first one
15458 is applied to define the casing of this name
15459
15460 @item
15461 if more than one dictionary file is passed as @command{gnatpp} switches, each
15462 dictionary adds new casing exceptions and overrides all the existing casing
15463 exceptions set by the previous dictionaries
15464
15465 @item
15466 when @command{gnatpp} checks if the word or subword is in the dictionary,
15467 this check is not case sensitive
15468 @end itemize
15469
15470 @noindent
15471 For example, suppose we have the following source to reformat:
15472
15473 @smallexample @c ada
15474 @cartouche
15475 procedure test is
15476    name1 : integer := 1;
15477    name4_name3_name2 : integer := 2;
15478    name2_name3_name4 : Boolean;
15479    name1_var : Float;
15480 begin
15481    name2_name3_name4 := name4_name3_name2 > name1;
15482 end;
15483 @end cartouche
15484 @end smallexample
15485
15486 @noindent
15487 And suppose we have two dictionaries:
15488
15489 @smallexample
15490 @cartouche
15491 @i{dict1:}
15492    NAME1
15493    *NaMe3*
15494    *Name1*
15495 @end cartouche
15496
15497 @cartouche
15498 @i{dict2:}
15499   *NAME3*
15500 @end cartouche
15501 @end smallexample
15502
15503 @noindent
15504 If @command{gnatpp} is called with the following switches:
15505
15506 @smallexample
15507 @ifclear vms
15508 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15509 @end ifclear
15510 @ifset vms
15511 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15512 @end ifset
15513 @end smallexample
15514
15515 @noindent
15516 then we will get the following name casing in the @command{gnatpp} output:
15517
15518 @smallexample @c ada
15519 @cartouche
15520 procedure Test is
15521    NAME1             : Integer := 1;
15522    Name4_NAME3_Name2 : Integer := 2;
15523    Name2_NAME3_Name4 : Boolean;
15524    Name1_Var         : Float;
15525 begin
15526    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15527 end Test;
15528 @end cartouche
15529 @end smallexample
15530
15531 @c *********************************
15532 @node The GNAT Metric Tool gnatmetric
15533 @chapter The GNAT Metric Tool @command{gnatmetric}
15534 @findex gnatmetric
15535 @cindex Metric tool
15536
15537 @noindent
15538 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15539 for computing various program metrics.
15540 It takes an Ada source file as input and generates a file containing the
15541 metrics data as output. Various switches control which
15542 metrics are computed and output.
15543
15544 @command{gnatmetric} generates and uses the ASIS
15545 tree for the input source and thus requires the input to be syntactically and
15546 semantically legal.
15547 If this condition is not met, @command{gnatmetric} will generate
15548 an error message; no metric information for this file will be
15549 computed and reported.
15550
15551 If the compilation unit contained in the input source depends semantically
15552 upon units in files located outside the current directory, you have to provide
15553 the source search path when invoking @command{gnatmetric}.
15554 If it depends semantically upon units that are contained
15555 in files with names that do not follow the GNAT file naming rules, you have to
15556 provide the configuration file describing the corresponding naming scheme; see
15557 the description of the @command{gnatmetric} switches below.
15558 Alternatively, you may use a project file and invoke @command{gnatmetric}
15559 through the @command{gnat} driver.
15560
15561
15562 The @command{gnatmetric} command has the form
15563
15564 @smallexample
15565 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
15566 @end smallexample
15567
15568 @noindent
15569 where
15570 @itemize @bullet
15571 @item
15572 @i{switches} specify the metrics to compute and define the destination for
15573 the output
15574
15575 @item
15576 Each @i{filename} is the name (including the extension) of a source
15577 file to process. ``Wildcards'' are allowed, and
15578 the file name may contain path information.
15579 If no @i{filename} is supplied, then the @i{switches} list must contain
15580 at least one
15581 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15582 Including both a @option{-files} switch and one or more
15583 @i{filename} arguments is permitted.
15584
15585 @item
15586 @i{-cargs gcc_switches} is a list of switches for
15587 @command{gcc}. They will be passed on to all compiler invocations made by
15588 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15589 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15590 and use the @option{-gnatec} switch to set the configuration file.
15591 @end itemize
15592
15593 @menu
15594 * Switches for gnatmetric::
15595 @end menu
15596
15597 @node Switches for gnatmetric
15598 @section Switches for @command{gnatmetric}
15599
15600 @noindent
15601 The following subsections describe the various switches accepted by
15602 @command{gnatmetric}, organized by category.
15603
15604 @menu
15605 * Output Files Control::
15606 * Disable Metrics For Local Units::
15607 * Line Metrics Control::
15608 * Syntax Metrics Control::
15609 * Complexity Metrics Control::
15610 * Other gnatmetric Switches::
15611 @end menu
15612
15613 @node Output Files Control
15614 @subsection Output File Control
15615 @cindex Output file control in @command{gnatmetric}
15616
15617 @noindent
15618 @command{gnatmetric} has two output formats. It can generate a
15619 textual (human-readable) form, and also XML. By default only textual
15620 output is generated.
15621
15622 When generating the output in textual form, @command{gnatmetric} creates
15623 for each Ada source file a corresponding text file
15624 containing the computed metrics. By default, this file
15625 is placed in the same directory as where the source file is located, and
15626 its name is obtained
15627 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15628 input file.
15629
15630 All the output information generated in XML format is placed in a single
15631 file. By default this file is placed in the current directory and has the
15632 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15633
15634 Some of the computed metrics are summed over the units passed to
15635 @command{gnatmetric}; for example, the total number of lines of code.
15636 By default this information is sent to @file{stdout}, but a file
15637 can be specified with the @option{-og} switch.
15638
15639 The following switches control the @command{gnatmetric} output:
15640
15641 @table @option
15642 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15643 @item ^-x^/XML^
15644 Generate the XML output
15645
15646 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15647 @item ^-nt^/NO_TEXT^
15648 Do not generate the output in text form (implies @option{^-x^/XML^})
15649
15650 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15651 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15652 Put textual files with detailed metrics into @var{output_dir}
15653
15654 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15655 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15656 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15657 in the name of the output file.
15658
15659 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15660 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15661 Put global metrics into @var{file_name}
15662
15663 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15664 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15665 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15666
15667 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15668 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15669 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15670 output includes the name(s) of the Ada source file(s) from which the metrics
15671 are computed.  By default each name includes the absolute path. The
15672 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15673 to exclude all directory information from the file names that are output.)
15674
15675 @end table
15676
15677 @node Disable Metrics For Local Units
15678 @subsection Disable Metrics For Local Units
15679 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15680
15681 @noindent
15682 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15683 one compilation
15684 unit per one source file. It computes line metrics for the whole source
15685 file, and it also computes syntax
15686 and complexity metrics for the file's outermost unit.
15687
15688 By default, @command{gnatmetric} will also compute all metrics for certain
15689 kinds of locally declared program units:
15690
15691 @itemize @bullet
15692 @item
15693 subprogram (and generic subprogram) bodies;
15694
15695 @item
15696 package (and generic package) specifications and bodies;
15697
15698 @item
15699 task object and type specifications and bodies;
15700
15701 @item
15702 protected object and type specifications and bodies.
15703 @end itemize
15704
15705 @noindent
15706 These kinds of entities will be referred to as
15707 @emph{eligible local program units}, or simply @emph{eligible local units},
15708 @cindex Eligible local unit (for @command{gnatmetric})
15709 in the discussion below.
15710
15711 Note that a subprogram declaration, generic instantiation,
15712 or renaming declaration only receives metrics
15713 computation when it appear as the outermost entity
15714 in a source file.
15715
15716 Suppression of metrics computation for eligible local units can be
15717 obtained via the following switch:
15718
15719 @table @option
15720 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15721 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15722 Do not compute detailed metrics for eligible local program units
15723
15724 @end table
15725
15726 @node Line Metrics Control
15727 @subsection Line Metrics Control
15728 @cindex Line metrics control in @command{gnatmetric}
15729
15730 @noindent
15731 For any (legal) source file, and for each of its
15732 eligible local program units, @command{gnatmetric} computes the following
15733 metrics:
15734
15735 @itemize @bullet
15736 @item
15737 the total number of lines;
15738
15739 @item
15740 the total number of code lines (i.e., non-blank lines that are not comments)
15741
15742 @item
15743 the number of comment lines
15744
15745 @item
15746 the number of code lines containing end-of-line comments;
15747
15748 @item
15749 the number of empty lines and lines containing only space characters and/or
15750 format effectors (blank lines)
15751
15752 @end itemize
15753
15754 If @command{gnatmetric} is invoked on more than one source file, it sums the
15755 values of the line metrics for all the files being processed and then
15756 generates the cumulative results.
15757
15758 By default, all the line metrics are computed and reported. You can use the
15759 following switches to select the specific line metrics to be computed and
15760 reported (if any of these parameters is set, only explicitly specified line
15761 metrics are computed).
15762
15763 @table @option
15764 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15765 @item ^-la^/LINES_ALL^
15766 The number of all lines
15767
15768 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15769 @item ^-lcode^/CODE_LINES^
15770 The number of code lines
15771
15772 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15773 @item ^-lcomm^/COMENT_LINES^
15774 The number of comment lines
15775
15776 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15777 @item ^-leol^/MIXED_CODE_COMMENTS^
15778 The number of code lines containing
15779 end-of-line comments
15780
15781 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15782 @item ^-lb^/BLANK_LINES^
15783 The number of blank lines
15784
15785 @end table
15786
15787
15788 @node Syntax Metrics Control
15789 @subsection Syntax Metrics Control
15790 @cindex Syntax metrics control in @command{gnatmetric}
15791
15792 @noindent
15793 @command{gnatmetric} computes various syntactic metrics for the
15794 outermost unit and for each eligible local unit:
15795
15796 @table @emph
15797 @item LSLOC (``Logical Source Lines Of Code'')
15798 The total number of declarations and the total number of statements
15799
15800 @item Maximal static nesting level of inner program units
15801 According to
15802 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15803 package, a task unit, a protected unit, a
15804 protected entry, a generic unit, or an explicitly declared subprogram other
15805 than an enumeration literal.''
15806
15807 @item Maximal nesting level of composite syntactic constructs
15808 This corresponds to the notion of the
15809 maximum nesting level in the GNAT built-in style checks
15810 (@pxref{Style Checking})
15811 @end table
15812
15813 @noindent
15814 For the outermost unit in the file, @command{gnatmetric} additionally computes
15815 the following metrics:
15816
15817 @table @emph
15818 @item Public subprograms
15819 This metric is computed for package specifications. It is the
15820 number of subprograms and generic subprograms declared in the visible
15821 part (including in nested packages, protected objects, and
15822 protected types).
15823
15824 @item All subprograms
15825 This metric is computed for bodies and subunits. The
15826 metric is equal to a total number of subprogram bodies in the compilation
15827 unit.
15828 Neither generic instantiations nor renamings-as-a-body nor body stubs
15829 are counted. Any subprogram body is counted, independently of its nesting
15830 level and enclosing constructs. Generic bodies and bodies of protected
15831 subprograms are counted in the same way as ``usual'' subprogram bodies.
15832
15833 @item Public types
15834 This metric is computed for package specifications and
15835 generic package declarations. It is the total number of types
15836 that can be referenced from outside this compilation unit, plus the
15837 number of types from all the visible parts of all the visible generic packages.
15838 Generic formal types are not counted.  Only types, not subtypes,
15839 are included.
15840
15841 @noindent
15842 Along with the total number of public types, the following
15843 types are counted and reported separately:
15844
15845 @itemize @bullet
15846 @item
15847 Abstract types
15848
15849 @item
15850 Root tagged types (abstract, non-abstract, private, non-private). Type
15851 extensions are @emph{not} counted
15852
15853 @item
15854 Private types (including private extensions)
15855
15856 @item
15857 Task types
15858
15859 @item
15860 Protected types
15861
15862 @end itemize
15863
15864 @item All types
15865 This metric is computed for any compilation unit. It is equal to the total
15866 number of the declarations of different types given in the compilation unit.
15867 The private and the corresponding full type declaration are counted as one
15868 type declaration. Incomplete type declarations and generic formal types
15869 are not counted.
15870 No distinction is made among different kinds of types (abstract,
15871 private etc.); the total number of types is computed and reported.
15872
15873 @end table
15874
15875 @noindent
15876 By default, all the syntax metrics are computed and reported. You can use the
15877 following switches to select specific syntax metrics;
15878 if any of these is set, only the explicitly specified metrics are computed.
15879
15880 @table @option
15881 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
15882 @item ^-ed^/DECLARATION_TOTAL^
15883 The total number of declarations
15884
15885 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
15886 @item ^-es^/STATEMENT_TOTAL^
15887 The total number of statements
15888
15889 @cindex @option{^-eps^/^} (@command{gnatmetric})
15890 @item ^-eps^/INT_SUBPROGRAMS^
15891 The number of public subprograms in a compilation unit
15892
15893 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
15894 @item ^-eas^/SUBPROGRAMS_ALL^
15895 The number of all the subprograms in a compilation unit
15896
15897 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
15898 @item ^-ept^/INT_TYPES^
15899 The number of public types in a compilation unit
15900
15901 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
15902 @item ^-eat^/TYPES_ALL^
15903 The number of all the types in a compilation unit
15904
15905 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
15906 @item ^-enu^/PROGRAM_NESTING_MAX^
15907 The maximal program unit nesting level
15908
15909 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
15910 @item ^-ec^/CONSTRUCT_NESTING_MAX^
15911 The maximal construct nesting level
15912
15913 @end table
15914
15915 @node Complexity Metrics Control
15916 @subsection Complexity Metrics Control
15917 @cindex Complexity metrics control in @command{gnatmetric}
15918
15919 @noindent
15920 For a program unit that is an executable body (a subprogram body (including
15921 generic bodies), task body, entry body or a package body containing
15922 its own statement sequence ) @command{gnatmetric} computes the following
15923 complexity metrics:
15924
15925 @itemize @bullet
15926 @item
15927 McCabe cyclomatic complexity;
15928
15929 @item
15930 McCabe essential complexity;
15931
15932 @item
15933 maximal loop nesting level
15934
15935 @end itemize
15936
15937 @noindent
15938 The McCabe complexity metrics are defined
15939 in @url{www.mccabe.com/pdf/nist235r.pdf}
15940
15941 According to McCabe, both control statements and short-circuit control forms
15942 should be taken into account when computing cyclomatic complexity. For each
15943 body, we compute three metric values:
15944
15945 @itemize @bullet
15946 @item
15947 the complexity introduced by control
15948 statements only, without taking into account short-circuit forms,
15949
15950 @item
15951 the complexity introduced by short-circuit control forms only, and
15952
15953 @item
15954 the total
15955 cyclomatic complexity, which is the sum of these two values.
15956 @end itemize
15957
15958 @noindent
15959 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15960 the code in the exception handlers and in all the nested program units.
15961
15962 By default, all the complexity metrics are computed and reported.
15963 For more finely-grained control you can use
15964 the following switches:
15965
15966 @table @option
15967 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15968
15969 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
15970 Do not compute the McCabe Cyclomatic Complexity
15971
15972 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
15973 Do not compute the Essential Complexity
15974
15975 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
15976 Do not compute maximal loop nesting level
15977
15978 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
15979 Do not consider @code{exit} statements as @code{goto}s when
15980 computing Essential Complexity
15981
15982 @end table
15983
15984 @node Other gnatmetric Switches
15985 @subsection Other @code{gnatmetric} Switches
15986
15987 @noindent
15988 Additional @command{gnatmetric} switches are as follows:
15989
15990 @table @option
15991 @item ^-files @var{filename}^/FILES=@var{filename}^
15992 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15993 Take the argument source files from the specified file. This file should be an
15994 ordinary textual file containing file names separated by spaces or
15995 line breaks. You can use this switch more then once in the same call to
15996 @command{gnatmetric}. You also can combine this switch with
15997 an explicit list of files.
15998
15999 @item ^-v^/VERBOSE^
16000 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16001 Verbose mode;
16002 @command{gnatmetric} generates version information and then
16003 a trace of sources being procesed.
16004
16005 @item ^-dv^/DEBUG_OUTPUT^
16006 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16007 Debug mode;
16008 @command{gnatmetric} generates various messages useful to understand what
16009 happens during the metrics computation
16010
16011 @item ^-q^/QUIET^
16012 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16013 Quiet mode.
16014 @end table
16015
16016 @c ***********************************
16017 @node File Name Krunching Using gnatkr
16018 @chapter File Name Krunching Using @code{gnatkr}
16019 @findex gnatkr
16020
16021 @noindent
16022 This chapter discusses the method used by the compiler to shorten
16023 the default file names chosen for Ada units so that they do not
16024 exceed the maximum length permitted. It also describes the
16025 @code{gnatkr} utility that can be used to determine the result of
16026 applying this shortening.
16027 @menu
16028 * About gnatkr::
16029 * Using gnatkr::
16030 * Krunching Method::
16031 * Examples of gnatkr Usage::
16032 @end menu
16033
16034 @node About gnatkr
16035 @section About @code{gnatkr}
16036
16037 @noindent
16038 The default file naming rule in GNAT
16039 is that the file name must be derived from
16040 the unit name. The exact default rule is as follows:
16041 @itemize @bullet
16042 @item
16043 Take the unit name and replace all dots by hyphens.
16044 @item
16045 If such a replacement occurs in the
16046 second character position of a name, and the first character is
16047 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16048 ^~ (tilde)^$ (dollar sign)^
16049 instead of a minus.
16050 @end itemize
16051 The reason for this exception is to avoid clashes
16052 with the standard names for children of System, Ada, Interfaces,
16053 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16054 respectively.
16055
16056 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16057 switch of the compiler activates a ``krunching''
16058 circuit that limits file names to nn characters (where nn is a decimal
16059 integer). For example, using OpenVMS,
16060 where the maximum file name length is
16061 39, the value of nn is usually set to 39, but if you want to generate
16062 a set of files that would be usable if ported to a system with some
16063 different maximum file length, then a different value can be specified.
16064 The default value of 39 for OpenVMS need not be specified.
16065
16066 The @code{gnatkr} utility can be used to determine the krunched name for
16067 a given file, when krunched to a specified maximum length.
16068
16069 @node Using gnatkr
16070 @section Using @code{gnatkr}
16071
16072 @noindent
16073 The @code{gnatkr} command has the form
16074
16075 @ifclear vms
16076 @smallexample
16077 $ gnatkr @var{name} [@var{length}]
16078 @end smallexample
16079 @end ifclear
16080
16081 @ifset vms
16082 @smallexample
16083 $ gnatkr @var{name} /COUNT=nn
16084 @end smallexample
16085 @end ifset
16086
16087 @noindent
16088 @var{name} is the uncrunched file name, derived from the name of the unit
16089 in the standard manner described in the previous section (i.e. in particular
16090 all dots are replaced by hyphens). The file name may or may not have an
16091 extension (defined as a suffix of the form period followed by arbitrary
16092 characters other than period). If an extension is present then it will
16093 be preserved in the output. For example, when krunching @file{hellofile.ads}
16094 to eight characters, the result will be hellofil.ads.
16095
16096 Note: for compatibility with previous versions of @code{gnatkr} dots may
16097 appear in the name instead of hyphens, but the last dot will always be
16098 taken as the start of an extension. So if @code{gnatkr} is given an argument
16099 such as @file{Hello.World.adb} it will be treated exactly as if the first
16100 period had been a hyphen, and for example krunching to eight characters
16101 gives the result @file{hellworl.adb}.
16102
16103 Note that the result is always all lower case (except on OpenVMS where it is
16104 all upper case). Characters of the other case are folded as required.
16105
16106 @var{length} represents the length of the krunched name. The default
16107 when no argument is given is ^8^39^ characters. A length of zero stands for
16108 unlimited, in other words do not chop except for system files where the
16109 impled crunching length is always eight characters.
16110
16111 @noindent
16112 The output is the krunched name. The output has an extension only if the
16113 original argument was a file name with an extension.
16114
16115 @node Krunching Method
16116 @section Krunching Method
16117
16118 @noindent
16119 The initial file name is determined by the name of the unit that the file
16120 contains. The name is formed by taking the full expanded name of the
16121 unit and replacing the separating dots with hyphens and
16122 using ^lowercase^uppercase^
16123 for all letters, except that a hyphen in the second character position is
16124 replaced by a ^tilde^dollar sign^ if the first character is
16125 ^a, i, g, or s^A, I, G, or S^.
16126 The extension is @code{.ads} for a
16127 specification and @code{.adb} for a body.
16128 Krunching does not affect the extension, but the file name is shortened to
16129 the specified length by following these rules:
16130
16131 @itemize @bullet
16132 @item
16133 The name is divided into segments separated by hyphens, tildes or
16134 underscores and all hyphens, tildes, and underscores are
16135 eliminated. If this leaves the name short enough, we are done.
16136
16137 @item
16138 If the name is too long, the longest segment is located (left-most
16139 if there are two of equal length), and shortened by dropping
16140 its last character. This is repeated until the name is short enough.
16141
16142 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16143 to fit the name into 8 characters as required by some operating systems.
16144
16145 @smallexample
16146 our-strings-wide_fixed 22
16147 our strings wide fixed 19
16148 our string  wide fixed 18
16149 our strin   wide fixed 17
16150 our stri    wide fixed 16
16151 our stri    wide fixe  15
16152 our str     wide fixe  14
16153 our str     wid  fixe  13
16154 our str     wid  fix   12
16155 ou  str     wid  fix   11
16156 ou  st      wid  fix   10
16157 ou  st      wi   fix   9
16158 ou  st      wi   fi    8
16159 Final file name: oustwifi.adb
16160 @end smallexample
16161
16162 @item
16163 The file names for all predefined units are always krunched to eight
16164 characters. The krunching of these predefined units uses the following
16165 special prefix replacements:
16166
16167 @table @file
16168 @item ada-
16169 replaced by @file{^a^A^-}
16170
16171 @item gnat-
16172 replaced by @file{^g^G^-}
16173
16174 @item interfaces-
16175 replaced by @file{^i^I^-}
16176
16177 @item system-
16178 replaced by @file{^s^S^-}
16179 @end table
16180
16181 These system files have a hyphen in the second character position. That
16182 is why normal user files replace such a character with a
16183 ^tilde^dollar sign^, to
16184 avoid confusion with system file names.
16185
16186 As an example of this special rule, consider
16187 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16188
16189 @smallexample
16190 ada-strings-wide_fixed 22
16191 a-  strings wide fixed 18
16192 a-  string  wide fixed 17
16193 a-  strin   wide fixed 16
16194 a-  stri    wide fixed 15
16195 a-  stri    wide fixe  14
16196 a-  str     wide fixe  13
16197 a-  str     wid  fixe  12
16198 a-  str     wid  fix   11
16199 a-  st      wid  fix   10
16200 a-  st      wi   fix   9
16201 a-  st      wi   fi    8
16202 Final file name: a-stwifi.adb
16203 @end smallexample
16204 @end itemize
16205
16206 Of course no file shortening algorithm can guarantee uniqueness over all
16207 possible unit names, and if file name krunching is used then it is your
16208 responsibility to ensure that no name clashes occur. The utility
16209 program @code{gnatkr} is supplied for conveniently determining the
16210 krunched name of a file.
16211
16212 @node Examples of gnatkr Usage
16213 @section Examples of @code{gnatkr} Usage
16214
16215 @smallexample
16216 @iftex
16217 @leftskip=0cm
16218 @end iftex
16219 @ifclear vms
16220 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16221 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16222 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16223 $ gnatkr grandparent-parent-child     --> grparchi
16224 @end ifclear
16225 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16226 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16227 @end smallexample
16228
16229 @node Preprocessing Using gnatprep
16230 @chapter Preprocessing Using @code{gnatprep}
16231 @findex gnatprep
16232
16233 @noindent
16234 The @code{gnatprep} utility provides
16235 a simple preprocessing capability for Ada programs.
16236 It is designed for use with GNAT, but is not dependent on any special
16237 features of GNAT.
16238
16239 @menu
16240 * Using gnatprep::
16241 * Switches for gnatprep::
16242 * Form of Definitions File::
16243 * Form of Input Text for gnatprep::
16244 @end menu
16245
16246 @node Using gnatprep
16247 @section Using @code{gnatprep}
16248
16249 @noindent
16250 To call @code{gnatprep} use
16251
16252 @smallexample
16253 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16254 @end smallexample
16255
16256 @noindent
16257 where
16258 @table @code
16259 @item infile
16260 is the full name of the input file, which is an Ada source
16261 file containing preprocessor directives.
16262
16263 @item outfile
16264 is the full name of the output file, which is an Ada source
16265 in standard Ada form. When used with GNAT, this file name will
16266 normally have an ads or adb suffix.
16267
16268 @item deffile
16269 is the full name of a text file containing definitions of
16270 symbols to be referenced by the preprocessor. This argument is
16271 optional, and can be replaced by the use of the @option{-D} switch.
16272
16273 @item switches
16274 is an optional sequence of switches as described in the next section.
16275 @end table
16276
16277 @node Switches for gnatprep
16278 @section Switches for @code{gnatprep}
16279
16280 @table @option
16281 @c !sort!
16282
16283 @item ^-b^/BLANK_LINES^
16284 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16285 Causes both preprocessor lines and the lines deleted by
16286 preprocessing to be replaced by blank lines in the output source file,
16287 preserving line numbers in the output file.
16288
16289 @item ^-c^/COMMENTS^
16290 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16291 Causes both preprocessor lines and the lines deleted
16292 by preprocessing to be retained in the output source as comments marked
16293 with the special string @code{"--! "}. This option will result in line numbers
16294 being preserved in the output file.
16295
16296 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16297 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16298 Defines a new symbol, associated with value. If no value is given on the
16299 command line, then symbol is considered to be @code{True}. This switch
16300 can be used in place of a definition file.
16301
16302 @ifset vms
16303 @item /REMOVE
16304 @cindex @option{/REMOVE} (@command{gnatprep})
16305 This is the default setting which causes lines deleted by preprocessing
16306 to be entirely removed from the output file.
16307 @end ifset
16308
16309 @item ^-r^/REFERENCE^
16310 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16311 Causes a @code{Source_Reference} pragma to be generated that
16312 references the original input file, so that error messages will use
16313 the file name of this original file. The use of this switch implies
16314 that preprocessor lines are not to be removed from the file, so its
16315 use will force @option{^-b^/BLANK_LINES^} mode if
16316 @option{^-c^/COMMENTS^}
16317 has not been specified explicitly.
16318
16319 Note that if the file to be preprocessed contains multiple units, then
16320 it will be necessary to @code{gnatchop} the output file from
16321 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16322 in the preprocessed file, it will be respected by
16323 @code{gnatchop ^-r^/REFERENCE^}
16324 so that the final chopped files will correctly refer to the original
16325 input source file for @code{gnatprep}.
16326
16327 @item ^-s^/SYMBOLS^
16328 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16329 Causes a sorted list of symbol names and values to be
16330 listed on the standard output file.
16331
16332 @item ^-u^/UNDEFINED^
16333 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16334 Causes undefined symbols to be treated as having the value FALSE in the context
16335 of a preprocessor test. In the absence of this option, an undefined symbol in
16336 a @code{#if} or @code{#elsif} test will be treated as an error.
16337
16338 @end table
16339
16340 @ifclear vms
16341 @noindent
16342 Note: if neither @option{-b} nor @option{-c} is present,
16343 then preprocessor lines and
16344 deleted lines are completely removed from the output, unless -r is
16345 specified, in which case -b is assumed.
16346 @end ifclear
16347
16348 @node Form of Definitions File
16349 @section Form of Definitions File
16350
16351 @noindent
16352 The definitions file contains lines of the form
16353
16354 @smallexample
16355 symbol := value
16356 @end smallexample
16357
16358 @noindent
16359 where symbol is an identifier, following normal Ada (case-insensitive)
16360 rules for its syntax, and value is one of the following:
16361
16362 @itemize @bullet
16363 @item
16364 Empty, corresponding to a null substitution
16365 @item
16366 A string literal using normal Ada syntax
16367 @item
16368 Any sequence of characters from the set
16369 (letters, digits, period, underline).
16370 @end itemize
16371
16372 @noindent
16373 Comment lines may also appear in the definitions file, starting with
16374 the usual @code{--},
16375 and comments may be added to the definitions lines.
16376
16377 @node Form of Input Text for gnatprep
16378 @section Form of Input Text for @code{gnatprep}
16379
16380 @noindent
16381 The input text may contain preprocessor conditional inclusion lines,
16382 as well as general symbol substitution sequences.
16383
16384 The preprocessor conditional inclusion commands have the form
16385
16386 @smallexample
16387 @group
16388 @cartouche
16389 #if @i{expression} [then]
16390    lines
16391 #elsif @i{expression} [then]
16392    lines
16393 #elsif @i{expression} [then]
16394    lines
16395 ...
16396 #else
16397    lines
16398 #end if;
16399 @end cartouche
16400 @end group
16401 @end smallexample
16402
16403 @noindent
16404 In this example, @i{expression} is defined by the following grammar:
16405 @smallexample
16406 @i{expression} ::=  <symbol>
16407 @i{expression} ::=  <symbol> = "<value>"
16408 @i{expression} ::=  <symbol> = <symbol>
16409 @i{expression} ::=  <symbol> 'Defined
16410 @i{expression} ::=  not @i{expression}
16411 @i{expression} ::=  @i{expression} and @i{expression}
16412 @i{expression} ::=  @i{expression} or @i{expression}
16413 @i{expression} ::=  @i{expression} and then @i{expression}
16414 @i{expression} ::=  @i{expression} or else @i{expression}
16415 @i{expression} ::=  ( @i{expression} )
16416 @end smallexample
16417
16418 @noindent
16419 For the first test (@i{expression} ::= <symbol>) the symbol must have
16420 either the value true or false, that is to say the right-hand of the
16421 symbol definition must be one of the (case-insensitive) literals
16422 @code{True} or @code{False}. If the value is true, then the
16423 corresponding lines are included, and if the value is false, they are
16424 excluded.
16425
16426 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16427 the symbol has been defined in the definition file or by a @option{-D}
16428 switch on the command line. Otherwise, the test is false.
16429
16430 The equality tests are case insensitive, as are all the preprocessor lines.
16431
16432 If the symbol referenced is not defined in the symbol definitions file,
16433 then the effect depends on whether or not switch @option{-u}
16434 is specified. If so, then the symbol is treated as if it had the value
16435 false and the test fails. If this switch is not specified, then
16436 it is an error to reference an undefined symbol. It is also an error to
16437 reference a symbol that is defined with a value other than @code{True}
16438 or @code{False}.
16439
16440 The use of the @code{not} operator inverts the sense of this logical test, so
16441 that the lines are included only if the symbol is not defined.
16442 The @code{then} keyword is optional as shown
16443
16444 The @code{#} must be the first non-blank character on a line, but
16445 otherwise the format is free form. Spaces or tabs may appear between
16446 the @code{#} and the keyword. The keywords and the symbols are case
16447 insensitive as in normal Ada code. Comments may be used on a
16448 preprocessor line, but other than that, no other tokens may appear on a
16449 preprocessor line. Any number of @code{elsif} clauses can be present,
16450 including none at all. The @code{else} is optional, as in Ada.
16451
16452 The @code{#} marking the start of a preprocessor line must be the first
16453 non-blank character on the line, i.e. it must be preceded only by
16454 spaces or horizontal tabs.
16455
16456 Symbol substitution outside of preprocessor lines is obtained by using
16457 the sequence
16458
16459 @smallexample
16460 $symbol
16461 @end smallexample
16462
16463 @noindent
16464 anywhere within a source line, except in a comment or within a
16465 string literal. The identifier
16466 following the @code{$} must match one of the symbols defined in the symbol
16467 definition file, and the result is to substitute the value of the
16468 symbol in place of @code{$symbol} in the output file.
16469
16470 Note that although the substitution of strings within a string literal
16471 is not possible, it is possible to have a symbol whose defined value is
16472 a string literal. So instead of setting XYZ to @code{hello} and writing:
16473
16474 @smallexample
16475 Header : String := "$XYZ";
16476 @end smallexample
16477
16478 @noindent
16479 you should set XYZ to @code{"hello"} and write:
16480
16481 @smallexample
16482 Header : String := $XYZ;
16483 @end smallexample
16484
16485 @noindent
16486 and then the substitution will occur as desired.
16487
16488 @ifset vms
16489 @node The GNAT Run-Time Library Builder gnatlbr
16490 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16491 @findex gnatlbr
16492 @cindex Library builder
16493
16494 @noindent
16495 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16496 supplied configuration pragmas.
16497
16498 @menu
16499 * Running gnatlbr::
16500 * Switches for gnatlbr::
16501 * Examples of gnatlbr Usage::
16502 @end menu
16503
16504 @node Running gnatlbr
16505 @section Running @code{gnatlbr}
16506
16507 @noindent
16508 The @code{gnatlbr} command has the form
16509
16510 @smallexample
16511 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16512 @end smallexample
16513
16514 @node Switches for gnatlbr
16515 @section Switches for @code{gnatlbr}
16516
16517 @noindent
16518 @code{gnatlbr} recognizes the following switches:
16519
16520 @table @option
16521 @c !sort!
16522 @item /CREATE=directory
16523 @cindex @code{/CREATE} (@code{gnatlbr})
16524      Create the new run-time library in the specified directory.
16525
16526 @item /SET=directory
16527 @cindex @code{/SET} (@code{gnatlbr})
16528      Make the library in the specified directory the current run-time
16529      library.
16530
16531 @item /DELETE=directory
16532 @cindex @code{/DELETE} (@code{gnatlbr})
16533      Delete the run-time library in the specified directory.
16534
16535 @item /CONFIG=file
16536 @cindex @code{/CONFIG} (@code{gnatlbr})
16537      With /CREATE:
16538      Use the configuration pragmas in the specified file when building
16539      the library.
16540
16541      With /SET:
16542      Use the configuration pragmas in the specified file when compiling.
16543
16544 @end table
16545
16546 @node Examples of gnatlbr Usage
16547 @section Example of @code{gnatlbr} Usage
16548
16549 @smallexample
16550 Contents of VAXFLOAT.ADC:
16551 pragma Float_Representation (VAX_Float);
16552
16553 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16554
16555 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16556
16557 @end smallexample
16558 @end ifset
16559
16560 @node The GNAT Library Browser gnatls
16561 @chapter The GNAT Library Browser @code{gnatls}
16562 @findex gnatls
16563 @cindex Library browser
16564
16565 @noindent
16566 @code{gnatls} is a tool that outputs information about compiled
16567 units. It gives the relationship between objects, unit names and source
16568 files. It can also be used to check the source dependencies of a unit
16569 as well as various characteristics.
16570
16571 @menu
16572 * Running gnatls::
16573 * Switches for gnatls::
16574 * Examples of gnatls Usage::
16575 @end menu
16576
16577 @node Running gnatls
16578 @section Running @code{gnatls}
16579
16580 @noindent
16581 The @code{gnatls} command has the form
16582
16583 @smallexample
16584 $ gnatls switches @var{object_or_ali_file}
16585 @end smallexample
16586
16587 @noindent
16588 The main argument is the list of object or @file{ali} files
16589 (@pxref{The Ada Library Information Files})
16590 for which information is requested.
16591
16592 In normal mode, without additional option, @code{gnatls} produces a
16593 four-column listing. Each line represents information for a specific
16594 object. The first column gives the full path of the object, the second
16595 column gives the name of the principal unit in this object, the third
16596 column gives the status of the source and the fourth column gives the
16597 full path of the source representing this unit.
16598 Here is a simple example of use:
16599
16600 @smallexample
16601 $ gnatls *.o
16602 ^./^[]^demo1.o            demo1            DIF demo1.adb
16603 ^./^[]^demo2.o            demo2             OK demo2.adb
16604 ^./^[]^hello.o            h1                OK hello.adb
16605 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16606 ^./^[]^instr.o            instr             OK instr.adb
16607 ^./^[]^tef.o              tef              DIF tef.adb
16608 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16609 ^./^[]^tgef.o             tgef             DIF tgef.adb
16610 @end smallexample
16611
16612 @noindent
16613 The first line can be interpreted as follows: the main unit which is
16614 contained in
16615 object file @file{demo1.o} is demo1, whose main source is in
16616 @file{demo1.adb}. Furthermore, the version of the source used for the
16617 compilation of demo1 has been modified (DIF). Each source file has a status
16618 qualifier which can be:
16619
16620 @table @code
16621 @item OK (unchanged)
16622 The version of the source file used for the compilation of the
16623 specified unit corresponds exactly to the actual source file.
16624
16625 @item MOK (slightly modified)
16626 The version of the source file used for the compilation of the
16627 specified unit differs from the actual source file but not enough to
16628 require recompilation. If you use gnatmake with the qualifier
16629 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16630 MOK will not be recompiled.
16631
16632 @item DIF (modified)
16633 No version of the source found on the path corresponds to the source
16634 used to build this object.
16635
16636 @item ??? (file not found)
16637 No source file was found for this unit.
16638
16639 @item HID (hidden,  unchanged version not first on PATH)
16640 The version of the source that corresponds exactly to the source used
16641 for compilation has been found on the path but it is hidden by another
16642 version of the same source that has been modified.
16643
16644 @end table
16645
16646 @node Switches for gnatls
16647 @section Switches for @code{gnatls}
16648
16649 @noindent
16650 @code{gnatls} recognizes the following switches:
16651
16652 @table @option
16653 @c !sort!
16654 @item ^-a^/ALL_UNITS^
16655 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16656 Consider all units, including those of the predefined Ada library.
16657 Especially useful with @option{^-d^/DEPENDENCIES^}.
16658
16659 @item ^-d^/DEPENDENCIES^
16660 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16661 List sources from which specified units depend on.
16662
16663 @item ^-h^/OUTPUT=OPTIONS^
16664 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16665 Output the list of options.
16666
16667 @item ^-o^/OUTPUT=OBJECTS^
16668 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16669 Only output information about object files.
16670
16671 @item ^-s^/OUTPUT=SOURCES^
16672 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16673 Only output information about source files.
16674
16675 @item ^-u^/OUTPUT=UNITS^
16676 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16677 Only output information about compilation units.
16678
16679 @item ^-files^/FILES^=@var{file}
16680 @cindex @option{^-files^/FILES^} (@code{gnatls})
16681 Take as arguments the files listed in text file @var{file}.
16682 Text file @var{file} may contain empty lines that are ignored.
16683 Each non empty line should contain the name of an existing file.
16684 Several such switches may be specified simultaneously.
16685
16686 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16687 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16688 @itemx ^-I^/SEARCH=^@var{dir}
16689 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16690 @itemx -nostdinc
16691 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16692 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16693 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16694 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16695 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16696 flags (@pxref{Switches for gnatmake}).
16697
16698 @item --RTS=@var{rts-path}
16699 @cindex @option{--RTS} (@code{gnatls})
16700 Specifies the default location of the runtime library. Same meaning as the
16701 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16702
16703 @item ^-v^/OUTPUT=VERBOSE^
16704 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16705 Verbose mode. Output the complete source, object and project paths. Do not use
16706 the default column layout but instead use long format giving as much as
16707 information possible on each requested units, including special
16708 characteristics such as:
16709
16710 @table @code
16711 @item  Preelaborable
16712 The unit is preelaborable in the Ada 95 sense.
16713
16714 @item No_Elab_Code
16715 No elaboration code has been produced by the compiler for this unit.
16716
16717 @item Pure
16718 The unit is pure in the Ada 95 sense.
16719
16720 @item Elaborate_Body
16721 The unit contains a pragma Elaborate_Body.
16722
16723 @item Remote_Types
16724 The unit contains a pragma Remote_Types.
16725
16726 @item Shared_Passive
16727 The unit contains a pragma Shared_Passive.
16728
16729 @item Predefined
16730 This unit is part of the predefined environment and cannot be modified
16731 by the user.
16732
16733 @item Remote_Call_Interface
16734 The unit contains a pragma Remote_Call_Interface.
16735
16736 @end table
16737
16738 @end table
16739
16740 @node Examples of gnatls Usage
16741 @section Example of @code{gnatls} Usage
16742 @ifclear vms
16743
16744 @noindent
16745 Example of using the verbose switch. Note how the source and
16746 object paths are affected by the -I switch.
16747
16748 @smallexample
16749 $ gnatls -v -I.. demo1.o
16750
16751 GNATLS 5.03w (20041123-34)
16752 Copyright 1997-2004 Free Software Foundation, Inc.
16753
16754 Source Search Path:
16755    <Current_Directory>
16756    ../
16757    /home/comar/local/adainclude/
16758
16759 Object Search Path:
16760    <Current_Directory>
16761    ../
16762    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16763
16764 Project Search Path:
16765    <Current_Directory>
16766    /home/comar/local/lib/gnat/
16767
16768 ./demo1.o
16769    Unit =>
16770      Name   => demo1
16771      Kind   => subprogram body
16772      Flags  => No_Elab_Code
16773      Source => demo1.adb    modified
16774 @end smallexample
16775
16776 @noindent
16777 The following is an example of use of the dependency list.
16778 Note the use of the -s switch
16779 which gives a straight list of source files. This can be useful for
16780 building specialized scripts.
16781
16782 @smallexample
16783 $ gnatls -d demo2.o
16784 ./demo2.o   demo2        OK demo2.adb
16785                          OK gen_list.ads
16786                          OK gen_list.adb
16787                          OK instr.ads
16788                          OK instr-child.ads
16789
16790 $ gnatls -d -s -a demo1.o
16791 demo1.adb
16792 /home/comar/local/adainclude/ada.ads
16793 /home/comar/local/adainclude/a-finali.ads
16794 /home/comar/local/adainclude/a-filico.ads
16795 /home/comar/local/adainclude/a-stream.ads
16796 /home/comar/local/adainclude/a-tags.ads
16797 gen_list.ads
16798 gen_list.adb
16799 /home/comar/local/adainclude/gnat.ads
16800 /home/comar/local/adainclude/g-io.ads
16801 instr.ads
16802 /home/comar/local/adainclude/system.ads
16803 /home/comar/local/adainclude/s-exctab.ads
16804 /home/comar/local/adainclude/s-finimp.ads
16805 /home/comar/local/adainclude/s-finroo.ads
16806 /home/comar/local/adainclude/s-secsta.ads
16807 /home/comar/local/adainclude/s-stalib.ads
16808 /home/comar/local/adainclude/s-stoele.ads
16809 /home/comar/local/adainclude/s-stratt.ads
16810 /home/comar/local/adainclude/s-tasoli.ads
16811 /home/comar/local/adainclude/s-unstyp.ads
16812 /home/comar/local/adainclude/unchconv.ads
16813 @end smallexample
16814 @end ifclear
16815
16816 @ifset vms
16817 @smallexample
16818 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16819
16820 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16822 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16823 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16824 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16825 demo1.adb
16826 gen_list.ads
16827 gen_list.adb
16828 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16829 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16830 instr.ads
16831 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16832 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16833 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16834 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16835 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16836 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16841 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16842 @end smallexample
16843 @end ifset
16844
16845 @node Cleaning Up Using gnatclean
16846 @chapter Cleaning Up Using @code{gnatclean}
16847 @findex gnatclean
16848 @cindex Cleaning tool
16849
16850 @noindent
16851 @code{gnatclean} is a tool that allows the deletion of files produced by the
16852 compiler, binder and linker, including ALI files, object files, tree files,
16853 expanded source files, library files, interface copy source files, binder
16854 generated files and executable files.
16855
16856 @menu
16857 * Running gnatclean::
16858 * Switches for gnatclean::
16859 * Examples of gnatclean Usage::
16860 @end menu
16861
16862 @node Running gnatclean
16863 @section Running @code{gnatclean}
16864
16865 @noindent
16866 The @code{gnatclean} command has the form:
16867
16868 @smallexample
16869 $ gnatclean switches @var{names}
16870 @end smallexample
16871
16872 @noindent
16873 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16874 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16875 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16876
16877 @noindent
16878 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16879 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16880 the linker. In informative-only mode, specified by switch
16881 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16882 normal mode is listed, but no file is actually deleted.
16883
16884 @node Switches for gnatclean
16885 @section Switches for @code{gnatclean}
16886
16887 @noindent
16888 @code{gnatclean} recognizes the following switches:
16889
16890 @table @option
16891 @c !sort!
16892 @item ^-c^/COMPILER_FILES_ONLY^
16893 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16894 Only attempt to delete the files produced by the compiler, not those produced
16895 by the binder or the linker. The files that are not to be deleted are library
16896 files, interface copy files, binder generated files and executable files.
16897
16898 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16899 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16900 Indicate that ALI and object files should normally be found in directory
16901 @var{dir}.
16902
16903 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16904 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16905 When using project files, if some errors or warnings are detected during
16906 parsing and verbose mode is not in effect (no use of switch
16907 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16908 file, rather than its simple file name.
16909
16910 @item ^-h^/HELP^
16911 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16912 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16913
16914 @item ^-n^/NODELETE^
16915 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16916 Informative-only mode. Do not delete any files. Output the list of the files
16917 that would have been deleted if this switch was not specified.
16918
16919 @item ^-P^/PROJECT_FILE=^@var{project}
16920 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16921 Use project file @var{project}. Only one such switch can be used.
16922 When cleaning a project file, the files produced by the compilation of the
16923 immediate sources or inherited sources of the project files are to be
16924 deleted. This is not depending on the presence or not of executable names
16925 on the command line.
16926
16927 @item ^-q^/QUIET^
16928 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16929 Quiet output. If there are no error, do not ouuput anything, except in
16930 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16931 (switch ^-n^/NODELETE^).
16932
16933 @item ^-r^/RECURSIVE^
16934 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16935 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16936 clean all imported and extended project files, recursively. If this switch
16937 is not specified, only the files related to the main project file are to be
16938 deleted. This switch has no effect if no project file is specified.
16939
16940 @item ^-v^/VERBOSE^
16941 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16942 Verbose mode.
16943
16944 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16945 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16946 Indicates the verbosity of the parsing of GNAT project files.
16947 @xref{Switches Related to Project Files}.
16948
16949 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16950 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16951 Indicates that external variable @var{name} has the value @var{value}.
16952 The Project Manager will use this value for occurrences of
16953 @code{external(name)} when parsing the project file.
16954 @xref{Switches Related to Project Files}.
16955
16956 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16957 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16958 When searching for ALI and object files, look in directory
16959 @var{dir}.
16960
16961 @item ^-I^/SEARCH=^@var{dir}
16962 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16963 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16964
16965 @item ^-I-^/NOCURRENT_DIRECTORY^
16966 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16967 @cindex Source files, suppressing search
16968 Do not look for ALI or object files in the directory
16969 where @code{gnatclean} was invoked.
16970
16971 @end table
16972
16973 @node Examples of gnatclean Usage
16974 @section Examples of @code{gnatclean} Usage
16975
16976 @ifclear vms
16977 @node GNAT and Libraries
16978 @chapter GNAT and Libraries
16979 @cindex Library, building, installing, using
16980
16981 @noindent
16982 This chapter describes how to build and use libraries with GNAT, and also shows
16983 how to recompile the GNAT run-time library. You should be familiar with the
16984 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16985 chapter.
16986
16987 @menu
16988 * Introduction to Libraries in GNAT::
16989 * General Ada Libraries::
16990 * Stand-alone Ada Libraries::
16991 * Rebuilding the GNAT Run-Time Library::
16992 @end menu
16993
16994 @node Introduction to Libraries in GNAT
16995 @section Introduction to Libraries in GNAT
16996
16997 @noindent
16998 A library is, conceptually, a collection of objects which does not have its
16999 own main thread of execution, but rather provides certain services to the
17000 applications that use it. A library can be either statically linked with the
17001 application, in which case its code is directly included in the application,
17002 or, on platforms that support it, be dynamically linked, in which case
17003 its code is shared by all applications making use of this library.
17004
17005 GNAT supports both types of libraries.
17006 In the static case, the compiled code can be provided in different ways. The
17007 simplest approach is to provide directly the set of objects resulting from
17008 compilation of the library source files. Alternatively, you can group the
17009 objects into an archive using whatever commands are provided by the operating
17010 system. For the latter case, the objects are grouped into a shared library.
17011
17012 In the GNAT environment, a library has three types of components:
17013 @itemize @bullet
17014 @item
17015 Source files.
17016 @item
17017 @file{ALI} files.
17018 @xref{The Ada Library Information Files}.
17019 @item
17020 Object files, an archive or a shared library.
17021 @end itemize
17022
17023 @noindent
17024 A GNAT library may expose all its source files, which is useful for
17025 documentation purposes. Alternatively, it may expose only the units needed by
17026 an external user to make use of the library. That is to say, the specs
17027 reflecting the library services along with all the units needed to compile
17028 those specs, which can include generic bodies or any body implementing an
17029 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17030 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17031
17032 All compilation units comprising an application, including those in a library,
17033 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17034 computes the elaboration order from the @file{ALI} files and this is why they
17035 constitute a mandatory part of GNAT libraries. Except in the case of
17036 @emph{stand-alone libraries}, where a specific library elaboration routine is
17037 produced independently of the application(s) using the library.
17038
17039 @node General Ada Libraries
17040 @section General Ada Libraries
17041
17042 @menu
17043 * Building a library::
17044 * Installing a library::
17045 * Using a library::
17046 @end menu
17047
17048 @node Building a library
17049 @subsection Building a library
17050
17051 @noindent
17052 The easiest way to build a library is to use the Project Manager,
17053 which supports a special type of project called a @emph{Library Project}
17054 (@pxref{Library Projects}).
17055
17056 A project is considered a library project, when two project-level attributes
17057 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17058 control different aspects of library configuration, additional optional
17059 project-level attributes can be specified:
17060 @table @code
17061 @item Library_Kind
17062 This attribute controls whether the library is to be static or dynamic
17063
17064 @item Library_Version
17065 This attribute specifies the library version; this value is used
17066 during dynamic linking of shared libraries to determine if the currently
17067 installed versions of the binaries are compatible.
17068
17069 @item Library_Options
17070 @item Library_GCC
17071 These attributes specify additional low-level options to be used during
17072 library generation, and redefine the actual application used to generate
17073 library.
17074 @end table
17075
17076 @noindent
17077 The GNAT Project Manager takes full care of the library maintenance task,
17078 including recompilation of the source files for which objects do not exist
17079 or are not up to date, assembly of the library archive, and installation of
17080 the library (i.e., copying associated source, object and @file{ALI} files
17081 to the specified location).
17082
17083 Here is a simple library project file:
17084 @smallexample @c ada
17085 project My_Lib is
17086    for Source_Dirs use ("src1", "src2");
17087    for Object_Dir use "obj";
17088    for Library_Name use "mylib";
17089    for Library_Dir use "lib";
17090    for Library_Kind use "dynamic";
17091 end My_lib;
17092 @end smallexample
17093
17094 @noindent
17095 and the compilation command to build and install the library:
17096
17097 @smallexample @c ada
17098   $ gnatmake -Pmy_lib
17099 @end smallexample
17100
17101 @noindent
17102 It is not entirely trivial to perform manually all the steps required to
17103 produce a library. We recommend that you use the GNAT Project Manager
17104 for this task. In special cases where this is not desired, the necessary
17105 steps are discussed below.
17106
17107 There are various possibilities for compiling the units that make up the
17108 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17109 with a conventional script. For simple libraries, it is also possible to create
17110 a dummy main program which depends upon all the packages that comprise the
17111 interface of the library. This dummy main program can then be given to
17112 @command{gnatmake}, which will ensure that all necessary objects are built.
17113
17114 After this task is accomplished, you should follow the standard procedure
17115 of the underlying operating system to produce the static or shared library.
17116
17117 Here is an example of such a dummy program:
17118 @smallexample @c ada
17119 @group
17120 with My_Lib.Service1;
17121 with My_Lib.Service2;
17122 with My_Lib.Service3;
17123 procedure My_Lib_Dummy is
17124 begin
17125    null;
17126 end;
17127 @end group
17128 @end smallexample
17129
17130 @noindent
17131 Here are the generic commands that will build an archive or a shared library.
17132
17133 @smallexample
17134 # compiling the library
17135 $ gnatmake -c my_lib_dummy.adb
17136
17137 # we don't need the dummy object itself
17138 $ rm my_lib_dummy.o my_lib_dummy.ali
17139
17140 # create an archive with the remaining objects
17141 $ ar rc libmy_lib.a *.o
17142 # some systems may require "ranlib" to be run as well
17143
17144 # or create a shared library
17145 $ gcc -shared -o libmy_lib.so *.o
17146 # some systems may require the code to have been compiled with -fPIC
17147
17148 # remove the object files that are now in the library
17149 $ rm *.o
17150
17151 # Make the ALI files read-only so that gnatmake will not try to
17152 # regenerate the objects that are in the library
17153 $ chmod -w *.ali
17154 @end smallexample
17155
17156 @noindent
17157 Please note that the library must have a name of the form @file{libxxx.a} or
17158 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17159 the directive @option{-lxxx} at link time.
17160
17161 @node Installing a library
17162 @subsection Installing a library
17163
17164 @noindent
17165 If you use project files, library installation is part of the library build
17166 process. Thus no further action is needed in order to make use of the
17167 libraries that are built as part of the general application build. A usable
17168 version of the library is installed in the directory specified by the
17169 @code{Library_Dir} attribute of the library project file.
17170
17171 You may want to install a library in a context different from where the library
17172 is built. This situation arises with third party suppliers, who may want
17173 to distribute a library in binary form where the user is not expected to be
17174 able to recompile the library. The simplest option in this case is to provide
17175 a project file slightly different from the one used to build the library, by
17176 using the @code{externally_built} attribute. For instance, the project
17177 file used to build the library in the previous section can be changed into the
17178 following one when the library is installed:
17179
17180 @smallexample @c projectfile
17181 project My_Lib is
17182    for Source_Dirs use ("src1", "src2");
17183    for Library_Name use "mylib";
17184    for Library_Dir use "lib";
17185    for Library_Kind use "dynamic";
17186    for Externally_Built use "true";
17187 end My_lib;
17188 @end smallexample
17189
17190 @noindent
17191 This project file assumes that the directories @file{src1},
17192 @file{src2}, and @file{lib} exist in
17193 the directory containing the project file. The @code{externally_built}
17194 attribute makes it clear to the GNAT builder that it should not attempt to
17195 recompile any of the units from this library. It allows the library provider to
17196 restrict the source set to the minimum necessary for clients to make use of the
17197 library as described in the first section of this chapter. It is the
17198 responsibility of the library provider to install the necessary sources, ALI
17199 files and libraries in the directories mentioned in the project file. For
17200 convenience, the user's library project file should be installed in a location
17201 that will be searched automatically by the GNAT
17202 builder. These are the directories referenced in the @code{ADA_LIBRARY_PATH}
17203 environment variable (@pxref{Importing Projects}), and also the default GNAT
17204 library location that can be queried with @command{gnatls -v} and is usually of
17205 the form $gnat_install_root/lib/gnat.
17206
17207 When project files are not an option, it is also possible, but not recommended,
17208 to install the library so that the sources needed to use the library are on the
17209 Ada source path and the ALI files & libraries be on the Ada Object path (see
17210 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17211 administrator can place general-purpose libraries in the default compiler
17212 paths, by specifying the libraries' location in the configuration files
17213 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17214 must be located in the GNAT installation tree at the same place as the gcc spec
17215 file. The location of the gcc spec file can be determined as follows:
17216 @smallexample
17217 $ gcc -v
17218 @end smallexample
17219
17220 @noindent
17221 The configuration files mentioned above have a simple format: each line
17222 must contain one unique directory name.
17223 Those names are added to the corresponding path
17224 in their order of appearance in the file. The names can be either absolute
17225 or relative; in the latter case, they are relative to where theses files
17226 are located.
17227
17228 The files @file{ada_source_path} and @file{ada_object_path} might not be
17229 present in a
17230 GNAT installation, in which case, GNAT will look for its run-time library in
17231 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17232 objects and @file{ALI} files). When the files exist, the compiler does not
17233 look in @file{adainclude} and @file{adalib}, and thus the
17234 @file{ada_source_path} file
17235 must contain the location for the GNAT run-time sources (which can simply
17236 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17237 contain the location for the GNAT run-time objects (which can simply
17238 be @file{adalib}).
17239
17240 You can also specify a new default path to the run-time library at compilation
17241 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17242 the run-time library you want your program to be compiled with. This switch is
17243 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17244 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17245
17246 It is possible to install a library before or after the standard GNAT
17247 library, by reordering the lines in the configuration files. In general, a
17248 library must be installed before the GNAT library if it redefines
17249 any part of it.
17250
17251 @node Using a library
17252 @subsection Using a library
17253
17254 @noindent Once again, the project facility greatly simplifies the use of
17255 libraries. In this context, using a library is just a matter of adding a
17256 @code{with} clause in the user project. For instance, to make use of the
17257 library @code{My_Lib} shown in examples in earlier sections, you can
17258 write:
17259
17260 @smallexample @c projectfile
17261 with "my_lib";
17262 project My_Proj is
17263   ...
17264 end My_Proj;
17265 @end smallexample
17266
17267 Even if you have a third-party, non-Ada library, you can still use GNAT's
17268 Project Manager facility to provide a wrapper for it. For example, the
17269 following project, when @code{with}ed by your main project, will link with the
17270 third-party library @file{liba.a}:
17271
17272 @smallexample @c projectfile
17273 @group
17274 project Liba is
17275    for Externally_Built use "true";
17276    for Library_Dir use "lib";
17277    for Library_Name use "a";
17278    for Library_Kind use "static";
17279 end Liba;
17280 @end group
17281 @end smallexample
17282 This is an alternative to the use of @code{pragma Linker_Options}. It is
17283 especially interesting in the context of systems with several interdependant
17284 static libraries where finding a proper linker order is not easy and best be
17285 left to the tools having visibility over project dependancy information.
17286
17287 @noindent
17288 In order to use an Ada library manually, you need to make sure that this
17289 library is on both your source and object path
17290 (see @ref{Search Paths and the Run-Time Library (RTL)}
17291 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17292 in an archive or a shared library, you need to specify the desired
17293 library at link time.
17294
17295 For example, you can use the library @file{mylib} installed in
17296 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17297
17298 @smallexample
17299 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17300   -largs -lmy_lib
17301 @end smallexample
17302
17303 @noindent
17304 This can be expressed more simply:
17305 @smallexample
17306 $ gnatmake my_appl
17307 @end smallexample
17308 @noindent
17309 when the following conditions are met:
17310 @itemize @bullet
17311 @item
17312 @file{/dir/my_lib_src} has been added by the user to the environment
17313 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17314 @file{ada_source_path}
17315 @item
17316 @file{/dir/my_lib_obj} has been added by the user to the environment
17317 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17318 @file{ada_object_path}
17319 @item
17320 a pragma @code{Linker_Options} has been added to one of the sources.
17321 For example:
17322
17323 @smallexample @c ada
17324 pragma Linker_Options ("-lmy_lib");
17325 @end smallexample
17326 @end itemize
17327
17328 @node Stand-alone Ada Libraries
17329 @section Stand-alone Ada Libraries
17330 @cindex Stand-alone library, building, using
17331
17332 @menu
17333 * Introduction to Stand-alone Libraries::
17334 * Building a Stand-alone Library::
17335 * Creating a Stand-alone Library to be used in a non-Ada context::
17336 * Restrictions in Stand-alone Libraries::
17337 @end menu
17338
17339 @node Introduction to Stand-alone Libraries
17340 @subsection Introduction to Stand-alone Libraries
17341
17342 @noindent
17343 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17344 necessary code to
17345 elaborate the Ada units that are included in the library. In contrast with
17346 an ordinary library, which consists of all sources, objects and @file{ALI}
17347 files of the
17348 library, a SAL may specify a restricted subset of compilation units
17349 to serve as a library interface. In this case, the fully
17350 self-sufficient set of files will normally consist of an objects
17351 archive, the sources of interface units' specs, and the @file{ALI}
17352 files of interface units.
17353 If an interface spec contains a generic unit or an inlined subprogram,
17354 the body's
17355 source must also be provided; if the units that must be provided in the source
17356 form depend on other units, the source and @file{ALI} files of those must
17357 also be provided.
17358
17359 The main purpose of a SAL is to minimize the recompilation overhead of client
17360 applications when a new version of the library is installed. Specifically,
17361 if the interface sources have not changed, client applications do not need to
17362 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17363 version, controlled by @code{Library_Version} attribute, is not changed,
17364 then the clients do not need to be relinked.
17365
17366 SALs also allow the library providers to minimize the amount of library source
17367 text exposed to the clients.  Such ``information hiding'' might be useful or
17368 necessary for various reasons.
17369
17370 Stand-alone libraries are also well suited to be used in an executable whose
17371 main routine is not written in Ada.
17372
17373 @node Building a Stand-alone Library
17374 @subsection Building a Stand-alone Library
17375
17376 @noindent
17377 GNAT's Project facility provides a simple way of building and installing
17378 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17379 To be a Stand-alone Library Project, in addition to the two attributes
17380 that make a project a Library Project (@code{Library_Name} and
17381 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17382 @code{Library_Interface} must be defined.  For example:
17383
17384 @smallexample @c projectfile
17385 @group
17386    for Library_Dir use "lib_dir";
17387    for Library_Name use "dummy";
17388    for Library_Interface use ("int1", "int1.child");
17389 @end group
17390 @end smallexample
17391
17392 @noindent
17393 Attribute @code{Library_Interface} has a non-empty string list value,
17394 each string in the list designating a unit contained in an immediate source
17395 of the project file.
17396
17397 When a Stand-alone Library is built, first the binder is invoked to build
17398 a package whose name depends on the library name
17399 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17400 This binder-generated package includes initialization and
17401 finalization procedures whose
17402 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17403 in the example
17404 above). The object corresponding to this package is included in the library.
17405
17406 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17407 calling of these procedures if a static SAL is built, or if a shared SAL
17408 is built
17409 with the project-level attribute @code{Library_Auto_Init} set to
17410 @code{"false"}.
17411
17412 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17413 (those that are listed in attribute @code{Library_Interface}) are copied to
17414 the Library Directory. As a consequence, only the Interface Units may be
17415 imported from Ada units outside of the library. If other units are imported,
17416 the binding phase will fail.
17417
17418 The attribute @code{Library_Src_Dir} may be specified for a
17419 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17420 single string value. Its value must be the path (absolute or relative to the
17421 project directory) of an existing directory. This directory cannot be the
17422 object directory or one of the source directories, but it can be the same as
17423 the library directory. The sources of the Interface
17424 Units of the library that are needed by an Ada client of the library will be
17425 copied to the designated directory, called the Interface Copy directory.
17426 These sources include the specs of the Interface Units, but they may also
17427 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17428 are used, or when there is a generic unit in the spec. Before the sources
17429 are copied to the Interface Copy directory, an attempt is made to delete all
17430 files in the Interface Copy directory.
17431
17432 Building stand-alone libraries by hand is somewhat tedious, but for those
17433 occasions when it is necessary here are the steps that you need to perform:
17434 @itemize @bullet
17435 @item
17436 Compile all library sources.
17437
17438 @item
17439 Invoke the binder with the switch @option{-n} (No Ada main program),
17440 with all the @file{ALI} files of the interfaces, and
17441 with the switch @option{-L} to give specific names to the @code{init}
17442 and @code{final} procedures.  For example:
17443 @smallexample
17444   gnatbind -n int1.ali int2.ali -Lsal1
17445 @end smallexample
17446
17447 @item
17448 Compile the binder generated file:
17449 @smallexample
17450   gcc -c b~int2.adb
17451 @end smallexample
17452
17453 @item
17454 Link the dynamic library with all the necessary object files,
17455 indicating to the linker the names of the @code{init} (and possibly
17456 @code{final}) procedures for automatic initialization (and finalization).
17457 The built library should be placed in a directory different from
17458 the object directory.
17459
17460 @item
17461 Copy the @code{ALI} files of the interface to the library directory,
17462 add in this copy an indication that it is an interface to a SAL
17463 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17464 with letter ``P'') and make the modified copy of the @file{ALI} file
17465 read-only.
17466 @end itemize
17467
17468 @noindent
17469 Using SALs is not different from using other libraries
17470 (see @ref{Using a library}).
17471
17472 @node Creating a Stand-alone Library to be used in a non-Ada context
17473 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17474
17475 @noindent
17476 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17477 a non-Ada context.
17478
17479 The only extra step required is to ensure that library interface subprograms
17480 are compatible with the main program, by means of @code{pragma Export}
17481 or @code{pragma Convention}.
17482
17483 Here is an example of simple library interface for use with C main program:
17484
17485 @smallexample @c ada
17486 package Interface is
17487
17488    procedure Do_Something;
17489    pragma Export (C, Do_Something, "do_something");
17490
17491    procedure Do_Something_Else;
17492    pragma Export (C, Do_Something_Else, "do_something_else");
17493
17494 end Interface;
17495 @end smallexample
17496
17497 @noindent
17498 On the foreign language side, you must provide a ``foreign'' view of the
17499 library interface; remember that it should contain elaboration routines in
17500 addition to interface subprograms.
17501
17502 The example below shows the content of @code{mylib_interface.h} (note
17503 that there is no rule for the naming of this file, any name can be used)
17504 @smallexample
17505 /* the library elaboration procedure */
17506 extern void mylibinit (void);
17507
17508 /* the library finalization procedure */
17509 extern void mylibfinal (void);
17510
17511 /* the interface exported by the library */
17512 extern void do_something (void);
17513 extern void do_something_else (void);
17514 @end smallexample
17515
17516 @noindent
17517 Libraries built as explained above can be used from any program, provided
17518 that the elaboration procedures (named @code{mylibinit} in the previous
17519 example) are called before the library services are used. Any number of
17520 libraries can be used simultaneously, as long as the elaboration
17521 procedure of each library is called.
17522
17523 Below is an example of a C program that uses the @code{mylib} library.
17524
17525 @smallexample
17526 #include "mylib_interface.h"
17527
17528 int
17529 main (void)
17530 @{
17531    /* First, elaborate the library before using it */
17532    mylibinit ();
17533
17534    /* Main program, using the library exported entities */
17535    do_something ();
17536    do_something_else ();
17537
17538    /* Library finalization at the end of the program */
17539    mylibfinal ();
17540    return 0;
17541 @}
17542 @end smallexample
17543
17544 @noindent
17545 Note that invoking any library finalization procedure generated by
17546 @code{gnatbind} shuts down the Ada run-time environment.
17547 Consequently, the
17548 finalization of all Ada libraries must be performed at the end of the program.
17549 No call to these libraries or to the Ada run-time library should be made
17550 after the finalization phase.
17551
17552 @node Restrictions in Stand-alone Libraries
17553 @subsection Restrictions in Stand-alone Libraries
17554
17555 @noindent
17556 The pragmas listed below should be used with caution inside libraries,
17557 as they can create incompatibilities with other Ada libraries:
17558 @itemize @bullet
17559 @item pragma @code{Locking_Policy}
17560 @item pragma @code{Queuing_Policy}
17561 @item pragma @code{Task_Dispatching_Policy}
17562 @item pragma @code{Unreserve_All_Interrupts}
17563 @end itemize
17564
17565 @noindent
17566 When using a library that contains such pragmas, the user must make sure
17567 that all libraries use the same pragmas with the same values. Otherwise,
17568 @code{Program_Error} will
17569 be raised during the elaboration of the conflicting
17570 libraries. The usage of these pragmas and its consequences for the user
17571 should therefore be well documented.
17572
17573 Similarly, the traceback in the exception occurrence mechanism should be
17574 enabled or disabled in a consistent manner across all libraries.
17575 Otherwise, Program_Error will be raised during the elaboration of the
17576 conflicting libraries.
17577
17578 If the @code{Version} or @code{Body_Version}
17579 attributes are used inside a library, then you need to
17580 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17581 libraries, so that version identifiers can be properly computed.
17582 In practice these attributes are rarely used, so this is unlikely
17583 to be a consideration.
17584
17585 @node  Rebuilding the GNAT Run-Time Library
17586 @section Rebuilding the GNAT Run-Time Library
17587 @cindex GNAT Run-Time Library, rebuilding
17588
17589 @noindent
17590 It may be useful to recompile the GNAT library in various contexts, the
17591 most important one being the use of partition-wide configuration pragmas
17592 such as @code{Normalize_Scalars}. A special Makefile called
17593 @code{Makefile.adalib} is provided to that effect and can be found in
17594 the directory containing the GNAT library. The location of this
17595 directory depends on the way the GNAT environment has been installed and can
17596 be determined by means of the command:
17597
17598 @smallexample
17599 $ gnatls -v
17600 @end smallexample
17601
17602 @noindent
17603 The last entry in the object search path usually contains the
17604 gnat library. This Makefile contains its own documentation and in
17605 particular the set of instructions needed to rebuild a new library and
17606 to use it.
17607
17608 @node Using the GNU make Utility
17609 @chapter Using the GNU @code{make} Utility
17610 @findex make
17611
17612 @noindent
17613 This chapter offers some examples of makefiles that solve specific
17614 problems. It does not explain how to write a makefile (see the GNU make
17615 documentation), nor does it try to replace the @command{gnatmake} utility
17616 (@pxref{The GNAT Make Program gnatmake}).
17617
17618 All the examples in this section are specific to the GNU version of
17619 make. Although @code{make} is a standard utility, and the basic language
17620 is the same, these examples use some advanced features found only in
17621 @code{GNU make}.
17622
17623 @menu
17624 * Using gnatmake in a Makefile::
17625 * Automatically Creating a List of Directories::
17626 * Generating the Command Line Switches::
17627 * Overcoming Command Line Length Limits::
17628 @end menu
17629
17630 @node Using gnatmake in a Makefile
17631 @section Using gnatmake in a Makefile
17632 @findex makefile
17633 @cindex GNU make
17634
17635 @noindent
17636 Complex project organizations can be handled in a very powerful way by
17637 using GNU make combined with gnatmake. For instance, here is a Makefile
17638 which allows you to build each subsystem of a big project into a separate
17639 shared library. Such a makefile allows you to significantly reduce the link
17640 time of very big applications while maintaining full coherence at
17641 each step of the build process.
17642
17643 The list of dependencies are handled automatically by
17644 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17645 the appropriate directories.
17646
17647 Note that you should also read the example on how to automatically
17648 create the list of directories
17649 (@pxref{Automatically Creating a List of Directories})
17650 which might help you in case your project has a lot of subdirectories.
17651
17652 @smallexample
17653 @iftex
17654 @leftskip=0cm
17655 @font@heightrm=cmr8
17656 @heightrm
17657 @end iftex
17658 ## This Makefile is intended to be used with the following directory
17659 ## configuration:
17660 ##  - The sources are split into a series of csc (computer software components)
17661 ##    Each of these csc is put in its own directory.
17662 ##    Their name are referenced by the directory names.
17663 ##    They will be compiled into shared library (although this would also work
17664 ##    with static libraries
17665 ##  - The main program (and possibly other packages that do not belong to any
17666 ##    csc is put in the top level directory (where the Makefile is).
17667 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17668 ##                    \_ second_csc (sources) __ lib (will contain the library)
17669 ##                    \_ ...
17670 ## Although this Makefile is build for shared library, it is easy to modify
17671 ## to build partial link objects instead (modify the lines with -shared and
17672 ## gnatlink below)
17673 ##
17674 ## With this makefile, you can change any file in the system or add any new
17675 ## file, and everything will be recompiled correctly (only the relevant shared
17676 ## objects will be recompiled, and the main program will be re-linked).
17677
17678 # The list of computer software component for your project. This might be
17679 # generated automatically.
17680 CSC_LIST=aa bb cc
17681
17682 # Name of the main program (no extension)
17683 MAIN=main
17684
17685 # If we need to build objects with -fPIC, uncomment the following line
17686 #NEED_FPIC=-fPIC
17687
17688 # The following variable should give the directory containing libgnat.so
17689 # You can get this directory through 'gnatls -v'. This is usually the last
17690 # directory in the Object_Path.
17691 GLIB=...
17692
17693 # The directories for the libraries
17694 # (This macro expands the list of CSC to the list of shared libraries, you
17695 # could simply use the expanded form :
17696 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17697 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17698
17699 $@{MAIN@}: objects $@{LIB_DIR@}
17700     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17701     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17702
17703 objects::
17704     # recompile the sources
17705     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17706
17707 # Note: In a future version of GNAT, the following commands will be simplified
17708 # by a new tool, gnatmlib
17709 $@{LIB_DIR@}:
17710     mkdir -p $@{dir $@@ @}
17711     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17712     cd $@{dir $@@ @}; cp -f ../*.ali .
17713
17714 # The dependencies for the modules
17715 # Note that we have to force the expansion of *.o, since in some cases
17716 # make won't be able to do it itself.
17717 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17718 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17719 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17720
17721 # Make sure all of the shared libraries are in the path before starting the
17722 # program
17723 run::
17724     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17725
17726 clean::
17727     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17728     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17729     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17730     $@{RM@} *.o *.ali $@{MAIN@}
17731 @end smallexample
17732
17733 @node Automatically Creating a List of Directories
17734 @section Automatically Creating a List of Directories
17735
17736 @noindent
17737 In most makefiles, you will have to specify a list of directories, and
17738 store it in a variable. For small projects, it is often easier to
17739 specify each of them by hand, since you then have full control over what
17740 is the proper order for these directories, which ones should be
17741 included...
17742
17743 However, in larger projects, which might involve hundreds of
17744 subdirectories, it might be more convenient to generate this list
17745 automatically.
17746
17747 The example below presents two methods. The first one, although less
17748 general, gives you more control over the list. It involves wildcard
17749 characters, that are automatically expanded by @code{make}. Its
17750 shortcoming is that you need to explicitly specify some of the
17751 organization of your project, such as for instance the directory tree
17752 depth, whether some directories are found in a separate tree,...
17753
17754 The second method is the most general one. It requires an external
17755 program, called @code{find}, which is standard on all Unix systems. All
17756 the directories found under a given root directory will be added to the
17757 list.
17758
17759 @smallexample
17760 @iftex
17761 @leftskip=0cm
17762 @font@heightrm=cmr8
17763 @heightrm
17764 @end iftex
17765 # The examples below are based on the following directory hierarchy:
17766 # All the directories can contain any number of files
17767 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17768 #                       ->  ab
17769 #                       ->  ac
17770 #                ->  b  ->  ba  ->  baa
17771 #                       ->  bb
17772 #                       ->  bc
17773 # This Makefile creates a variable called DIRS, that can be reused any time
17774 # you need this list (see the other examples in this section)
17775
17776 # The root of your project's directory hierarchy
17777 ROOT_DIRECTORY=.
17778
17779 ####
17780 # First method: specify explicitly the list of directories
17781 # This allows you to specify any subset of all the directories you need.
17782 ####
17783
17784 DIRS := a/aa/ a/ab/ b/ba/
17785
17786 ####
17787 # Second method: use wildcards
17788 # Note that the argument(s) to wildcard below should end with a '/'.
17789 # Since wildcards also return file names, we have to filter them out
17790 # to avoid duplicate directory names.
17791 # We thus use make's @code{dir} and @code{sort} functions.
17792 # It sets DIRs to the following value (note that the directories aaa and baa
17793 # are not given, unless you change the arguments to wildcard).
17794 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17795 ####
17796
17797 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17798                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17799
17800 ####
17801 # Third method: use an external program
17802 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17803 # This is the most complete command: it sets DIRs to the following value:
17804 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17805 ####
17806
17807 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17808
17809 @end smallexample
17810
17811 @node Generating the Command Line Switches
17812 @section Generating the Command Line Switches
17813
17814 @noindent
17815 Once you have created the list of directories as explained in the
17816 previous section (@pxref{Automatically Creating a List of Directories}),
17817 you can easily generate the command line arguments to pass to gnatmake.
17818
17819 For the sake of completeness, this example assumes that the source path
17820 is not the same as the object path, and that you have two separate lists
17821 of directories.
17822
17823 @smallexample
17824 # see "Automatically creating a list of directories" to create
17825 # these variables
17826 SOURCE_DIRS=
17827 OBJECT_DIRS=
17828
17829 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17830 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17831
17832 all:
17833         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17834 @end smallexample
17835
17836 @node Overcoming Command Line Length Limits
17837 @section Overcoming Command Line Length Limits
17838
17839 @noindent
17840 One problem that might be encountered on big projects is that many
17841 operating systems limit the length of the command line. It is thus hard to give
17842 gnatmake the list of source and object directories.
17843
17844 This example shows how you can set up environment variables, which will
17845 make @command{gnatmake} behave exactly as if the directories had been
17846 specified on the command line, but have a much higher length limit (or
17847 even none on most systems).
17848
17849 It assumes that you have created a list of directories in your Makefile,
17850 using one of the methods presented in
17851 @ref{Automatically Creating a List of Directories}.
17852 For the sake of completeness, we assume that the object
17853 path (where the ALI files are found) is different from the sources patch.
17854
17855 Note a small trick in the Makefile below: for efficiency reasons, we
17856 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17857 expanded immediately by @code{make}. This way we overcome the standard
17858 make behavior which is to expand the variables only when they are
17859 actually used.
17860
17861 On Windows, if you are using the standard Windows command shell, you must
17862 replace colons with semicolons in the assignments to these variables.
17863
17864 @smallexample
17865 @iftex
17866 @leftskip=0cm
17867 @font@heightrm=cmr8
17868 @heightrm
17869 @end iftex
17870 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17871 # This is the same thing as putting the -I arguments on the command line.
17872 # (the equivalent of using -aI on the command line would be to define
17873 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17874 # You can of course have different values for these variables.
17875 #
17876 # Note also that we need to keep the previous values of these variables, since
17877 # they might have been set before running 'make' to specify where the GNAT
17878 # library is installed.
17879
17880 # see "Automatically creating a list of directories" to create these
17881 # variables
17882 SOURCE_DIRS=
17883 OBJECT_DIRS=
17884
17885 empty:=
17886 space:=$@{empty@} $@{empty@}
17887 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17888 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17889 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17890 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17891 export ADA_INCLUDE_PATH
17892 export ADA_OBJECT_PATH
17893
17894 all:
17895         gnatmake main_unit
17896 @end smallexample
17897 @end ifclear
17898
17899 @node Memory Management Issues
17900 @chapter Memory Management Issues
17901
17902 @noindent
17903 This chapter describes some useful memory pools provided in the GNAT library
17904 and in particular the GNAT Debug Pool facility, which can be used to detect
17905 incorrect uses of access values (including ``dangling references'').
17906 @ifclear vms
17907 It also describes the @command{gnatmem} tool, which can be used to track down
17908 ``memory leaks''.
17909 @end ifclear
17910
17911 @menu
17912 * Some Useful Memory Pools::
17913 * The GNAT Debug Pool Facility::
17914 @ifclear vms
17915 * The gnatmem Tool::
17916 @end ifclear
17917 @end menu
17918
17919 @node Some Useful Memory Pools
17920 @section Some Useful Memory Pools
17921 @findex Memory Pool
17922 @cindex storage, pool
17923
17924 @noindent
17925 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17926 storage pool. Allocations use the standard system call @code{malloc} while
17927 deallocations use the standard system call @code{free}. No reclamation is
17928 performed when the pool goes out of scope. For performance reasons, the
17929 standard default Ada allocators/deallocators do not use any explicit storage
17930 pools but if they did, they could use this storage pool without any change in
17931 behavior. That is why this storage pool is used  when the user
17932 manages to make the default implicit allocator explicit as in this example:
17933 @smallexample @c ada
17934    type T1 is access Something;
17935     -- no Storage pool is defined for T2
17936    type T2 is access Something_Else;
17937    for T2'Storage_Pool use T1'Storage_Pool;
17938    -- the above is equivalent to
17939    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17940 @end smallexample
17941
17942 @noindent
17943 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17944 pool. The allocation strategy is similar to @code{Pool_Local}'s
17945 except that the all
17946 storage allocated with this pool is reclaimed when the pool object goes out of
17947 scope. This pool provides a explicit mechanism similar to the implicit one
17948 provided by several Ada 83 compilers for allocations performed through a local
17949 access type and whose purpose was to reclaim memory when exiting the
17950 scope of a given local access. As an example, the following program does not
17951 leak memory even though it does not perform explicit deallocation:
17952
17953 @smallexample @c ada
17954 with System.Pool_Local;
17955 procedure Pooloc1 is
17956    procedure Internal is
17957       type A is access Integer;
17958       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17959       for A'Storage_Pool use X;
17960       v : A;
17961    begin
17962       for I in  1 .. 50 loop
17963          v := new Integer;
17964       end loop;
17965    end Internal;
17966 begin
17967    for I in  1 .. 100 loop
17968       Internal;
17969    end loop;
17970 end Pooloc1;
17971 @end smallexample
17972
17973 @noindent
17974 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17975 @code{Storage_Size} is specified for an access type.
17976 The whole storage for the pool is
17977 allocated at once, usually on the stack at the point where the access type is
17978 elaborated. It is automatically reclaimed when exiting the scope where the
17979 access type is defined. This package is not intended to be used directly by the
17980 user and it is implicitly used for each such declaration:
17981
17982 @smallexample @c ada
17983    type T1 is access Something;
17984    for T1'Storage_Size use 10_000;
17985 @end smallexample
17986
17987
17988 @node The GNAT Debug Pool Facility
17989 @section The GNAT Debug Pool Facility
17990 @findex Debug Pool
17991 @cindex storage, pool, memory corruption
17992
17993 @noindent
17994 The use of unchecked deallocation and unchecked conversion can easily
17995 lead to incorrect memory references. The problems generated by such
17996 references are usually difficult to tackle because the symptoms can be
17997 very remote from the origin of the problem. In such cases, it is
17998 very helpful to detect the problem as early as possible. This is the
17999 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18000
18001 In order to use the GNAT specific debugging pool, the user must
18002 associate a debug pool object with each of the access types that may be
18003 related to suspected memory problems. See Ada Reference Manual 13.11.
18004 @smallexample @c ada
18005 type Ptr is access Some_Type;
18006 Pool : GNAT.Debug_Pools.Debug_Pool;
18007 for Ptr'Storage_Pool use Pool;
18008 @end smallexample
18009
18010 @noindent
18011 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18012 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18013 allow the user to redefine allocation and deallocation strategies. They
18014 also provide a checkpoint for each dereference, through the use of
18015 the primitive operation @code{Dereference} which is implicitly called at
18016 each dereference of an access value.
18017
18018 Once an access type has been associated with a debug pool, operations on
18019 values of the type may raise four distinct exceptions,
18020 which correspond to four potential kinds of memory corruption:
18021 @itemize @bullet
18022 @item
18023 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18024 @item
18025 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18026 @item
18027 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18028 @item
18029 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18030 @end itemize
18031
18032 @noindent
18033 For types associated with a Debug_Pool, dynamic allocation is performed using
18034 the standard GNAT allocation routine. References to all allocated chunks of
18035 memory are kept in an internal dictionary. Several deallocation strategies are
18036 provided, whereupon the user can choose to release the memory to the system,
18037 keep it allocated for further invalid access checks, or fill it with an easily
18038 recognizable pattern for debug sessions. The memory pattern is the old IBM
18039 hexadecimal convention: @code{16#DEADBEEF#}.
18040
18041 See the documentation in the file g-debpoo.ads for more information on the
18042 various strategies.
18043
18044 Upon each dereference, a check is made that the access value denotes a
18045 properly allocated memory location. Here is a complete example of use of
18046 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18047 @smallexample @c ada
18048 @iftex
18049 @leftskip=0cm
18050 @end iftex
18051 with Gnat.Io; use Gnat.Io;
18052 with Unchecked_Deallocation;
18053 with Unchecked_Conversion;
18054 with GNAT.Debug_Pools;
18055 with System.Storage_Elements;
18056 with Ada.Exceptions; use Ada.Exceptions;
18057 procedure Debug_Pool_Test is
18058
18059    type T is access Integer;
18060    type U is access all T;
18061
18062    P : GNAT.Debug_Pools.Debug_Pool;
18063    for T'Storage_Pool use P;
18064
18065    procedure Free is new Unchecked_Deallocation (Integer, T);
18066    function UC is new Unchecked_Conversion (U, T);
18067    A, B : aliased T;
18068
18069    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18070
18071 begin
18072    Info (P);
18073    A := new Integer;
18074    B := new Integer;
18075    B := A;
18076    Info (P);
18077    Free (A);
18078    begin
18079       Put_Line (Integer'Image(B.all));
18080    exception
18081       when E : others => Put_Line ("raised: " & Exception_Name (E));
18082    end;
18083    begin
18084       Free (B);
18085    exception
18086       when E : others => Put_Line ("raised: " & Exception_Name (E));
18087    end;
18088    B := UC(A'Access);
18089    begin
18090       Put_Line (Integer'Image(B.all));
18091    exception
18092       when E : others => Put_Line ("raised: " & Exception_Name (E));
18093    end;
18094    begin
18095       Free (B);
18096    exception
18097       when E : others => Put_Line ("raised: " & Exception_Name (E));
18098    end;
18099    Info (P);
18100 end Debug_Pool_Test;
18101 @end smallexample
18102
18103 @noindent
18104 The debug pool mechanism provides the following precise diagnostics on the
18105 execution of this erroneous program:
18106 @smallexample
18107 Debug Pool info:
18108   Total allocated bytes :  0
18109   Total deallocated bytes :  0
18110   Current Water Mark:  0
18111   High Water Mark:  0
18112
18113 Debug Pool info:
18114   Total allocated bytes :  8
18115   Total deallocated bytes :  0
18116   Current Water Mark:  8
18117   High Water Mark:  8
18118
18119 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18120 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18121 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18122 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18123 Debug Pool info:
18124   Total allocated bytes :  8
18125   Total deallocated bytes :  4
18126   Current Water Mark:  4
18127   High Water Mark:  8
18128 @end smallexample
18129
18130 @ifclear vms
18131 @node The gnatmem Tool
18132 @section The @command{gnatmem} Tool
18133 @findex gnatmem
18134
18135 @noindent
18136 The @code{gnatmem} utility monitors dynamic allocation and
18137 deallocation activity in a program, and displays information about
18138 incorrect deallocations and possible sources of memory leaks.
18139 It provides three type of information:
18140 @itemize @bullet
18141 @item
18142 General information concerning memory management, such as the total
18143 number of allocations and deallocations, the amount of allocated
18144 memory and the high water mark, i.e. the largest amount of allocated
18145 memory in the course of program execution.
18146
18147 @item
18148 Backtraces for all incorrect deallocations, that is to say deallocations
18149 which do not correspond to a valid allocation.
18150
18151 @item
18152 Information on each allocation that is potentially the origin of a memory
18153 leak.
18154 @end itemize
18155
18156 @menu
18157 * Running gnatmem::
18158 * Switches for gnatmem::
18159 * Example of gnatmem Usage::
18160 @end menu
18161
18162 @node Running gnatmem
18163 @subsection Running @code{gnatmem}
18164
18165 @noindent
18166 @code{gnatmem} makes use of the output created by the special version of
18167 allocation and deallocation routines that record call information. This
18168 allows to obtain accurate dynamic memory usage history at a minimal cost to
18169 the execution speed. Note however, that @code{gnatmem} is not supported on
18170 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18171 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18172
18173 @noindent
18174 The @code{gnatmem} command has the form
18175
18176 @smallexample
18177    $ gnatmem [switches] user_program
18178 @end smallexample
18179
18180 @noindent
18181 The program must have been linked with the instrumented version of the
18182 allocation and deallocation routines. This is done by linking with the
18183 @file{libgmem.a} library. For correct symbolic backtrace information,
18184 the user program should be compiled with debugging options
18185 @ref{Switches for gcc}. For example to build @file{my_program}:
18186
18187 @smallexample
18188 $ gnatmake -g my_program -largs -lgmem
18189 @end smallexample
18190
18191 @noindent
18192 When running @file{my_program} the file @file{gmem.out} is produced. This file
18193 contains information about all allocations and deallocations done by the
18194 program. It is produced by the instrumented allocations and
18195 deallocations routines and will be used by @code{gnatmem}.
18196
18197 @noindent
18198 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18199 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18200 @code{-i} switch, gnatmem will assume that this file can be found in the
18201 current directory. For example, after you have executed @file{my_program},
18202 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18203
18204 @smallexample
18205 $ gnatmem my_program
18206 @end smallexample
18207
18208 @noindent
18209 This will produce the output with the following format:
18210
18211 *************** debut cc
18212 @smallexample
18213 $ gnatmem my_program
18214
18215 Global information
18216 ------------------
18217    Total number of allocations        :  45
18218    Total number of deallocations      :   6
18219    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18220    High Water Mark                    :  11.40 Kilobytes
18221
18222 .
18223 .
18224 .
18225 Allocation Root # 2
18226 -------------------
18227  Number of non freed allocations    :  11
18228  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18229  High Water Mark                    :   1.27 Kilobytes
18230  Backtrace                          :
18231    my_program.adb:23 my_program.alloc
18232 .
18233 .
18234 .
18235 @end smallexample
18236
18237 The first block of output gives general information. In this case, the
18238 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18239 Unchecked_Deallocation routine occurred.
18240
18241 @noindent
18242 Subsequent paragraphs display  information on all allocation roots.
18243 An allocation root is a specific point in the execution of the program
18244 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18245 construct. This root is represented by an execution backtrace (or subprogram
18246 call stack). By default the backtrace depth for allocations roots is 1, so
18247 that a root corresponds exactly to a source location. The backtrace can
18248 be made deeper, to make the root more specific.
18249
18250 @node Switches for gnatmem
18251 @subsection Switches for @code{gnatmem}
18252
18253 @noindent
18254 @code{gnatmem} recognizes the following switches:
18255
18256 @table @option
18257
18258 @item -q
18259 @cindex @option{-q} (@code{gnatmem})
18260 Quiet. Gives the minimum output needed to identify the origin of the
18261 memory leaks. Omits statistical information.
18262
18263 @item @var{N}
18264 @cindex @var{N} (@code{gnatmem})
18265 N is an integer literal (usually between 1 and 10) which controls the
18266 depth of the backtraces defining allocation root. The default value for
18267 N is 1. The deeper the backtrace, the more precise the localization of
18268 the root. Note that the total number of roots can depend on this
18269 parameter. This parameter must be specified @emph{before} the name of the
18270 executable to be analyzed, to avoid ambiguity.
18271
18272 @item -b n
18273 @cindex @option{-b} (@code{gnatmem})
18274 This switch has the same effect as just depth parameter.
18275
18276 @item -i @var{file}
18277 @cindex @option{-i} (@code{gnatmem})
18278 Do the @code{gnatmem} processing starting from @file{file}, rather than
18279 @file{gmem.out} in the current directory.
18280
18281 @item -m n
18282 @cindex @option{-m} (@code{gnatmem})
18283 This switch causes @code{gnatmem} to mask the allocation roots that have less
18284 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18285 examine even the roots that didn't result in leaks.
18286
18287 @item -s order
18288 @cindex @option{-s} (@code{gnatmem})
18289 This switch causes @code{gnatmem} to sort the allocation roots according to the
18290 specified order of sort criteria, each identified by a single letter. The
18291 currently supported criteria are @code{n, h, w} standing respectively for
18292 number of unfreed allocations, high watermark, and final watermark
18293 corresponding to a specific root. The default order is @code{nwh}.
18294
18295 @end table
18296
18297 @node Example of gnatmem Usage
18298 @subsection Example of @code{gnatmem} Usage
18299
18300 @noindent
18301 The following example shows the use of @code{gnatmem}
18302 on a simple memory-leaking program.
18303 Suppose that we have the following Ada program:
18304
18305 @smallexample @c ada
18306 @group
18307 @cartouche
18308 with Unchecked_Deallocation;
18309 procedure Test_Gm is
18310
18311    type T is array (1..1000) of Integer;
18312    type Ptr is access T;
18313    procedure Free is new Unchecked_Deallocation (T, Ptr);
18314    A : Ptr;
18315
18316    procedure My_Alloc is
18317    begin
18318       A := new T;
18319    end My_Alloc;
18320
18321    procedure My_DeAlloc is
18322       B : Ptr := A;
18323    begin
18324       Free (B);
18325    end My_DeAlloc;
18326
18327 begin
18328    My_Alloc;
18329    for I in 1 .. 5 loop
18330       for J in I .. 5 loop
18331          My_Alloc;
18332       end loop;
18333       My_Dealloc;
18334    end loop;
18335 end;
18336 @end cartouche
18337 @end group
18338 @end smallexample
18339
18340 @noindent
18341 The program needs to be compiled with debugging option and linked with
18342 @code{gmem} library:
18343
18344 @smallexample
18345 $ gnatmake -g test_gm -largs -lgmem
18346 @end smallexample
18347
18348 @noindent
18349 Then we execute the program as usual:
18350
18351 @smallexample
18352 $ test_gm
18353 @end smallexample
18354
18355 @noindent
18356 Then @code{gnatmem} is invoked simply with
18357 @smallexample
18358 $ gnatmem test_gm
18359 @end smallexample
18360
18361 @noindent
18362 which produces the following output (result may vary on different platforms):
18363
18364 @smallexample
18365 Global information
18366 ------------------
18367    Total number of allocations        :  18
18368    Total number of deallocations      :   5
18369    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18370    High Water Mark                    :  56.90 Kilobytes
18371
18372 Allocation Root # 1
18373 -------------------
18374  Number of non freed allocations    :  11
18375  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18376  High Water Mark                    :  46.88 Kilobytes
18377  Backtrace                          :
18378    test_gm.adb:11 test_gm.my_alloc
18379
18380 Allocation Root # 2
18381 -------------------
18382  Number of non freed allocations    :   1
18383  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18384  High Water Mark                    :  10.02 Kilobytes
18385  Backtrace                          :
18386    s-secsta.adb:81 system.secondary_stack.ss_init
18387
18388 Allocation Root # 3
18389 -------------------
18390  Number of non freed allocations    :   1
18391  Final Water Mark (non freed mem)   :  12 Bytes
18392  High Water Mark                    :  12 Bytes
18393  Backtrace                          :
18394    s-secsta.adb:181 system.secondary_stack.ss_init
18395 @end smallexample
18396
18397 @noindent
18398 Note that the GNAT run time contains itself a certain number of
18399 allocations that have no  corresponding deallocation,
18400 as shown here for root #2 and root
18401 #3. This is a normal behavior when the number of non freed allocations
18402 is one, it allocates dynamic data structures that the run time needs for
18403 the complete lifetime of the program. Note also that there is only one
18404 allocation root in the user program with a single line back trace:
18405 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18406 program shows that 'My_Alloc' is called at 2 different points in the
18407 source (line 21 and line 24). If those two allocation roots need to be
18408 distinguished, the backtrace depth parameter can be used:
18409
18410 @smallexample
18411 $ gnatmem 3 test_gm
18412 @end smallexample
18413
18414 @noindent
18415 which will give the following output:
18416
18417 @smallexample
18418 Global information
18419 ------------------
18420    Total number of allocations        :  18
18421    Total number of deallocations      :   5
18422    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18423    High Water Mark                    :  56.90 Kilobytes
18424
18425 Allocation Root # 1
18426 -------------------
18427  Number of non freed allocations    :  10
18428  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18429  High Water Mark                    :  42.97 Kilobytes
18430  Backtrace                          :
18431    test_gm.adb:11 test_gm.my_alloc
18432    test_gm.adb:24 test_gm
18433    b_test_gm.c:52 main
18434
18435 Allocation Root # 2
18436 -------------------
18437  Number of non freed allocations    :   1
18438  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18439  High Water Mark                    :  10.02 Kilobytes
18440  Backtrace                          :
18441    s-secsta.adb:81  system.secondary_stack.ss_init
18442    s-secsta.adb:283 <system__secondary_stack___elabb>
18443    b_test_gm.c:33   adainit
18444
18445 Allocation Root # 3
18446 -------------------
18447  Number of non freed allocations    :   1
18448  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18449  High Water Mark                    :   3.91 Kilobytes
18450  Backtrace                          :
18451    test_gm.adb:11 test_gm.my_alloc
18452    test_gm.adb:21 test_gm
18453    b_test_gm.c:52 main
18454
18455 Allocation Root # 4
18456 -------------------
18457  Number of non freed allocations    :   1
18458  Final Water Mark (non freed mem)   :  12 Bytes
18459  High Water Mark                    :  12 Bytes
18460  Backtrace                          :
18461    s-secsta.adb:181 system.secondary_stack.ss_init
18462    s-secsta.adb:283 <system__secondary_stack___elabb>
18463    b_test_gm.c:33   adainit
18464 @end smallexample
18465
18466 @noindent
18467 The allocation root #1 of the first example has been split in 2 roots #1
18468 and #3 thanks to the more precise associated backtrace.
18469
18470 @end ifclear
18471
18472 @node Creating Sample Bodies Using gnatstub
18473 @chapter Creating Sample Bodies Using @command{gnatstub}
18474 @findex gnatstub
18475
18476 @noindent
18477 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18478 for library unit declarations.
18479
18480 To create a body stub, @command{gnatstub} has to compile the library
18481 unit declaration. Therefore, bodies can be created only for legal
18482 library units. Moreover, if a library unit depends semantically upon
18483 units located outside the current directory, you have to provide
18484 the source search path when calling @command{gnatstub}, see the description
18485 of @command{gnatstub} switches below.
18486
18487 @menu
18488 * Running gnatstub::
18489 * Switches for gnatstub::
18490 @end menu
18491
18492 @node Running gnatstub
18493 @section Running @command{gnatstub}
18494
18495 @noindent
18496 @command{gnatstub} has the command-line interface of the form
18497
18498 @smallexample
18499 $ gnatstub [switches] filename [directory]
18500 @end smallexample
18501
18502 @noindent
18503 where
18504 @table @emph
18505 @item filename
18506 is the name of the source file that contains a library unit declaration
18507 for which a body must be created. The file name may contain the path
18508 information.
18509 The file name does not have to follow the GNAT file name conventions. If the
18510 name
18511 does not follow GNAT file naming conventions, the name of the body file must
18512 be provided
18513 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18514 If the file name follows the GNAT file naming
18515 conventions and the name of the body file is not provided,
18516 @command{gnatstub}
18517 creates the name
18518 of the body file from the argument file name by replacing the @file{.ads}
18519 suffix
18520 with the @file{.adb} suffix.
18521
18522 @item directory
18523 indicates the directory in which the body stub is to be placed (the default
18524 is the
18525 current directory)
18526
18527 @item switches
18528 is an optional sequence of switches as described in the next section
18529 @end table
18530
18531 @node Switches for gnatstub
18532 @section Switches for @command{gnatstub}
18533
18534 @table @option
18535 @c !sort!
18536
18537 @item ^-f^/FULL^
18538 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18539 If the destination directory already contains a file with the name of the
18540 body file
18541 for the argument spec file, replace it with the generated body stub.
18542
18543 @item ^-hs^/HEADER=SPEC^
18544 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18545 Put the comment header (i.e., all the comments preceding the
18546 compilation unit) from the source of the library unit declaration
18547 into the body stub.
18548
18549 @item ^-hg^/HEADER=GENERAL^
18550 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18551 Put a sample comment header into the body stub.
18552
18553 @ifclear vms
18554 @item -IDIR
18555 @cindex @option{-IDIR} (@command{gnatstub})
18556 @itemx -I-
18557 @cindex @option{-I-} (@command{gnatstub})
18558 @end ifclear
18559 @ifset vms
18560 @item /NOCURRENT_DIRECTORY
18561 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18562 @end ifset
18563 ^These switches have ^This switch has^ the same meaning as in calls to
18564 @command{gcc}.
18565 ^They define ^It defines ^ the source search path in the call to
18566 @command{gcc} issued
18567 by @command{gnatstub} to compile an argument source file.
18568
18569 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18570 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18571 This switch has the same meaning as in calls to @command{gcc}.
18572 It defines the additional configuration file to be passed to the call to
18573 @command{gcc} issued
18574 by @command{gnatstub} to compile an argument source file.
18575
18576 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18577 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18578 (@var{n} is a non-negative integer). Set the maximum line length in the
18579 body stub to @var{n}; the default is 79. The maximum value that can be
18580 specified is 32767. Note that in the special case of configuration
18581 pragma files, the maximum is always 32767 regardless of whether or
18582 not this switch appears.
18583
18584 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18585 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18586 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18587 the generated body sample to @var{n}.
18588 The default indentation is 3.
18589
18590 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18591 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18592 Order local bodies alphabetically. (By default local bodies are ordered
18593 in the same way as the corresponding local specs in the argument spec file.)
18594
18595 @item ^-i^/INDENTATION=^@var{n}
18596 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18597 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18598
18599 @item ^-k^/TREE_FILE=SAVE^
18600 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18601 Do not remove the tree file (i.e., the snapshot of the compiler internal
18602 structures used by @command{gnatstub}) after creating the body stub.
18603
18604 @item ^-l^/LINE_LENGTH=^@var{n}
18605 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18606 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18607
18608 @item ^-o^/BODY=^@var{body-name}
18609 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18610 Body file name.  This should be set if the argument file name does not
18611 follow
18612 the GNAT file naming
18613 conventions. If this switch is omitted the default name for the body will be
18614 obtained
18615 from the argument file name according to the GNAT file naming conventions.
18616
18617 @item ^-q^/QUIET^
18618 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18619 Quiet mode: do not generate a confirmation when a body is
18620 successfully created, and do not generate a message when a body is not
18621 required for an
18622 argument unit.
18623
18624 @item ^-r^/TREE_FILE=REUSE^
18625 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18626 Reuse the tree file (if it exists) instead of creating it.  Instead of
18627 creating the tree file for the library unit declaration, @command{gnatstub}
18628 tries to find it in the current directory and use it for creating
18629 a body. If the tree file is not found, no body is created. This option
18630 also implies @option{^-k^/SAVE^}, whether or not
18631 the latter is set explicitly.
18632
18633 @item ^-t^/TREE_FILE=OVERWRITE^
18634 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18635 Overwrite the existing tree file.  If the current directory already
18636 contains the file which, according to the GNAT file naming rules should
18637 be considered as a tree file for the argument source file,
18638 @command{gnatstub}
18639 will refuse to create the tree file needed to create a sample body
18640 unless this option is set.
18641
18642 @item ^-v^/VERBOSE^
18643 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18644 Verbose mode: generate version information.
18645
18646 @end table
18647
18648 @node Other Utility Programs
18649 @chapter Other Utility Programs
18650
18651 @noindent
18652 This chapter discusses some other utility programs available in the Ada
18653 environment.
18654
18655 @menu
18656 * Using Other Utility Programs with GNAT::
18657 * The External Symbol Naming Scheme of GNAT::
18658 @ifclear vms
18659 * Ada Mode for Glide::
18660 @end ifclear
18661 * Converting Ada Files to html with gnathtml::
18662 * Installing gnathtml::
18663 @ifset vms
18664 * LSE::
18665 * Profiling::
18666 @end ifset
18667 @end menu
18668
18669 @node Using Other Utility Programs with GNAT
18670 @section Using Other Utility Programs with GNAT
18671
18672 @noindent
18673 The object files generated by GNAT are in standard system format and in
18674 particular the debugging information uses this format. This means
18675 programs generated by GNAT can be used with existing utilities that
18676 depend on these formats.
18677
18678 @ifclear vms
18679 In general, any utility program that works with C will also often work with
18680 Ada programs generated by GNAT. This includes software utilities such as
18681 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18682 as Purify.
18683 @end ifclear
18684
18685 @node The External Symbol Naming Scheme of GNAT
18686 @section The External Symbol Naming Scheme of GNAT
18687
18688 @noindent
18689 In order to interpret the output from GNAT, when using tools that are
18690 originally intended for use with other languages, it is useful to
18691 understand the conventions used to generate link names from the Ada
18692 entity names.
18693
18694 All link names are in all lowercase letters. With the exception of library
18695 procedure names, the mechanism used is simply to use the full expanded
18696 Ada name with dots replaced by double underscores. For example, suppose
18697 we have the following package spec:
18698
18699 @smallexample @c ada
18700 @group
18701 @cartouche
18702 package QRS is
18703    MN : Integer;
18704 end QRS;
18705 @end cartouche
18706 @end group
18707 @end smallexample
18708
18709 @noindent
18710 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18711 the corresponding link name is @code{qrs__mn}.
18712 @findex Export
18713 Of course if a @code{pragma Export} is used this may be overridden:
18714
18715 @smallexample @c ada
18716 @group
18717 @cartouche
18718 package Exports is
18719    Var1 : Integer;
18720    pragma Export (Var1, C, External_Name => "var1_name");
18721    Var2 : Integer;
18722    pragma Export (Var2, C, Link_Name => "var2_link_name");
18723 end Exports;
18724 @end cartouche
18725 @end group
18726 @end smallexample
18727
18728 @noindent
18729 In this case, the link name for @var{Var1} is whatever link name the
18730 C compiler would assign for the C function @var{var1_name}. This typically
18731 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18732 system conventions, but other possibilities exist. The link name for
18733 @var{Var2} is @var{var2_link_name}, and this is not operating system
18734 dependent.
18735
18736 @findex _main
18737 One exception occurs for library level procedures. A potential ambiguity
18738 arises between the required name @code{_main} for the C main program,
18739 and the name we would otherwise assign to an Ada library level procedure
18740 called @code{Main} (which might well not be the main program).
18741
18742 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18743 names. So if we have a library level procedure such as
18744
18745 @smallexample @c ada
18746 @group
18747 @cartouche
18748 procedure Hello (S : String);
18749 @end cartouche
18750 @end group
18751 @end smallexample
18752
18753 @noindent
18754 the external name of this procedure will be @var{_ada_hello}.
18755
18756 @ifclear vms
18757 @node Ada Mode for Glide
18758 @section Ada Mode for @code{Glide}
18759 @cindex Ada mode (for Glide)
18760
18761 @noindent
18762 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18763 user to understand and navigate existing code, and facilitates writing
18764 new code. It furthermore provides some utility functions for easier
18765 integration of standard Emacs features when programming in Ada.
18766
18767 Its general features include:
18768
18769 @itemize @bullet
18770 @item
18771 An Integrated Development Environment with functionality such as the
18772 following
18773
18774 @itemize @bullet
18775 @item
18776 ``Project files'' for configuration-specific aspects
18777 (e.g. directories and compilation options)
18778
18779 @item
18780 Compiling and stepping through error messages.
18781
18782 @item
18783 Running and debugging an applications within Glide.
18784 @end itemize
18785
18786 @item
18787 Pull-down menus
18788
18789 @item
18790 User configurability
18791 @end itemize
18792
18793 Some of the specific Ada mode features are:
18794
18795 @itemize @bullet
18796 @item
18797 Functions for easy and quick stepping through Ada code
18798
18799 @item
18800 Getting cross reference information for identifiers (e.g., finding a
18801 defining occurrence)
18802
18803 @item
18804 Displaying an index menu of types and subprograms, allowing
18805 direct selection for browsing
18806
18807 @item
18808 Automatic color highlighting of the various Ada entities
18809 @end itemize
18810
18811 Glide directly supports writing Ada code, via several facilities:
18812
18813 @itemize @bullet
18814 @item
18815 Switching between spec and body files with possible
18816 autogeneration of body files
18817
18818 @item
18819 Automatic formating of subprogram parameter lists
18820
18821 @item
18822 Automatic indentation according to Ada syntax
18823
18824 @item
18825 Automatic completion of identifiers
18826
18827 @item
18828 Automatic (and configurable) casing of identifiers, keywords, and attributes
18829
18830 @item
18831 Insertion of syntactic templates
18832
18833 @item
18834 Block commenting / uncommenting
18835 @end itemize
18836
18837 @noindent
18838 For more information, please refer to the online documentation
18839 available in the @code{Glide} @result{} @code{Help} menu.
18840 @end ifclear
18841
18842 @node Converting Ada Files to html with gnathtml
18843 @section Converting Ada Files to HTML with @code{gnathtml}
18844
18845 @noindent
18846 This @code{Perl} script allows Ada source files to be browsed using
18847 standard Web browsers. For installation procedure, see the section
18848 @xref{Installing gnathtml}.
18849
18850 Ada reserved keywords are highlighted in a bold font and Ada comments in
18851 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18852 switch to suppress the generation of cross-referencing information, user
18853 defined variables and types will appear in a different color; you will
18854 be able to click on any identifier and go to its declaration.
18855
18856 The command line is as follow:
18857 @smallexample
18858 $ perl gnathtml.pl [switches] ada-files
18859 @end smallexample
18860
18861 @noindent
18862 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18863 an html file for every ada file, and a global file called @file{index.htm}.
18864 This file is an index of every identifier defined in the files.
18865
18866 The available switches are the following ones :
18867
18868 @table @option
18869 @item -83
18870 @cindex @option{-83} (@code{gnathtml})
18871 Only the subset on the Ada 83 keywords will be highlighted, not the full
18872 Ada 95 keywords set.
18873
18874 @item -cc @var{color}
18875 @cindex @option{-cc} (@code{gnathtml})
18876 This option allows you to change the color used for comments. The default
18877 value is green. The color argument can be any name accepted by html.
18878
18879 @item -d
18880 @cindex @option{-d} (@code{gnathtml})
18881 If the ada files depend on some other files (using for instance the
18882 @code{with} command, the latter will also be converted to html.
18883 Only the files in the user project will be converted to html, not the files
18884 in the run-time library itself.
18885
18886 @item -D
18887 @cindex @option{-D} (@code{gnathtml})
18888 This command is the same as @option{-d} above, but @command{gnathtml} will
18889 also look for files in the run-time library, and generate html files for them.
18890
18891 @item -ext @var{extension}
18892 @cindex @option{-ext} (@code{gnathtml})
18893 This option allows you to change the extension of the generated HTML files.
18894 If you do not specify an extension, it will default to @file{htm}.
18895
18896 @item -f
18897 @cindex @option{-f} (@code{gnathtml})
18898 By default, gnathtml will generate html links only for global entities
18899 ('with'ed units, global variables and types,...). If you specify the
18900 @option{-f} on the command line, then links will be generated for local
18901 entities too.
18902
18903 @item -l @var{number}
18904 @cindex @option{-l} (@code{gnathtml})
18905 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18906 will number the html files every @var{number} line.
18907
18908 @item -I @var{dir}
18909 @cindex @option{-I} (@code{gnathtml})
18910 Specify a directory to search for library files (@file{.ALI} files) and
18911 source files. You can provide several -I switches on the command line,
18912 and the directories will be parsed in the order of the command line.
18913
18914 @item -o @var{dir}
18915 @cindex @option{-o} (@code{gnathtml})
18916 Specify the output directory for html files. By default, gnathtml will
18917 saved the generated html files in a subdirectory named @file{html/}.
18918
18919 @item -p @var{file}
18920 @cindex @option{-p} (@code{gnathtml})
18921 If you are using Emacs and the most recent Emacs Ada mode, which provides
18922 a full Integrated Development Environment for compiling, checking,
18923 running and debugging applications, you may use @file{.gpr} files
18924 to give the directories where Emacs can find sources and object files.
18925
18926 Using this switch, you can tell gnathtml to use these files. This allows
18927 you to get an html version of your application, even if it is spread
18928 over multiple directories.
18929
18930 @item -sc @var{color}
18931 @cindex @option{-sc} (@code{gnathtml})
18932 This option allows you to change the color used for symbol definitions.
18933 The default value is red. The color argument can be any name accepted by html.
18934
18935 @item -t @var{file}
18936 @cindex @option{-t} (@code{gnathtml})
18937 This switch provides the name of a file. This file contains a list of
18938 file names to be converted, and the effect is exactly as though they had
18939 appeared explicitly on the command line. This
18940 is the recommended way to work around the command line length limit on some
18941 systems.
18942
18943 @end table
18944
18945 @node Installing gnathtml
18946 @section Installing @code{gnathtml}
18947
18948 @noindent
18949 @code{Perl} needs to be installed on your machine to run this script.
18950 @code{Perl} is freely available for almost every architecture and
18951 Operating System via the Internet.
18952
18953 On Unix systems, you  may want to modify  the  first line of  the script
18954 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18955 is. The syntax of this line is :
18956 @smallexample
18957 #!full_path_name_to_perl
18958 @end smallexample
18959
18960 @noindent
18961 Alternatively, you may run the script using the following command line:
18962
18963 @smallexample
18964 $ perl gnathtml.pl [switches] files
18965 @end smallexample
18966
18967 @ifset vms
18968 @node LSE
18969 @section LSE
18970 @findex LSE
18971
18972 @noindent
18973 The GNAT distribution provides an Ada 95 template for the Digital Language
18974 Sensitive Editor (LSE), a component of DECset. In order to
18975 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18976
18977 @node Profiling
18978 @section Profiling
18979 @findex PCA
18980
18981 @noindent
18982 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18983 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18984 the collection phase with the /DEBUG qualifier.
18985
18986 @smallexample
18987 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18988 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18989 $ RUN/DEBUG <PROGRAM_NAME>
18990 @end smallexample
18991 @noindent
18992 @end ifset
18993
18994 @node Running and Debugging Ada Programs
18995 @chapter Running and Debugging Ada Programs
18996 @cindex Debugging
18997
18998 @noindent
18999 This chapter discusses how to debug Ada programs.
19000 @ifset vms
19001 It applies to the Alpha OpenVMS platform;
19002 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
19003 @end ifset
19004
19005 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19006
19007 @enumerate
19008 @item
19009 The illegality may be a violation of the static semantics of Ada. In
19010 that case GNAT diagnoses the constructs in the program that are illegal.
19011 It is then a straightforward matter for the user to modify those parts of
19012 the program.
19013
19014 @item
19015 The illegality may be a violation of the dynamic semantics of Ada. In
19016 that case the program compiles and executes, but may generate incorrect
19017 results, or may terminate abnormally with some exception.
19018
19019 @item
19020 When presented with a program that contains convoluted errors, GNAT
19021 itself may terminate abnormally without providing full diagnostics on
19022 the incorrect user program.
19023 @end enumerate
19024
19025 @menu
19026 * The GNAT Debugger GDB::
19027 * Running GDB::
19028 * Introduction to GDB Commands::
19029 * Using Ada Expressions::
19030 * Calling User-Defined Subprograms::
19031 * Using the Next Command in a Function::
19032 * Ada Exceptions::
19033 * Ada Tasks::
19034 * Debugging Generic Units::
19035 * GNAT Abnormal Termination or Failure to Terminate::
19036 * Naming Conventions for GNAT Source Files::
19037 * Getting Internal Debugging Information::
19038 * Stack Traceback::
19039 @end menu
19040
19041 @cindex Debugger
19042 @findex gdb
19043
19044 @node The GNAT Debugger GDB
19045 @section The GNAT Debugger GDB
19046
19047 @noindent
19048 @code{GDB} is a general purpose, platform-independent debugger that
19049 can be used to debug mixed-language programs compiled with @command{gcc},
19050 and in particular is capable of debugging Ada programs compiled with
19051 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19052 complex Ada data structures.
19053
19054 The manual @cite{Debugging with GDB}
19055 @ifset vms
19056 , located in the GNU:[DOCS] directory,
19057 @end ifset
19058 contains full details on the usage of @code{GDB}, including a section on
19059 its usage on programs. This manual should be consulted for full
19060 details. The section that follows is a brief introduction to the
19061 philosophy and use of @code{GDB}.
19062
19063 When GNAT programs are compiled, the compiler optionally writes debugging
19064 information into the generated object file, including information on
19065 line numbers, and on declared types and variables. This information is
19066 separate from the generated code. It makes the object files considerably
19067 larger, but it does not add to the size of the actual executable that
19068 will be loaded into memory, and has no impact on run-time performance. The
19069 generation of debug information is triggered by the use of the
19070 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19071 the compilations. It is important to emphasize that the use of these
19072 options does not change the generated code.
19073
19074 The debugging information is written in standard system formats that
19075 are used by many tools, including debuggers and profilers. The format
19076 of the information is typically designed to describe C types and
19077 semantics, but GNAT implements a translation scheme which allows full
19078 details about Ada types and variables to be encoded into these
19079 standard C formats. Details of this encoding scheme may be found in
19080 the file exp_dbug.ads in the GNAT source distribution. However, the
19081 details of this encoding are, in general, of no interest to a user,
19082 since @code{GDB} automatically performs the necessary decoding.
19083
19084 When a program is bound and linked, the debugging information is
19085 collected from the object files, and stored in the executable image of
19086 the program. Again, this process significantly increases the size of
19087 the generated executable file, but it does not increase the size of
19088 the executable program itself. Furthermore, if this program is run in
19089 the normal manner, it runs exactly as if the debug information were
19090 not present, and takes no more actual memory.
19091
19092 However, if the program is run under control of @code{GDB}, the
19093 debugger is activated.  The image of the program is loaded, at which
19094 point it is ready to run.  If a run command is given, then the program
19095 will run exactly as it would have if @code{GDB} were not present. This
19096 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19097 entirely non-intrusive until a breakpoint is encountered.  If no
19098 breakpoint is ever hit, the program will run exactly as it would if no
19099 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19100 the debugging information and can respond to user commands to inspect
19101 variables, and more generally to report on the state of execution.
19102
19103 @c **************
19104 @node Running GDB
19105 @section Running GDB
19106
19107 @noindent
19108 The debugger can be launched directly and simply from @code{glide} or
19109 through its graphical interface: @code{gvd}. It can also be used
19110 directly in text mode. Here is described the basic use of @code{GDB}
19111 in text mode. All the commands described below can be used in the
19112 @code{gvd} console window even though there is usually other more
19113 graphical ways to achieve the same goals.
19114
19115 @ifclear vms
19116 @noindent
19117 The command to run the graphical interface of the debugger is
19118 @smallexample
19119 $ gvd program
19120 @end smallexample
19121 @end ifclear
19122
19123 @noindent
19124 The command to run @code{GDB} in text mode is
19125
19126 @smallexample
19127 $ ^gdb program^$ GDB PROGRAM^
19128 @end smallexample
19129
19130 @noindent
19131 where @code{^program^PROGRAM^} is the name of the executable file. This
19132 activates the debugger and results in a prompt for debugger commands.
19133 The simplest command is simply @code{run}, which causes the program to run
19134 exactly as if the debugger were not present. The following section
19135 describes some of the additional commands that can be given to @code{GDB}.
19136
19137 @c *******************************
19138 @node Introduction to GDB Commands
19139 @section Introduction to GDB Commands
19140
19141 @noindent
19142 @code{GDB} contains a large repertoire of commands. The manual
19143 @cite{Debugging with GDB}
19144 @ifset vms
19145 , located in the GNU:[DOCS] directory,
19146 @end ifset
19147 includes extensive documentation on the use
19148 of these commands, together with examples of their use. Furthermore,
19149 the command @var{help} invoked from within @code{GDB} activates a simple help
19150 facility which summarizes the available commands and their options.
19151 In this section we summarize a few of the most commonly
19152 used commands to give an idea of what @code{GDB} is about. You should create
19153 a simple program with debugging information and experiment with the use of
19154 these @code{GDB} commands on the program as you read through the
19155 following section.
19156
19157 @table @code
19158 @item set args @var{arguments}
19159 The @var{arguments} list above is a list of arguments to be passed to
19160 the program on a subsequent run command, just as though the arguments
19161 had been entered on a normal invocation of the program. The @code{set args}
19162 command is not needed if the program does not require arguments.
19163
19164 @item run
19165 The @code{run} command causes execution of the program to start from
19166 the beginning. If the program is already running, that is to say if
19167 you are currently positioned at a breakpoint, then a prompt will ask
19168 for confirmation that you want to abandon the current execution and
19169 restart.
19170
19171 @item breakpoint @var{location}
19172 The breakpoint command sets a breakpoint, that is to say a point at which
19173 execution will halt and @code{GDB} will await further
19174 commands. @var{location} is
19175 either a line number within a file, given in the format @code{file:linenumber},
19176 or it is the name of a subprogram. If you request that a breakpoint be set on
19177 a subprogram that is overloaded, a prompt will ask you to specify on which of
19178 those subprograms you want to breakpoint. You can also
19179 specify that all of them should be breakpointed. If the program is run
19180 and execution encounters the breakpoint, then the program
19181 stops and @code{GDB} signals that the breakpoint was encountered by
19182 printing the line of code before which the program is halted.
19183
19184 @item breakpoint exception @var{name}
19185 A special form of the breakpoint command which breakpoints whenever
19186 exception @var{name} is raised.
19187 If @var{name} is omitted,
19188 then a breakpoint will occur when any exception is raised.
19189
19190 @item print @var{expression}
19191 This will print the value of the given expression. Most simple
19192 Ada expression formats are properly handled by @code{GDB}, so the expression
19193 can contain function calls, variables, operators, and attribute references.
19194
19195 @item continue
19196 Continues execution following a breakpoint, until the next breakpoint or the
19197 termination of the program.
19198
19199 @item step
19200 Executes a single line after a breakpoint. If the next statement
19201 is a subprogram call, execution continues into (the first statement of)
19202 the called subprogram.
19203
19204 @item next
19205 Executes a single line. If this line is a subprogram call, executes and
19206 returns from the call.
19207
19208 @item list
19209 Lists a few lines around the current source location. In practice, it
19210 is usually more convenient to have a separate edit window open with the
19211 relevant source file displayed. Successive applications of this command
19212 print subsequent lines. The command can be given an argument which is a
19213 line number, in which case it displays a few lines around the specified one.
19214
19215 @item backtrace
19216 Displays a backtrace of the call chain. This command is typically
19217 used after a breakpoint has occurred, to examine the sequence of calls that
19218 leads to the current breakpoint. The display includes one line for each
19219 activation record (frame) corresponding to an active subprogram.
19220
19221 @item up
19222 At a breakpoint, @code{GDB} can display the values of variables local
19223 to the current frame. The command @code{up} can be used to
19224 examine the contents of other active frames, by moving the focus up
19225 the stack, that is to say from callee to caller, one frame at a time.
19226
19227 @item down
19228 Moves the focus of @code{GDB} down from the frame currently being
19229 examined to the frame of its callee (the reverse of the previous command),
19230
19231 @item frame @var{n}
19232 Inspect the frame with the given number. The value 0 denotes the frame
19233 of the current breakpoint, that is to say the top of the call stack.
19234
19235 @end table
19236
19237 The above list is a very short introduction to the commands that
19238 @code{GDB} provides. Important additional capabilities, including conditional
19239 breakpoints, the ability to execute command sequences on a breakpoint,
19240 the ability to debug at the machine instruction level and many other
19241 features are described in detail in @cite{Debugging with GDB}.
19242 Note that most commands can be abbreviated
19243 (for example, c for continue, bt for backtrace).
19244
19245 @node Using Ada Expressions
19246 @section Using Ada Expressions
19247 @cindex Ada expressions
19248
19249 @noindent
19250 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19251 extensions. The philosophy behind the design of this subset is
19252
19253 @itemize @bullet
19254 @item
19255 That @code{GDB} should provide basic literals and access to operations for
19256 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19257 leaving more sophisticated computations to subprograms written into the
19258 program (which therefore may be called from @code{GDB}).
19259
19260 @item
19261 That type safety and strict adherence to Ada language restrictions
19262 are not particularly important to the @code{GDB} user.
19263
19264 @item
19265 That brevity is important to the @code{GDB} user.
19266 @end itemize
19267
19268 Thus, for brevity, the debugger acts as if there were
19269 implicit @code{with} and @code{use} clauses in effect for all user-written
19270 packages, thus making it unnecessary to fully qualify most names with
19271 their packages, regardless of context. Where this causes ambiguity,
19272 @code{GDB} asks the user's intent.
19273
19274 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19275
19276 @node Calling User-Defined Subprograms
19277 @section Calling User-Defined Subprograms
19278
19279 @noindent
19280 An important capability of @code{GDB} is the ability to call user-defined
19281 subprograms while debugging. This is achieved simply by entering
19282 a subprogram call statement in the form:
19283
19284 @smallexample
19285 call subprogram-name (parameters)
19286 @end smallexample
19287
19288 @noindent
19289 The keyword @code{call} can be omitted in the normal case where the
19290 @code{subprogram-name} does not coincide with any of the predefined
19291 @code{GDB} commands.
19292
19293 The effect is to invoke the given subprogram, passing it the
19294 list of parameters that is supplied. The parameters can be expressions and
19295 can include variables from the program being debugged. The
19296 subprogram must be defined
19297 at the library level within your program, and @code{GDB} will call the
19298 subprogram within the environment of your program execution (which
19299 means that the subprogram is free to access or even modify variables
19300 within your program).
19301
19302 The most important use of this facility is in allowing the inclusion of
19303 debugging routines that are tailored to particular data structures
19304 in your program. Such debugging routines can be written to provide a suitably
19305 high-level description of an abstract type, rather than a low-level dump
19306 of its physical layout. After all, the standard
19307 @code{GDB print} command only knows the physical layout of your
19308 types, not their abstract meaning. Debugging routines can provide information
19309 at the desired semantic level and are thus enormously useful.
19310
19311 For example, when debugging GNAT itself, it is crucial to have access to
19312 the contents of the tree nodes used to represent the program internally.
19313 But tree nodes are represented simply by an integer value (which in turn
19314 is an index into a table of nodes).
19315 Using the @code{print} command on a tree node would simply print this integer
19316 value, which is not very useful. But the PN routine (defined in file
19317 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19318 a useful high level representation of the tree node, which includes the
19319 syntactic category of the node, its position in the source, the integers
19320 that denote descendant nodes and parent node, as well as varied
19321 semantic information. To study this example in more detail, you might want to
19322 look at the body of the PN procedure in the stated file.
19323
19324 @node Using the Next Command in a Function
19325 @section Using the Next Command in a Function
19326
19327 @noindent
19328 When you use the @code{next} command in a function, the current source
19329 location will advance to the next statement as usual. A special case
19330 arises in the case of a @code{return} statement.
19331
19332 Part of the code for a return statement is the ``epilog'' of the function.
19333 This is the code that returns to the caller. There is only one copy of
19334 this epilog code, and it is typically associated with the last return
19335 statement in the function if there is more than one return. In some
19336 implementations, this epilog is associated with the first statement
19337 of the function.
19338
19339 The result is that if you use the @code{next} command from a return
19340 statement that is not the last return statement of the function you
19341 may see a strange apparent jump to the last return statement or to
19342 the start of the function. You should simply ignore this odd jump.
19343 The value returned is always that from the first return statement
19344 that was stepped through.
19345
19346 @node Ada Exceptions
19347 @section Breaking on Ada Exceptions
19348 @cindex Exceptions
19349
19350 @noindent
19351 You can set breakpoints that trip when your program raises
19352 selected exceptions.
19353
19354 @table @code
19355 @item break exception
19356 Set a breakpoint that trips whenever (any task in the) program raises
19357 any exception.
19358
19359 @item break exception @var{name}
19360 Set a breakpoint that trips whenever (any task in the) program raises
19361 the exception @var{name}.
19362
19363 @item break exception unhandled
19364 Set a breakpoint that trips whenever (any task in the) program raises an
19365 exception for which there is no handler.
19366
19367 @item info exceptions
19368 @itemx info exceptions @var{regexp}
19369 The @code{info exceptions} command permits the user to examine all defined
19370 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19371 argument, prints out only those exceptions whose name matches @var{regexp}.
19372 @end table
19373
19374 @node Ada Tasks
19375 @section Ada Tasks
19376 @cindex Tasks
19377
19378 @noindent
19379 @code{GDB} allows the following task-related commands:
19380
19381 @table @code
19382 @item info tasks
19383 This command shows a list of current Ada tasks, as in the following example:
19384
19385 @smallexample
19386 @iftex
19387 @leftskip=0cm
19388 @end iftex
19389 (gdb) info tasks
19390   ID       TID P-ID   Thread Pri State                 Name
19391    1   8088000   0   807e000  15 Child Activation Wait main_task
19392    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19393    3   809a800   1   80a4800  15 Child Activation Wait a
19394 *  4   80ae800   3   80b8000  15 Running               c
19395 @end smallexample
19396
19397 @noindent
19398 In this listing, the asterisk before the first task indicates it to be the
19399 currently running task. The first column lists the task ID that is used
19400 to refer to tasks in the following commands.
19401
19402 @item break @var{linespec} task @var{taskid}
19403 @itemx break @var{linespec} task @var{taskid} if @dots{}
19404 @cindex Breakpoints and tasks
19405 These commands are like the @code{break @dots{} thread @dots{}}.
19406 @var{linespec} specifies source lines.
19407
19408 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19409 to specify that you only want @code{GDB} to stop the program when a
19410 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19411 numeric task identifiers assigned by @code{GDB}, shown in the first
19412 column of the @samp{info tasks} display.
19413
19414 If you do not specify @samp{task @var{taskid}} when you set a
19415 breakpoint, the breakpoint applies to @emph{all} tasks of your
19416 program.
19417
19418 You can use the @code{task} qualifier on conditional breakpoints as
19419 well; in this case, place @samp{task @var{taskid}} before the
19420 breakpoint condition (before the @code{if}).
19421
19422 @item task @var{taskno}
19423 @cindex Task switching
19424
19425 This command allows to switch to the task referred by @var{taskno}. In
19426 particular, This allows to browse the backtrace of the specified
19427 task. It is advised to switch back to the original task before
19428 continuing execution otherwise the scheduling of the program may be
19429 perturbated.
19430 @end table
19431
19432 @noindent
19433 For more detailed information on the tasking support,
19434 see @cite{Debugging with GDB}.
19435
19436 @node Debugging Generic Units
19437 @section Debugging Generic Units
19438 @cindex Debugging Generic Units
19439 @cindex Generics
19440
19441 @noindent
19442 GNAT always uses code expansion for generic instantiation. This means that
19443 each time an instantiation occurs, a complete copy of the original code is
19444 made, with appropriate substitutions of formals by actuals.
19445
19446 It is not possible to refer to the original generic entities in
19447 @code{GDB}, but it is always possible to debug a particular instance of
19448 a generic, by using the appropriate expanded names. For example, if we have
19449
19450 @smallexample @c ada
19451 @group
19452 @cartouche
19453 procedure g is
19454
19455    generic package k is
19456       procedure kp (v1 : in out integer);
19457    end k;
19458
19459    package body k is
19460       procedure kp (v1 : in out integer) is
19461       begin
19462          v1 := v1 + 1;
19463       end kp;
19464    end k;
19465
19466    package k1 is new k;
19467    package k2 is new k;
19468
19469    var : integer := 1;
19470
19471 begin
19472    k1.kp (var);
19473    k2.kp (var);
19474    k1.kp (var);
19475    k2.kp (var);
19476 end;
19477 @end cartouche
19478 @end group
19479 @end smallexample
19480
19481 @noindent
19482 Then to break on a call to procedure kp in the k2 instance, simply
19483 use the command:
19484
19485 @smallexample
19486 (gdb) break g.k2.kp
19487 @end smallexample
19488
19489 @noindent
19490 When the breakpoint occurs, you can step through the code of the
19491 instance in the normal manner and examine the values of local variables, as for
19492 other units.
19493
19494 @node GNAT Abnormal Termination or Failure to Terminate
19495 @section GNAT Abnormal Termination or Failure to Terminate
19496 @cindex GNAT Abnormal Termination or Failure to Terminate
19497
19498 @noindent
19499 When presented with programs that contain serious errors in syntax
19500 or semantics,
19501 GNAT may on rare occasions  experience problems in operation, such
19502 as aborting with a
19503 segmentation fault or illegal memory access, raising an internal
19504 exception, terminating abnormally, or failing to terminate at all.
19505 In such cases, you can activate
19506 various features of GNAT that can help you pinpoint the construct in your
19507 program that is the likely source of the problem.
19508
19509 The following strategies are presented in increasing order of
19510 difficulty, corresponding to your experience in using GNAT and your
19511 familiarity with compiler internals.
19512
19513 @enumerate
19514 @item
19515 Run @command{gcc} with the @option{-gnatf}. This first
19516 switch causes all errors on a given line to be reported. In its absence,
19517 only the first error on a line is displayed.
19518
19519 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19520 are encountered, rather than after compilation is terminated. If GNAT
19521 terminates prematurely or goes into an infinite loop, the last error
19522 message displayed may help to pinpoint the culprit.
19523
19524 @item
19525 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19526 mode, @command{gcc} produces ongoing information about the progress of the
19527 compilation and provides the name of each procedure as code is
19528 generated. This switch allows you to find which Ada procedure was being
19529 compiled when it encountered a code generation problem.
19530
19531 @item
19532 @cindex @option{-gnatdc} switch
19533 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19534 switch that does for the front-end what @option{^-v^VERBOSE^} does
19535 for the back end. The system prints the name of each unit,
19536 either a compilation unit or nested unit, as it is being analyzed.
19537 @item
19538 Finally, you can start
19539 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19540 front-end of GNAT, and can be run independently (normally it is just
19541 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19542 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19543 @code{where} command is the first line of attack; the variable
19544 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19545 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19546 which the execution stopped, and @code{input_file name} indicates the name of
19547 the source file.
19548 @end enumerate
19549
19550 @node Naming Conventions for GNAT Source Files
19551 @section Naming Conventions for GNAT Source Files
19552
19553 @noindent
19554 In order to examine the workings of the GNAT system, the following
19555 brief description of its organization may be helpful:
19556
19557 @itemize @bullet
19558 @item
19559 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19560
19561 @item
19562 All files prefixed with @file{^par^PAR^} are components of the parser. The
19563 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19564 parsing of select statements can be found in @file{par-ch9.adb}.
19565
19566 @item
19567 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19568 numbers correspond to chapters of the Ada standard. For example, all
19569 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19570 addition, some features of the language require sufficient special processing
19571 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19572 dynamic dispatching, etc.
19573
19574 @item
19575 All files prefixed with @file{^exp^EXP^} perform normalization and
19576 expansion of the intermediate representation (abstract syntax tree, or AST).
19577 these files use the same numbering scheme as the parser and semantics files.
19578 For example, the construction of record initialization procedures is done in
19579 @file{exp_ch3.adb}.
19580
19581 @item
19582 The files prefixed with @file{^bind^BIND^} implement the binder, which
19583 verifies the consistency of the compilation, determines an order of
19584 elaboration, and generates the bind file.
19585
19586 @item
19587 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19588 data structures used by the front-end.
19589
19590 @item
19591 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19592 the abstract syntax tree as produced by the parser.
19593
19594 @item
19595 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19596 all entities, computed during semantic analysis.
19597
19598 @item
19599 Library management issues are dealt with in files with prefix
19600 @file{^lib^LIB^}.
19601
19602 @item
19603 @findex Ada
19604 @cindex Annex A
19605 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19606 defined in Annex A.
19607
19608 @item
19609 @findex Interfaces
19610 @cindex Annex B
19611 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19612 defined in Annex B.
19613
19614 @item
19615 @findex System
19616 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19617 both language-defined children and GNAT run-time routines.
19618
19619 @item
19620 @findex GNAT
19621 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19622 general-purpose packages, fully documented in their specifications. All
19623 the other @file{.c} files are modifications of common @command{gcc} files.
19624 @end itemize
19625
19626 @node Getting Internal Debugging Information
19627 @section Getting Internal Debugging Information
19628
19629 @noindent
19630 Most compilers have internal debugging switches and modes. GNAT
19631 does also, except GNAT internal debugging switches and modes are not
19632 secret. A summary and full description of all the compiler and binder
19633 debug flags are in the file @file{debug.adb}. You must obtain the
19634 sources of the compiler to see the full detailed effects of these flags.
19635
19636 The switches that print the source of the program (reconstructed from
19637 the internal tree) are of general interest for user programs, as are the
19638 options to print
19639 the full internal tree, and the entity table (the symbol table
19640 information). The reconstructed source provides a readable version of the
19641 program after the front-end has completed analysis and  expansion,
19642 and is useful when studying the performance of specific constructs.
19643 For example, constraint checks are indicated, complex aggregates
19644 are replaced with loops and assignments, and tasking primitives
19645 are replaced with run-time calls.
19646
19647 @node Stack Traceback
19648 @section Stack Traceback
19649 @cindex traceback
19650 @cindex stack traceback
19651 @cindex stack unwinding
19652
19653 @noindent
19654 Traceback is a mechanism to display the sequence of subprogram calls that
19655 leads to a specified execution point in a program. Often (but not always)
19656 the execution point is an instruction at which an exception has been raised.
19657 This mechanism is also known as @i{stack unwinding} because it obtains
19658 its information by scanning the run-time stack and recovering the activation
19659 records of all active subprograms. Stack unwinding is one of the most
19660 important tools for program debugging.
19661
19662 The first entry stored in traceback corresponds to the deepest calling level,
19663 that is to say the subprogram currently executing the instruction
19664 from which we want to obtain the traceback.
19665
19666 Note that there is no runtime performance penalty when stack traceback
19667 is enabled, and no exception is raised during program execution.
19668
19669 @menu
19670 * Non-Symbolic Traceback::
19671 * Symbolic Traceback::
19672 @end menu
19673
19674 @node Non-Symbolic Traceback
19675 @subsection Non-Symbolic Traceback
19676 @cindex traceback, non-symbolic
19677
19678 @noindent
19679 Note: this feature is not supported on all platforms. See
19680 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19681 platforms.
19682
19683 @menu
19684 * Tracebacks From an Unhandled Exception::
19685 * Tracebacks From Exception Occurrences (non-symbolic)::
19686 * Tracebacks From Anywhere in a Program (non-symbolic)::
19687 @end menu
19688
19689 @node Tracebacks From an Unhandled Exception
19690 @subsubsection Tracebacks From an Unhandled Exception
19691
19692 @noindent
19693 A runtime non-symbolic traceback is a list of addresses of call instructions.
19694 To enable this feature you must use the @option{-E}
19695 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19696 of exception information. You can retrieve this information using the
19697 @code{addr2line} tool.
19698
19699 Here is a simple example:
19700
19701 @smallexample @c ada
19702 @cartouche
19703 procedure STB is
19704
19705    procedure P1 is
19706    begin
19707       raise Constraint_Error;
19708    end P1;
19709
19710    procedure P2 is
19711    begin
19712       P1;
19713    end P2;
19714
19715 begin
19716    P2;
19717 end STB;
19718 @end cartouche
19719 @end smallexample
19720
19721 @smallexample
19722 $ gnatmake stb -bargs -E
19723 $ stb
19724
19725 Execution terminated by unhandled exception
19726 Exception name: CONSTRAINT_ERROR
19727 Message: stb.adb:5
19728 Call stack traceback locations:
19729 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19730 @end smallexample
19731
19732 @noindent
19733 As we see the traceback lists a sequence of addresses for the unhandled
19734 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19735 guess that this exception come from procedure P1. To translate these
19736 addresses into the source lines where the calls appear, the
19737 @code{addr2line} tool, described below, is invaluable. The use of this tool
19738 requires the program to be compiled with debug information.
19739
19740 @smallexample
19741 $ gnatmake -g stb -bargs -E
19742 $ stb
19743
19744 Execution terminated by unhandled exception
19745 Exception name: CONSTRAINT_ERROR
19746 Message: stb.adb:5
19747 Call stack traceback locations:
19748 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19749
19750 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19751    0x4011f1 0x77e892a4
19752
19753 00401373 at d:/stb/stb.adb:5
19754 0040138B at d:/stb/stb.adb:10
19755 0040139C at d:/stb/stb.adb:14
19756 00401335 at d:/stb/b~stb.adb:104
19757 004011C4 at /build/.../crt1.c:200
19758 004011F1 at /build/.../crt1.c:222
19759 77E892A4 in ?? at ??:0
19760 @end smallexample
19761
19762 @noindent
19763 The @code{addr2line} tool has several other useful options:
19764
19765 @table @code
19766 @item --functions
19767 to get the function name corresponding to any location
19768
19769 @item --demangle=gnat
19770 to use the gnat decoding mode for the function names. Note that
19771 for binutils version 2.9.x the option is simply @option{--demangle}.
19772 @end table
19773
19774 @smallexample
19775 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19776    0x40139c 0x401335 0x4011c4 0x4011f1
19777
19778 00401373 in stb.p1 at d:/stb/stb.adb:5
19779 0040138B in stb.p2 at d:/stb/stb.adb:10
19780 0040139C in stb at d:/stb/stb.adb:14
19781 00401335 in main at d:/stb/b~stb.adb:104
19782 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19783 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19784 @end smallexample
19785
19786 @noindent
19787 From this traceback we can see that the exception was raised in
19788 @file{stb.adb} at line 5, which was reached from a procedure call in
19789 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19790 which contains the call to the main program.
19791 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19792 and the output will vary from platform to platform.
19793
19794 It is also possible to use @code{GDB} with these traceback addresses to debug
19795 the program. For example, we can break at a given code location, as reported
19796 in the stack traceback:
19797
19798 @smallexample
19799 $ gdb -nw stb
19800 @ifclear vms
19801 @noindent
19802 Furthermore, this feature is not implemented inside Windows DLL. Only
19803 the non-symbolic traceback is reported in this case.
19804 @end ifclear
19805
19806 (gdb) break *0x401373
19807 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19808 @end smallexample
19809
19810 @noindent
19811 It is important to note that the stack traceback addresses
19812 do not change when debug information is included. This is particularly useful
19813 because it makes it possible to release software without debug information (to
19814 minimize object size), get a field report that includes a stack traceback
19815 whenever an internal bug occurs, and then be able to retrieve the sequence
19816 of calls with the same program compiled with debug information.
19817
19818 @node Tracebacks From Exception Occurrences (non-symbolic)
19819 @subsubsection Tracebacks From Exception Occurrences
19820
19821 @noindent
19822 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19823 The stack traceback is attached to the exception information string, and can
19824 be retrieved in an exception handler within the Ada program, by means of the
19825 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19826
19827 @smallexample @c ada
19828 with Ada.Text_IO;
19829 with Ada.Exceptions;
19830
19831 procedure STB is
19832
19833    use Ada;
19834    use Ada.Exceptions;
19835
19836    procedure P1 is
19837       K : Positive := 1;
19838    begin
19839       K := K - 1;
19840    exception
19841       when E : others =>
19842          Text_IO.Put_Line (Exception_Information (E));
19843    end P1;
19844
19845    procedure P2 is
19846    begin
19847       P1;
19848    end P2;
19849
19850 begin
19851    P2;
19852 end STB;
19853 @end smallexample
19854
19855 @noindent
19856 This program will output:
19857
19858 @smallexample
19859 $ stb
19860
19861 Exception name: CONSTRAINT_ERROR
19862 Message: stb.adb:12
19863 Call stack traceback locations:
19864 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19865 @end smallexample
19866
19867 @node Tracebacks From Anywhere in a Program (non-symbolic)
19868 @subsubsection Tracebacks From Anywhere in a Program
19869
19870 @noindent
19871 It is also possible to retrieve a stack traceback from anywhere in a
19872 program. For this you need to
19873 use the @code{GNAT.Traceback} API. This package includes a procedure called
19874 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19875 display procedures described below. It is not necessary to use the
19876 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19877 is invoked explicitly.
19878
19879 @noindent
19880 In the following example we compute a traceback at a specific location in
19881 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19882 convert addresses to strings:
19883
19884 @smallexample @c ada
19885 with Ada.Text_IO;
19886 with GNAT.Traceback;
19887 with GNAT.Debug_Utilities;
19888
19889 procedure STB is
19890
19891    use Ada;
19892    use GNAT;
19893    use GNAT.Traceback;
19894
19895    procedure P1 is
19896       TB  : Tracebacks_Array (1 .. 10);
19897       --  We are asking for a maximum of 10 stack frames.
19898       Len : Natural;
19899       --  Len will receive the actual number of stack frames returned.
19900    begin
19901       Call_Chain (TB, Len);
19902
19903       Text_IO.Put ("In STB.P1 : ");
19904
19905       for K in 1 .. Len loop
19906          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19907          Text_IO.Put (' ');
19908       end loop;
19909
19910       Text_IO.New_Line;
19911    end P1;
19912
19913    procedure P2 is
19914    begin
19915       P1;
19916    end P2;
19917
19918 begin
19919    P2;
19920 end STB;
19921 @end smallexample
19922
19923 @smallexample
19924 $ gnatmake -g stb
19925 $ stb
19926
19927 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19928 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19929 @end smallexample
19930
19931 @noindent
19932 You can then get further information by invoking the @code{addr2line}
19933 tool as described earlier (note that the hexadecimal addresses
19934 need to be specified in C format, with a leading ``0x'').
19935
19936 @node Symbolic Traceback
19937 @subsection Symbolic Traceback
19938 @cindex traceback, symbolic
19939
19940 @noindent
19941 A symbolic traceback is a stack traceback in which procedure names are
19942 associated with each code location.
19943
19944 @noindent
19945 Note that this feature is not supported on all platforms. See
19946 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19947 list of currently supported platforms.
19948
19949 @noindent
19950 Note that the symbolic traceback requires that the program be compiled
19951 with debug information. If it is not compiled with debug information
19952 only the non-symbolic information will be valid.
19953
19954 @menu
19955 * Tracebacks From Exception Occurrences (symbolic)::
19956 * Tracebacks From Anywhere in a Program (symbolic)::
19957 @end menu
19958
19959 @node Tracebacks From Exception Occurrences (symbolic)
19960 @subsubsection Tracebacks From Exception Occurrences
19961
19962 @smallexample @c ada
19963 with Ada.Text_IO;
19964 with GNAT.Traceback.Symbolic;
19965
19966 procedure STB is
19967
19968    procedure P1 is
19969    begin
19970       raise Constraint_Error;
19971    end P1;
19972
19973    procedure P2 is
19974    begin
19975       P1;
19976    end P2;
19977
19978    procedure P3 is
19979    begin
19980       P2;
19981    end P3;
19982
19983 begin
19984    P3;
19985 exception
19986    when E : others =>
19987       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19988 end STB;
19989 @end smallexample
19990
19991 @smallexample
19992 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19993 $ stb
19994
19995 0040149F in stb.p1 at stb.adb:8
19996 004014B7 in stb.p2 at stb.adb:13
19997 004014CF in stb.p3 at stb.adb:18
19998 004015DD in ada.stb at stb.adb:22
19999 00401461 in main at b~stb.adb:168
20000 004011C4 in __mingw_CRTStartup at crt1.c:200
20001 004011F1 in mainCRTStartup at crt1.c:222
20002 77E892A4 in ?? at ??:0
20003 @end smallexample
20004
20005 @noindent
20006 In the above example the ``.\'' syntax in the @command{gnatmake} command
20007 is currently required by @command{addr2line} for files that are in
20008 the current working directory.
20009 Moreover, the exact sequence of linker options may vary from platform
20010 to platform.
20011 The above @option{-largs} section is for Windows platforms. By contrast,
20012 under Unix there is no need for the @option{-largs} section.
20013 Differences across platforms are due to details of linker implementation.
20014
20015 @node Tracebacks From Anywhere in a Program (symbolic)
20016 @subsubsection Tracebacks From Anywhere in a Program
20017
20018 @noindent
20019 It is possible to get a symbolic stack traceback
20020 from anywhere in a program, just as for non-symbolic tracebacks.
20021 The first step is to obtain a non-symbolic
20022 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20023 information. Here is an example:
20024
20025 @smallexample @c ada
20026 with Ada.Text_IO;
20027 with GNAT.Traceback;
20028 with GNAT.Traceback.Symbolic;
20029
20030 procedure STB is
20031
20032    use Ada;
20033    use GNAT.Traceback;
20034    use GNAT.Traceback.Symbolic;
20035
20036    procedure P1 is
20037       TB  : Tracebacks_Array (1 .. 10);
20038       --  We are asking for a maximum of 10 stack frames.
20039       Len : Natural;
20040       --  Len will receive the actual number of stack frames returned.
20041    begin
20042       Call_Chain (TB, Len);
20043       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20044    end P1;
20045
20046    procedure P2 is
20047    begin
20048       P1;
20049    end P2;
20050
20051 begin
20052    P2;
20053 end STB;
20054 @end smallexample
20055
20056 @ifset vms
20057 @node Compatibility with DEC Ada
20058 @chapter Compatibility with DEC Ada
20059 @cindex Compatibility
20060
20061 @noindent
20062 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
20063 OpenVMS Alpha. GNAT achieves a high level of compatibility
20064 with DEC Ada, and it should generally be straightforward to port code
20065 from the DEC Ada environment to GNAT. However, there are a few language
20066 and implementation differences of which the user must be aware. These
20067 differences are discussed in this section. In
20068 addition, the operating environment and command structure for the
20069 compiler are different, and these differences are also discussed.
20070
20071 Note that this discussion addresses specifically the implementation
20072 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
20073 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20074 GNAT always follows the Alpha implementation.
20075
20076 @menu
20077 * Ada 95 Compatibility::
20078 * Differences in the Definition of Package System::
20079 * Language-Related Features::
20080 * The Package STANDARD::
20081 * The Package SYSTEM::
20082 * Tasking and Task-Related Features::
20083 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
20084 * Pragmas and Pragma-Related Features::
20085 * Library of Predefined Units::
20086 * Bindings::
20087 * Main Program Definition::
20088 * Implementation-Defined Attributes::
20089 * Compiler and Run-Time Interfacing::
20090 * Program Compilation and Library Management::
20091 * Input-Output::
20092 * Implementation Limits::
20093 * Tools::
20094 @end menu
20095
20096 @node Ada 95 Compatibility
20097 @section Ada 95 Compatibility
20098
20099 @noindent
20100 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
20101 compiler. Ada 95 is almost completely upwards compatible
20102 with Ada 83, and therefore Ada 83 programs will compile
20103 and run under GNAT with
20104 no changes or only minor changes. The Ada 95 Reference
20105 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
20106 incompatibilities.
20107
20108 GNAT provides the switch /83 on the GNAT COMPILE command,
20109 as well as the pragma ADA_83, to force the compiler to
20110 operate in Ada 83 mode. This mode does not guarantee complete
20111 conformance to Ada 83, but in practice is sufficient to
20112 eliminate most sources of incompatibilities.
20113 In particular, it eliminates the recognition of the
20114 additional Ada 95 keywords, so that their use as identifiers
20115 in Ada83 program is legal, and handles the cases of packages
20116 with optional bodies, and generics that instantiate unconstrained
20117 types without the use of @code{(<>)}.
20118
20119 @node Differences in the Definition of Package System
20120 @section Differences in the Definition of Package System
20121
20122 @noindent
20123 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20124 implementation-dependent declarations to package System. In normal mode,
20125 GNAT does not take advantage of this permission, and the version of System
20126 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20127
20128 However, DEC Ada adds an extensive set of declarations to package System,
20129 as fully documented in the DEC Ada manuals. To minimize changes required
20130 for programs that make use of these extensions, GNAT provides the pragma
20131 Extend_System for extending the definition of package System. By using:
20132
20133 @smallexample @c ada
20134 @group
20135 @cartouche
20136 pragma Extend_System (Aux_DEC);
20137 @end cartouche
20138 @end group
20139 @end smallexample
20140
20141 @noindent
20142 The set of definitions in System is extended to include those in package
20143 @code{System.Aux_DEC}.
20144 These definitions are incorporated directly into package
20145 System, as though they had been declared there in the first place. For a
20146 list of the declarations added, see the specification of this package,
20147 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20148 The pragma Extend_System is a configuration pragma, which means that
20149 it can be placed in the file @file{gnat.adc}, so that it will automatically
20150 apply to all subsequent compilations. See the section on Configuration
20151 Pragmas for further details.
20152
20153 An alternative approach that avoids the use of the non-standard
20154 Extend_System pragma is to add a context clause to the unit that
20155 references these facilities:
20156
20157 @smallexample @c ada
20158 @group
20159 @cartouche
20160 with System.Aux_DEC;
20161 use  System.Aux_DEC;
20162 @end cartouche
20163 @end group
20164 @end smallexample
20165
20166 @noindent
20167 The effect is not quite semantically identical to incorporating
20168 the declarations directly into package @code{System},
20169 but most programs will not notice a difference
20170 unless they use prefix notation (e.g. @code{System.Integer_8})
20171 to reference the
20172 entities directly in package @code{System}.
20173 For units containing such references,
20174 the prefixes must either be removed, or the pragma @code{Extend_System}
20175 must be used.
20176
20177 @node Language-Related Features
20178 @section Language-Related Features
20179
20180 @noindent
20181 The following sections highlight differences in types,
20182 representations of types, operations, alignment, and
20183 related topics.
20184
20185 @menu
20186 * Integer Types and Representations::
20187 * Floating-Point Types and Representations::
20188 * Pragmas Float_Representation and Long_Float::
20189 * Fixed-Point Types and Representations::
20190 * Record and Array Component Alignment::
20191 * Address Clauses::
20192 * Other Representation Clauses::
20193 @end menu
20194
20195 @node Integer Types and Representations
20196 @subsection Integer Types and Representations
20197
20198 @noindent
20199 The set of predefined integer types is identical in DEC Ada and GNAT.
20200 Furthermore the representation of these integer types is also identical,
20201 including the capability of size clauses forcing biased representation.
20202
20203 In addition,
20204 DEC Ada for OpenVMS Alpha systems has defined the
20205 following additional integer types in package System:
20206
20207 @itemize @bullet
20208
20209 @item
20210 INTEGER_8
20211
20212 @item
20213 INTEGER_16
20214
20215 @item
20216 INTEGER_32
20217
20218 @item
20219 INTEGER_64
20220
20221 @item
20222 LARGEST_INTEGER
20223 @end itemize
20224
20225 @noindent
20226 When using GNAT, the first four of these types may be obtained from the
20227 standard Ada 95 package @code{Interfaces}.
20228 Alternatively, by use of the pragma
20229 @code{Extend_System}, identical
20230 declarations can be referenced directly in package @code{System}.
20231 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
20232
20233 @node Floating-Point Types and Representations
20234 @subsection Floating-Point Types and Representations
20235 @cindex Floating-Point types
20236
20237 @noindent
20238 The set of predefined floating-point types is identical in DEC Ada and GNAT.
20239 Furthermore the representation of these floating-point
20240 types is also identical. One important difference is that the default
20241 representation for DEC Ada is VAX_Float, but the default representation
20242 for GNAT is IEEE.
20243
20244 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20245 @code{Float_Representation} as described in the DEC Ada documentation.
20246 For example, the declarations:
20247
20248 @smallexample @c ada
20249 @group
20250 @cartouche
20251 type F_Float is digits 6;
20252 pragma Float_Representation (VAX_Float, F_Float);
20253 @end cartouche
20254 @end group
20255 @end smallexample
20256
20257 @noindent
20258 declare a type F_Float that will be represented in VAX_Float format.
20259 This set of declarations actually appears in System.Aux_DEC, which provides
20260 the full set of additional floating-point declarations provided in
20261 the DEC Ada version of package
20262 System. This and similar declarations may be accessed in a user program
20263 by using pragma @code{Extend_System}. The use of this
20264 pragma, and the related pragma @code{Long_Float} is described in further
20265 detail in the following section.
20266
20267 @node Pragmas Float_Representation and Long_Float
20268 @subsection Pragmas Float_Representation and Long_Float
20269
20270 @noindent
20271 DEC Ada provides the pragma @code{Float_Representation}, which
20272 acts as a program library switch to allow control over
20273 the internal representation chosen for the predefined
20274 floating-point types declared in the package @code{Standard}.
20275 The format of this pragma is as follows:
20276
20277 @smallexample
20278 @group
20279 @cartouche
20280 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20281 @end cartouche
20282 @end group
20283 @end smallexample
20284
20285 @noindent
20286 This pragma controls the representation of floating-point
20287 types as follows:
20288
20289 @itemize @bullet
20290 @item
20291 @code{VAX_Float} specifies that floating-point
20292 types are represented by default with the VAX hardware types
20293 F-floating, D-floating, G-floating. Note that the H-floating
20294 type is available only on DIGITAL Vax systems, and is not available
20295 in either DEC Ada or GNAT for Alpha systems.
20296
20297 @item
20298 @code{IEEE_Float} specifies that floating-point
20299 types are represented by default with the IEEE single and
20300 double floating-point types.
20301 @end itemize
20302
20303 @noindent
20304 GNAT provides an identical implementation of the pragma
20305 @code{Float_Representation}, except that it functions as a
20306 configuration pragma, as defined by Ada 95. Note that the
20307 notion of configuration pragma corresponds closely to the
20308 DEC Ada notion of a program library switch.
20309
20310 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20311 from DEC Ada 83, where the default is VAX_Float. In addition, the
20312 predefined libraries in GNAT are built using IEEE_Float, so it is not
20313 advisable to change the format of numbers passed to standard library
20314 routines, and if necessary explicit type conversions may be needed.
20315
20316 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20317 and (given that it conforms to an international standard) potentially more
20318 portable. The situation in which VAX_Float may be useful is in interfacing
20319 to existing code and data that expects the use of VAX_Float. There are
20320 two possibilities here. If the requirement for the use of VAX_Float is
20321 localized, then the best approach is to use the predefined VAX_Float
20322 types in package @code{System}, as extended by
20323 @code{Extend_System}. For example, use @code{System.F_Float}
20324 to specify the 32-bit @code{F-Float} format.
20325
20326 Alternatively, if an entire program depends heavily on the use of
20327 the @code{VAX_Float} and in particular assumes that the types in
20328 package @code{Standard} are in @code{Vax_Float} format, then it
20329 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20330 This is done by using the GNAT LIBRARY command to rebuild the library, and
20331 then using the general form of the @code{Float_Representation}
20332 pragma to ensure that this default format is used throughout.
20333 The form of the GNAT LIBRARY command is:
20334
20335 @smallexample
20336 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20337 @end smallexample
20338
20339 @noindent
20340 where @i{file} contains the new configuration pragmas
20341 and @i{directory} is the directory to be created to contain
20342 the new library.
20343
20344 @noindent
20345 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
20346 to allow control over the internal representation chosen
20347 for the predefined type @code{Long_Float} and for floating-point
20348 type declarations with digits specified in the range 7 .. 15.
20349 The format of this pragma is as follows:
20350
20351 @smallexample @c ada
20352 @cartouche
20353 pragma Long_Float (D_FLOAT | G_FLOAT);
20354 @end cartouche
20355 @end smallexample
20356
20357 @node Fixed-Point Types and Representations
20358 @subsection Fixed-Point Types and Representations
20359
20360 @noindent
20361 On DEC Ada for OpenVMS Alpha systems, rounding is
20362 away from zero for both positive and negative numbers.
20363 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20364
20365 On GNAT for OpenVMS Alpha, the results of operations
20366 on fixed-point types are in accordance with the Ada 95
20367 rules. In particular, results of operations on decimal
20368 fixed-point types are truncated.
20369
20370 @node Record and Array Component Alignment
20371 @subsection Record and Array Component Alignment
20372
20373 @noindent
20374 On DEC Ada for OpenVMS Alpha, all non composite components
20375 are aligned on natural boundaries. For example, 1-byte
20376 components are aligned on byte boundaries, 2-byte
20377 components on 2-byte boundaries, 4-byte components on 4-byte
20378 byte boundaries, and so on. The OpenVMS Alpha hardware
20379 runs more efficiently with naturally aligned data.
20380
20381 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20382 with DEC Ada for OpenVMS Alpha.
20383
20384 @node Address Clauses
20385 @subsection Address Clauses
20386
20387 @noindent
20388 In DEC Ada and GNAT, address clauses are supported for
20389 objects and imported subprograms.
20390 The predefined type @code{System.Address} is a private type
20391 in both compilers, with the same representation (it is simply
20392 a machine pointer). Addition, subtraction, and comparison
20393 operations are available in the standard Ada 95 package
20394 @code{System.Storage_Elements}, or in package @code{System}
20395 if it is extended to include @code{System.Aux_DEC} using a
20396 pragma @code{Extend_System} as previously described.
20397
20398 Note that code that with's both this extended package @code{System}
20399 and the package @code{System.Storage_Elements} should not @code{use}
20400 both packages, or ambiguities will result. In general it is better
20401 not to mix these two sets of facilities. The Ada 95 package was
20402 designed specifically to provide the kind of features that DEC Ada
20403 adds directly to package @code{System}.
20404
20405 GNAT is compatible with DEC Ada in its handling of address
20406 clauses, except for some limitations in
20407 the form of address clauses for composite objects with
20408 initialization. Such address clauses are easily replaced
20409 by the use of an explicitly-defined constant as described
20410 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20411 of declarations:
20412
20413 @smallexample @c ada
20414 @cartouche
20415 X, Y : Integer := Init_Func;
20416 Q : String (X .. Y) := "abc";
20417 ...
20418 for Q'Address use Compute_Address;
20419 @end cartouche
20420 @end smallexample
20421
20422 @noindent
20423 will be rejected by GNAT, since the address cannot be computed at the time
20424 that Q is declared. To achieve the intended effect, write instead:
20425
20426 @smallexample @c ada
20427 @group
20428 @cartouche
20429 X, Y : Integer := Init_Func;
20430 Q_Address : constant Address := Compute_Address;
20431 Q : String (X .. Y) := "abc";
20432 ...
20433 for Q'Address use Q_Address;
20434 @end cartouche
20435 @end group
20436 @end smallexample
20437
20438 @noindent
20439 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20440 backwards compatible with Ada 83. A fuller description of the restrictions
20441 on address specifications is found in the GNAT Reference Manual.
20442
20443 @node Other Representation Clauses
20444 @subsection Other Representation Clauses
20445
20446 @noindent
20447 GNAT supports in a compatible manner all the representation
20448 clauses supported by DEC Ada. In addition, it
20449 supports representation clause forms that are new in Ada 95
20450 including COMPONENT_SIZE and SIZE clauses for objects.
20451
20452 @node The Package STANDARD
20453 @section The Package STANDARD
20454
20455 @noindent
20456 The package STANDARD, as implemented by DEC Ada, is fully
20457 described in the Reference Manual for the Ada Programming
20458 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
20459 Language Reference Manual. As implemented by GNAT, the
20460 package STANDARD is described in the Ada 95 Reference
20461 Manual.
20462
20463 In addition, DEC Ada supports the Latin-1 character set in
20464 the type CHARACTER. GNAT supports the Latin-1 character set
20465 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20466 the type WIDE_CHARACTER.
20467
20468 The floating-point types supported by GNAT are those
20469 supported by DEC Ada, but defaults are different, and are controlled by
20470 pragmas. See @ref{Floating-Point Types and Representations} for details.
20471
20472 @node The Package SYSTEM
20473 @section The Package SYSTEM
20474
20475 @noindent
20476 DEC Ada provides a system-specific version of the package
20477 SYSTEM for each platform on which the language ships.
20478 For the complete specification of the package SYSTEM, see
20479 Appendix F of the DEC Ada Language Reference Manual.
20480
20481 On DEC Ada, the package SYSTEM includes the following conversion functions:
20482 @itemize @bullet
20483 @item TO_ADDRESS(INTEGER)
20484
20485 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
20486
20487 @item  TO_ADDRESS(universal_integer)
20488
20489 @item  TO_INTEGER(ADDRESS)
20490
20491 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
20492
20493 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20494                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20495 @end itemize
20496
20497 @noindent
20498 By default, GNAT supplies a version of SYSTEM that matches
20499 the definition given in the Ada 95 Reference Manual.
20500 This
20501 is a subset of the DIGITAL system definitions, which is as
20502 close as possible to the original definitions. The only difference
20503 is that the definition of SYSTEM_NAME is different:
20504
20505 @smallexample @c ada
20506 @group
20507 @cartouche
20508 type Name is (SYSTEM_NAME_GNAT);
20509 System_Name : constant Name := SYSTEM_NAME_GNAT;
20510 @end cartouche
20511 @end group
20512 @end smallexample
20513
20514 @noindent
20515 Also, GNAT adds the new Ada 95 declarations for
20516 BIT_ORDER and DEFAULT_BIT_ORDER.
20517
20518 However, the use of the following pragma causes GNAT
20519 to extend the definition of package SYSTEM so that it
20520 encompasses the full set of DIGITAL-specific extensions,
20521 including the functions listed above:
20522
20523 @smallexample @c ada
20524 @cartouche
20525 pragma Extend_System (Aux_DEC);
20526 @end cartouche
20527 @end smallexample
20528
20529 @noindent
20530 The pragma Extend_System is a configuration pragma that
20531 is most conveniently placed in the @file{gnat.adc} file. See the
20532 GNAT Reference Manual for further details.
20533
20534 DEC Ada does not allow the recompilation of the package
20535 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
20536 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20537 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20538 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20539 its single argument.
20540
20541 GNAT does permit the recompilation of package SYSTEM using
20542 a special switch (@option{-gnatg}) and this switch can be used if
20543 it is necessary to modify the definitions in SYSTEM. GNAT does
20544 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20545 or MEMORY_SIZE by any other means.
20546
20547 On GNAT systems, the pragma SYSTEM_NAME takes the
20548 enumeration literal SYSTEM_NAME_GNAT.
20549
20550 The definitions provided by the use of
20551
20552 @smallexample @c ada
20553 pragma Extend_System (AUX_Dec);
20554 @end smallexample
20555
20556 @noindent
20557 are virtually identical to those provided by the DEC Ada 83 package
20558 System. One important difference is that the name of the TO_ADDRESS
20559 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20560 See the GNAT Reference manual for a discussion of why this change was
20561 necessary.
20562
20563 @noindent
20564 The version of TO_ADDRESS taking a universal integer argument is in fact
20565 an extension to Ada 83 not strictly compatible with the reference manual.
20566 In GNAT, we are constrained to be exactly compatible with the standard,
20567 and this means we cannot provide this capability. In DEC Ada 83, the
20568 point of this definition is to deal with a call like:
20569
20570 @smallexample @c ada
20571 TO_ADDRESS (16#12777#);
20572 @end smallexample
20573
20574 @noindent
20575 Normally, according to the Ada 83 standard, one would expect this to be
20576 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20577 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
20578 definition using universal_integer takes precedence.
20579
20580 In GNAT, since the version with universal_integer cannot be supplied, it is
20581 not possible to be 100% compatible. Since there are many programs using
20582 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20583 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20584 declarations provided in the GNAT version of AUX_Dec are:
20585
20586 @smallexample @c ada
20587 function To_Address (X : Integer) return Address;
20588 pragma Pure_Function (To_Address);
20589
20590 function To_Address_Long (X : Unsigned_Longword) return Address;
20591 pragma Pure_Function (To_Address_Long);
20592 @end smallexample
20593
20594 @noindent
20595 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20596 change the name to TO_ADDRESS_LONG.
20597
20598 @node Tasking and Task-Related Features
20599 @section Tasking and Task-Related Features
20600
20601 @noindent
20602 The concepts relevant to a comparison of tasking on GNAT
20603 and on DEC Ada for OpenVMS Alpha systems are discussed in
20604 the following sections.
20605
20606 For detailed information on concepts related to tasking in
20607 DEC Ada, see the DEC Ada Language Reference Manual and the
20608 relevant run-time reference manual.
20609
20610 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20611 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20612
20613 @noindent
20614 On OpenVMS Alpha systems, each Ada task (except a passive
20615 task) is implemented as a single stream of execution
20616 that is created and managed by the kernel. On these
20617 systems, DEC Ada tasking support is based on DECthreads,
20618 an implementation of the POSIX standard for threads.
20619
20620 Although tasks are implemented as threads, all tasks in
20621 an Ada program are part of the same process. As a result,
20622 resources such as open files and virtual memory can be
20623 shared easily among tasks. Having all tasks in one process
20624 allows better integration with the programming environment
20625 (the shell and the debugger, for example).
20626
20627 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
20628 code that calls DECthreads routines can be used together.
20629 The interaction between Ada tasks and DECthreads routines
20630 can have some benefits. For example when on OpenVMS Alpha,
20631 DEC Ada can call C code that is already threaded.
20632 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20633 and Ada tasks are mapped to threads.
20634
20635 @menu
20636 * Assigning Task IDs::
20637 * Task IDs and Delays::
20638 * Task-Related Pragmas::
20639 * Scheduling and Task Priority::
20640 * The Task Stack::
20641 * External Interrupts::
20642 @end menu
20643
20644 @node Assigning Task IDs
20645 @subsection Assigning Task IDs
20646
20647 @noindent
20648 The DEC Ada Run-Time Library always assigns %TASK 1 to
20649 the environment task that executes the main program. On
20650 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20651 that have been created but are not yet activated.
20652
20653 On OpenVMS Alpha systems, task IDs are assigned at
20654 activation. On GNAT systems, task IDs are also assigned at
20655 task creation but do not have the same form or values as
20656 task ID values in DEC Ada. There is no null task, and the
20657 environment task does not have a specific task ID value.
20658
20659 @node Task IDs and Delays
20660 @subsection Task IDs and Delays
20661
20662 @noindent
20663 On OpenVMS Alpha systems, tasking delays are implemented
20664 using Timer System Services. The Task ID is used for the
20665 identification of the timer request (the REQIDT parameter).
20666 If Timers are used in the application take care not to use
20667 0 for the identification, because cancelling such a timer
20668 will cancel all timers and may lead to unpredictable results.
20669
20670 @node Task-Related Pragmas
20671 @subsection Task-Related Pragmas
20672
20673 @noindent
20674 Ada supplies the pragma TASK_STORAGE, which allows
20675 specification of the size of the guard area for a task
20676 stack. (The guard area forms an area of memory that has no
20677 read or write access and thus helps in the detection of
20678 stack overflow.) On OpenVMS Alpha systems, if the pragma
20679 TASK_STORAGE specifies a value of zero, a minimal guard
20680 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20681 area is created.
20682
20683 GNAT supplies the following task-related pragmas:
20684
20685 @itemize @bullet
20686 @item  TASK_INFO
20687
20688               This pragma appears within a task definition and
20689               applies to the task in which it appears. The argument
20690               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
20691
20692 @item  TASK_STORAGE
20693
20694               GNAT implements pragma TASK_STORAGE in the same way as
20695               DEC Ada.
20696               Both DEC Ada and GNAT supply the pragmas PASSIVE,
20697               SUPPRESS, and VOLATILE.
20698 @end itemize
20699 @node Scheduling and Task Priority
20700 @subsection Scheduling and Task Priority
20701
20702 @noindent
20703 DEC Ada implements the Ada language requirement that
20704 when two tasks are eligible for execution and they have
20705 different priorities, the lower priority task does not
20706 execute while the higher priority task is waiting. The DEC
20707 Ada Run-Time Library keeps a task running until either the
20708 task is suspended or a higher priority task becomes ready.
20709
20710 On OpenVMS Alpha systems, the default strategy is round-
20711 robin with preemption. Tasks of equal priority take turns
20712 at the processor. A task is run for a certain period of
20713 time and then placed at the rear of the ready queue for
20714 its priority level.
20715
20716 DEC Ada provides the implementation-defined pragma TIME_SLICE,
20717 which can be used to enable or disable round-robin
20718 scheduling of tasks with the same priority.
20719 See the relevant DEC Ada run-time reference manual for
20720 information on using the pragmas to control DEC Ada task
20721 scheduling.
20722
20723 GNAT follows the scheduling rules of Annex D (real-time
20724 Annex) of the Ada 95 Reference Manual. In general, this
20725 scheduling strategy is fully compatible with DEC Ada
20726 although it provides some additional constraints (as
20727 fully documented in Annex D).
20728 GNAT implements time slicing control in a manner compatible with
20729 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
20730 to the DEC Ada 83 pragma of the same name.
20731 Note that it is not possible to mix GNAT tasking and
20732 DEC Ada 83 tasking in the same program, since the two run times are
20733 not compatible.
20734
20735 @node The Task Stack
20736 @subsection The Task Stack
20737
20738 @noindent
20739 In DEC Ada, a task stack is allocated each time a
20740 non passive task is activated. As soon as the task is
20741 terminated, the storage for the task stack is deallocated.
20742 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20743 a default stack size is used. Also, regardless of the size
20744 specified, some additional space is allocated for task
20745 management purposes. On OpenVMS Alpha systems, at least
20746 one page is allocated.
20747
20748 GNAT handles task stacks in a similar manner. According to
20749 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20750 an alternative method for controlling the task stack size.
20751 The specification of the attribute T'STORAGE_SIZE is also
20752 supported in a manner compatible with DEC Ada.
20753
20754 @node External Interrupts
20755 @subsection External Interrupts
20756
20757 @noindent
20758 On DEC Ada, external interrupts can be associated with task entries.
20759 GNAT is compatible with DEC Ada in its handling of external interrupts.
20760
20761 @node Pragmas and Pragma-Related Features
20762 @section Pragmas and Pragma-Related Features
20763
20764 @noindent
20765 Both DEC Ada and GNAT supply all language-defined pragmas
20766 as specified by the Ada 83 standard. GNAT also supplies all
20767 language-defined pragmas specified in the Ada 95 Reference Manual.
20768 In addition, GNAT implements the implementation-defined pragmas
20769 from DEC Ada 83.
20770
20771 @itemize @bullet
20772 @item  AST_ENTRY
20773
20774 @item  COMMON_OBJECT
20775
20776 @item  COMPONENT_ALIGNMENT
20777
20778 @item  EXPORT_EXCEPTION
20779
20780 @item  EXPORT_FUNCTION
20781
20782 @item  EXPORT_OBJECT
20783
20784 @item  EXPORT_PROCEDURE
20785
20786 @item  EXPORT_VALUED_PROCEDURE
20787
20788 @item  FLOAT_REPRESENTATION
20789
20790 @item  IDENT
20791
20792 @item  IMPORT_EXCEPTION
20793
20794 @item  IMPORT_FUNCTION
20795
20796 @item  IMPORT_OBJECT
20797
20798 @item  IMPORT_PROCEDURE
20799
20800 @item  IMPORT_VALUED_PROCEDURE
20801
20802 @item  INLINE_GENERIC
20803
20804 @item  INTERFACE_NAME
20805
20806 @item  LONG_FLOAT
20807
20808 @item  MAIN_STORAGE
20809
20810 @item  PASSIVE
20811
20812 @item  PSET_OBJECT
20813
20814 @item  SHARE_GENERIC
20815
20816 @item  SUPPRESS_ALL
20817
20818 @item  TASK_STORAGE
20819
20820 @item  TIME_SLICE
20821
20822 @item  TITLE
20823 @end itemize
20824
20825 @noindent
20826 These pragmas are all fully implemented, with the exception of @code{Title},
20827 @code{Passive}, and @code{Share_Generic}, which are
20828 recognized, but which have no
20829 effect in GNAT. The effect of @code{Passive} may be obtained by the
20830 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20831
20832 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20833 a separate subprogram specification which must appear before the
20834 subprogram body.
20835
20836 GNAT also supplies a number of implementation-defined pragmas as follows:
20837 @itemize @bullet
20838 @item  C_PASS_BY_COPY
20839
20840 @item  EXTEND_SYSTEM
20841
20842 @item  SOURCE_FILE_NAME
20843
20844 @item  UNSUPPRESS
20845
20846 @item  WARNINGS
20847
20848 @item  ABORT_DEFER
20849
20850 @item  ADA_83
20851
20852 @item  ADA_95
20853
20854 @item  ADA_05
20855
20856 @item  ANNOTATE
20857
20858 @item  ASSERT
20859
20860 @item  CPP_CLASS
20861
20862 @item  CPP_CONSTRUCTOR
20863
20864 @item  CPP_DESTRUCTOR
20865
20866 @item  CPP_VIRTUAL
20867
20868 @item  CP_VTABLE
20869
20870 @item  DEBUG
20871
20872 @item  LINKER_ALIAS
20873
20874 @item  LINKER_SECTION
20875
20876 @item  MACHINE_ATTRIBUTE
20877
20878 @item  NO_RETURN
20879
20880 @item  PURE_FUNCTION
20881
20882 @item  SOURCE_REFERENCE
20883
20884 @item  TASK_INFO
20885
20886 @item  UNCHECKED_UNION
20887
20888 @item  UNIMPLEMENTED_UNIT
20889
20890 @item  UNIVERSAL_DATA
20891
20892 @item  WEAK_EXTERNAL
20893 @end itemize
20894
20895 @noindent
20896 For full details on these GNAT implementation-defined pragmas, see
20897 the GNAT Reference Manual.
20898
20899 @menu
20900 * Restrictions on the Pragma INLINE::
20901 * Restrictions on the Pragma INTERFACE::
20902 * Restrictions on the Pragma SYSTEM_NAME::
20903 @end menu
20904
20905 @node Restrictions on the Pragma INLINE
20906 @subsection Restrictions on the Pragma INLINE
20907
20908 @noindent
20909 DEC Ada applies the following restrictions to the pragma INLINE:
20910 @itemize @bullet
20911 @item  Parameters cannot be a task type.
20912
20913 @item  Function results cannot be task types, unconstrained
20914 array types, or unconstrained types with discriminants.
20915
20916 @item  Bodies cannot declare the following:
20917 @itemize @bullet
20918 @item  Subprogram body or stub (imported subprogram is allowed)
20919
20920 @item  Tasks
20921
20922 @item  Generic declarations
20923
20924 @item  Instantiations
20925
20926 @item  Exceptions
20927
20928 @item  Access types (types derived from access types allowed)
20929
20930 @item  Array or record types
20931
20932 @item  Dependent tasks
20933
20934 @item  Direct recursive calls of subprogram or containing
20935 subprogram, directly or via a renaming
20936
20937 @end itemize
20938 @end itemize
20939
20940 @noindent
20941 In GNAT, the only restriction on pragma INLINE is that the
20942 body must occur before the call if both are in the same
20943 unit, and the size must be appropriately small. There are
20944 no other specific restrictions which cause subprograms to
20945 be incapable of being inlined.
20946
20947 @node  Restrictions on the Pragma INTERFACE
20948 @subsection  Restrictions on the Pragma INTERFACE
20949
20950 @noindent
20951 The following lists and describes the restrictions on the
20952 pragma INTERFACE on DEC Ada and GNAT:
20953 @itemize @bullet
20954 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20955 Default is the default on OpenVMS Alpha systems.
20956
20957 @item  Parameter passing: Language specifies default
20958 mechanisms but can be overridden with an EXPORT pragma.
20959
20960 @itemize @bullet
20961 @item  Ada: Use internal Ada rules.
20962
20963 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20964 record or task type. Result cannot be a string, an
20965 array, or a record.
20966
20967 @item  Fortran: Parameters cannot be a task. Result cannot
20968 be a string, an array, or a record.
20969 @end itemize
20970 @end itemize
20971
20972 @noindent
20973 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20974 record parameters for all languages.
20975
20976 @node  Restrictions on the Pragma SYSTEM_NAME
20977 @subsection  Restrictions on the Pragma SYSTEM_NAME
20978
20979 @noindent
20980 For DEC Ada for OpenVMS Alpha, the enumeration literal
20981 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20982 literal for the type NAME is SYSTEM_NAME_GNAT.
20983
20984 @node  Library of Predefined Units
20985 @section  Library of Predefined Units
20986
20987 @noindent
20988 A library of predefined units is provided as part of the
20989 DEC Ada and GNAT implementations. DEC Ada does not provide
20990 the package MACHINE_CODE but instead recommends importing
20991 assembler code.
20992
20993 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20994 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20995 version. During GNAT installation, the DEC Ada Predefined
20996 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20997 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20998 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20999 for details.
21000
21001 The GNAT RTL is contained in
21002 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
21003 the default search path is set up to find DECLIB units in preference
21004 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
21005 for example).
21006
21007 However, it is possible to change the default so that the
21008 reverse is true, or even to mix them using child package
21009 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
21010 is the package name, and the Ada units are available in the
21011 standard manner defined for Ada 95, that is to say as Ada.xxx. To
21012 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
21013 appropriately. For example, to change the default to use the Ada95
21014 versions do:
21015
21016 @smallexample
21017 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
21018                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21019 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
21020                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21021 @end smallexample
21022
21023 @menu
21024 * Changes to DECLIB::
21025 @end menu
21026
21027 @node Changes to DECLIB
21028 @subsection Changes to DECLIB
21029
21030 @noindent
21031 The changes made to the DEC Ada predefined library for GNAT and Ada 95
21032 compatibility are minor and include the following:
21033
21034 @itemize @bullet
21035 @item  Adjusting the location of pragmas and record representation
21036 clauses to obey Ada 95 rules
21037
21038 @item  Adding the proper notation to generic formal parameters
21039 that take unconstrained types in instantiation
21040
21041 @item  Adding pragma ELABORATE_BODY to package specifications
21042 that have package bodies not otherwise allowed
21043
21044 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
21045 @code{"PROTECTD"}.
21046 Currently these are found only in the STARLET package spec.
21047 @end itemize
21048
21049 @noindent
21050 None of the above changes is visible to users.
21051
21052 @node Bindings
21053 @section Bindings
21054
21055 @noindent
21056 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
21057 @itemize @bullet
21058
21059 @item  Command Language Interpreter (CLI interface)
21060
21061 @item  DECtalk Run-Time Library (DTK interface)
21062
21063 @item  Librarian utility routines (LBR interface)
21064
21065 @item  General Purpose Run-Time Library (LIB interface)
21066
21067 @item  Math Run-Time Library (MTH interface)
21068
21069 @item  National Character Set Run-Time Library (NCS interface)
21070
21071 @item  Compiled Code Support Run-Time Library (OTS interface)
21072
21073 @item  Parallel Processing Run-Time Library (PPL interface)
21074
21075 @item  Screen Management Run-Time Library (SMG interface)
21076
21077 @item  Sort Run-Time Library (SOR interface)
21078
21079 @item  String Run-Time Library (STR interface)
21080
21081 @item STARLET System Library
21082 @findex Starlet
21083
21084 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21085
21086 @item  X Windows Toolkit (XT interface)
21087
21088 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21089 @end itemize
21090
21091 @noindent
21092 GNAT provides implementations of these DEC bindings in the DECLIB directory.
21093
21094 The X/Motif bindings used to build DECLIB are whatever versions are in the
21095 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21096 The build script will
21097 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
21098 and @code{X_Lib}
21099 causing the default X/Motif sharable image libraries to be linked in. This
21100 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21101 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21102
21103 It may be necessary to edit these options files to update or correct the
21104 library names if, for example, the newer X/Motif bindings from
21105 @file{ADA$EXAMPLES}
21106 had been (previous to installing GNAT) copied and renamed to supersede the
21107 default @file{ADA$PREDEFINED} versions.
21108
21109 @menu
21110 * Shared Libraries and Options Files::
21111 * Interfaces to C::
21112 @end menu
21113
21114 @node Shared Libraries and Options Files
21115 @subsection Shared Libraries and Options Files
21116
21117 @noindent
21118 When using the DEC Ada
21119 predefined X and Motif bindings, the linking with their sharable images is
21120 done automatically by @command{GNAT LINK}.
21121 When using other X and Motif bindings, you need
21122 to add the corresponding sharable images to the command line for
21123 @code{GNAT LINK}. When linking with shared libraries, or with
21124 @file{.OPT} files, you must
21125 also add them to the command line for @command{GNAT LINK}.
21126
21127 A shared library to be used with GNAT is built in the same way as other
21128 libraries under VMS. The VMS Link command can be used in standard fashion.
21129
21130 @node Interfaces to C
21131 @subsection Interfaces to C
21132
21133 @noindent
21134 DEC Ada
21135 provides the following Ada types and operations:
21136
21137 @itemize @bullet
21138 @item C types package (C_TYPES)
21139
21140 @item C strings (C_TYPES.NULL_TERMINATED)
21141
21142 @item Other_types (SHORT_INT)
21143 @end itemize
21144
21145 @noindent
21146 Interfacing to C with GNAT, one can use the above approach
21147 described for DEC Ada or the facilities of Annex B of
21148 the Ada 95 Reference Manual (packages INTERFACES.C,
21149 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21150 information, see the section ``Interfacing to C'' in the
21151 @cite{GNAT Reference Manual}.
21152
21153 The @option{-gnatF} qualifier forces default and explicit
21154 @code{External_Name} parameters in pragmas Import and Export
21155 to be uppercased for compatibility with the default behavior
21156 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21157
21158 @node Main Program Definition
21159 @section Main Program Definition
21160
21161 @noindent
21162 The following section discusses differences in the
21163 definition of main programs on DEC Ada and GNAT.
21164 On DEC Ada, main programs are defined to meet the
21165 following conditions:
21166 @itemize @bullet
21167 @item  Procedure with no formal parameters (returns 0 upon
21168        normal completion)
21169
21170 @item  Procedure with no formal parameters (returns 42 when
21171        unhandled exceptions are raised)
21172
21173 @item  Function with no formal parameters whose returned value
21174        is of a discrete type
21175
21176 @item  Procedure with one OUT formal of a discrete type for
21177        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21178
21179 @end itemize
21180
21181 @noindent
21182 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21183 a main function or main procedure returns a discrete
21184 value whose size is less than 64 bits (32 on VAX systems),
21185 the value is zero- or sign-extended as appropriate.
21186 On GNAT, main programs are defined as follows:
21187 @itemize @bullet
21188 @item  Must be a non-generic, parameter-less subprogram that
21189 is either a procedure or function returning an Ada
21190 STANDARD.INTEGER (the predefined type)
21191
21192 @item  Cannot be a generic subprogram or an instantiation of a
21193 generic subprogram
21194 @end itemize
21195
21196 @node Implementation-Defined Attributes
21197 @section Implementation-Defined Attributes
21198
21199 @noindent
21200 GNAT provides all DEC Ada implementation-defined
21201 attributes.
21202
21203 @node Compiler and Run-Time Interfacing
21204 @section Compiler and Run-Time Interfacing
21205
21206 @noindent
21207 DEC Ada provides the following ways to pass options to the linker
21208 (ACS LINK):
21209 @itemize @bullet
21210 @item  /WAIT and /SUBMIT qualifiers
21211
21212 @item  /COMMAND qualifier
21213
21214 @item  /[NO]MAP qualifier
21215
21216 @item  /OUTPUT=file-spec
21217
21218 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21219 @end itemize
21220
21221 @noindent
21222 To pass options to the linker, GNAT provides the following
21223 switches:
21224
21225 @itemize @bullet
21226 @item   @option{/EXECUTABLE=exec-name}
21227
21228 @item   @option{/VERBOSE qualifier}
21229
21230 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21231 @end itemize
21232
21233 @noindent
21234 For more information on these switches, see
21235 @ref{Switches for gnatlink}.
21236 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
21237 to control optimization. DEC Ada also supplies the
21238 following pragmas:
21239 @itemize @bullet
21240 @item  @code{OPTIMIZE}
21241
21242 @item  @code{INLINE}
21243
21244 @item  @code{INLINE_GENERIC}
21245
21246 @item  @code{SUPPRESS_ALL}
21247
21248 @item  @code{PASSIVE}
21249 @end itemize
21250
21251 @noindent
21252 In GNAT, optimization is controlled strictly by command
21253 line parameters, as described in the corresponding section of this guide.
21254 The DIGITAL pragmas for control of optimization are
21255 recognized but ignored.
21256
21257 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
21258 the default is that optimization is turned on.
21259
21260 @node Program Compilation and Library Management
21261 @section Program Compilation and Library Management
21262
21263 @noindent
21264 DEC Ada and GNAT provide a comparable set of commands to
21265 build programs. DEC Ada also provides a program library,
21266 which is a concept that does not exist on GNAT. Instead,
21267 GNAT provides directories of sources that are compiled as
21268 needed.
21269
21270 The following table summarizes
21271 the DEC Ada commands and provides
21272 equivalent GNAT commands. In this table, some GNAT
21273 equivalents reflect the fact that GNAT does not use the
21274 concept of a program library. Instead, it uses a model
21275 in which collections of source and object files are used
21276 in a manner consistent with other languages like C and
21277 Fortran. Therefore, standard system file commands are used
21278 to manipulate these elements. Those GNAT commands are marked with
21279 an asterisk.
21280 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
21281
21282 @need 1500
21283 @multitable @columnfractions .35 .65
21284
21285 @item @emph{DEC Ada Command}
21286 @tab @emph{GNAT Equivalent / Description}
21287
21288 @item @command{ADA}
21289 @tab @command{GNAT COMPILE}@*
21290 Invokes the compiler to compile one or more Ada source files.
21291
21292 @item @command{ACS ATTACH}@*
21293 @tab [No equivalent]@*
21294 Switches control of terminal from current process running the program
21295 library manager.
21296
21297 @item @command{ACS CHECK}
21298 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21299 Forms the execution closure of one
21300 or more compiled units and checks completeness and currency.
21301
21302 @item @command{ACS COMPILE}
21303 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21304 Forms the execution closure of one or
21305 more specified units, checks completeness and currency,
21306 identifies units that have revised source files, compiles same,
21307 and recompiles units that are or will become obsolete.
21308 Also completes incomplete generic instantiations.
21309
21310 @item @command{ACS COPY FOREIGN}
21311 @tab Copy (*)@*
21312 Copies a foreign object file into the program library as a
21313 library unit body.
21314
21315 @item @command{ACS COPY UNIT}
21316 @tab Copy (*)@*
21317 Copies a compiled unit from one program library to another.
21318
21319 @item @command{ACS CREATE LIBRARY}
21320 @tab Create /directory (*)@*
21321 Creates a program library.
21322
21323 @item @command{ACS CREATE SUBLIBRARY}
21324 @tab Create /directory (*)@*
21325 Creates a program sublibrary.
21326
21327 @item @command{ACS DELETE LIBRARY}
21328 @tab @*
21329 Deletes a program library and its contents.
21330
21331 @item @command{ACS DELETE SUBLIBRARY}
21332 @tab @*
21333 Deletes a program sublibrary and its contents.
21334
21335 @item @command{ACS DELETE UNIT}
21336 @tab Delete file (*)@*
21337 On OpenVMS systems, deletes one or more compiled units from
21338 the current program library.
21339
21340 @item @command{ACS DIRECTORY}
21341 @tab Directory (*)@*
21342 On OpenVMS systems, lists units contained in the current
21343 program library.
21344
21345 @item @command{ACS ENTER FOREIGN}
21346 @tab Copy (*)@*
21347 Allows the import of a foreign body as an Ada library
21348 specification and enters a reference to a pointer.
21349
21350 @item @command{ACS ENTER UNIT}
21351 @tab Copy (*)@*
21352 Enters a reference (pointer) from the current program library to
21353 a unit compiled into another program library.
21354
21355 @item @command{ACS EXIT}
21356 @tab [No equivalent]@*
21357 Exits from the program library manager.
21358
21359 @item @command{ACS EXPORT}
21360 @tab Copy (*)@*
21361 Creates an object file that contains system-specific object code
21362 for one or more units. With GNAT, object files can simply be copied
21363 into the desired directory.
21364
21365 @item @command{ACS EXTRACT SOURCE}
21366 @tab Copy (*)@*
21367 Allows access to the copied source file for each Ada compilation unit
21368
21369 @item @command{ACS HELP}
21370 @tab @command{HELP GNAT}@*
21371 Provides online help.
21372
21373 @item @command{ACS LINK}
21374 @tab @command{GNAT LINK}@*
21375 Links an object file containing Ada units into an executable file.
21376
21377 @item @command{ACS LOAD}
21378 @tab Copy (*)@*
21379 Loads (partially compiles) Ada units into the program library.
21380 Allows loading a program from a collection of files into a library
21381 without knowing the relationship among units.
21382
21383 @item @command{ACS MERGE}
21384 @tab Copy (*)@*
21385 Merges into the current program library, one or more units from
21386 another library where they were modified.
21387
21388 @item @command{ACS RECOMPILE}
21389 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21390 Recompiles from   external or copied source files any obsolete
21391 unit in the closure. Also, completes any incomplete generic
21392 instantiations.
21393
21394 @item @command{ACS REENTER}
21395 @tab @command{GNAT MAKE}@*
21396 Reenters current references to units compiled after last entered
21397 with the @command{ACS ENTER UNIT} command.
21398
21399 @item @command{ACS SET LIBRARY}
21400 @tab Set default (*)@*
21401 Defines a program library to be the compilation context as well
21402 as the target library for compiler output and commands in general.
21403
21404 @item @command{ACS SET PRAGMA}
21405 @tab Edit @file{gnat.adc} (*)@*
21406 Redefines specified  values of the library characteristics
21407 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21408 and @code{Float_Representation}.
21409
21410 @item @command{ACS SET SOURCE}
21411 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21412 Defines the source file search list for the @command{ACS COMPILE} command.
21413
21414 @item @command{ACS SHOW LIBRARY}
21415 @tab Directory (*)@*
21416 Lists information about one or more program libraries.
21417
21418 @item @command{ACS SHOW PROGRAM}
21419 @tab [No equivalent]@*
21420 Lists information about the execution closure of one or
21421 more units in the program library.
21422
21423 @item @command{ACS SHOW SOURCE}
21424 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21425 Shows the source file search used when compiling units.
21426
21427 @item @command{ACS SHOW VERSION}
21428 @tab Compile with @option{VERBOSE} option
21429 Displays the version number of the compiler and program library
21430 manager used.
21431
21432 @item @command{ACS SPAWN}
21433 @tab [No equivalent]@*
21434 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21435 command).
21436
21437 @item @command{ACS VERIFY}
21438 @tab [No equivalent]@*
21439 Performs a series of consistency checks on a program library to
21440 determine whether the library structure and library files are in
21441 valid form.
21442 @end multitable
21443
21444 @noindent
21445
21446 @node Input-Output
21447 @section Input-Output
21448
21449 @noindent
21450 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
21451 Management Services (RMS) to perform operations on
21452 external files.
21453
21454 @noindent
21455 DEC Ada and GNAT predefine an identical set of input-
21456 output packages. To make the use of the
21457 generic TEXT_IO operations more convenient, DEC Ada
21458 provides predefined library packages that instantiate the
21459 integer and floating-point operations for the predefined
21460 integer and floating-point types as shown in the following table.
21461
21462 @multitable @columnfractions .45 .55
21463 @item @emph{Package Name} @tab Instantiation
21464
21465 @item @code{INTEGER_TEXT_IO}
21466 @tab @code{INTEGER_IO(INTEGER)}
21467
21468 @item @code{SHORT_INTEGER_TEXT_IO}
21469 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21470
21471 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21472 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21473
21474 @item @code{FLOAT_TEXT_IO}
21475 @tab @code{FLOAT_IO(FLOAT)}
21476
21477 @item @code{LONG_FLOAT_TEXT_IO}
21478 @tab @code{FLOAT_IO(LONG_FLOAT)}
21479 @end multitable
21480
21481 @noindent
21482 The DEC Ada predefined packages and their operations
21483 are implemented using OpenVMS Alpha files and input-
21484 output facilities. DEC Ada supports asynchronous input-
21485 output on OpenVMS Alpha. Familiarity with the following is
21486 recommended:
21487 @itemize @bullet
21488 @item  RMS file organizations and access methods
21489
21490 @item  OpenVMS file specifications and directories
21491
21492 @item  OpenVMS File Definition Language (FDL)
21493 @end itemize
21494
21495 @noindent
21496 GNAT provides I/O facilities that are completely
21497 compatible with DEC Ada. The distribution includes the
21498 standard DEC Ada versions of all I/O packages, operating
21499 in a manner compatible with DEC Ada. In particular, the
21500 following packages are by default the DEC Ada (Ada 83)
21501 versions of these packages rather than the renamings
21502 suggested in annex J of the Ada 95 Reference Manual:
21503 @itemize @bullet
21504 @item  @code{TEXT_IO}
21505
21506 @item  @code{SEQUENTIAL_IO}
21507
21508 @item  @code{DIRECT_IO}
21509 @end itemize
21510
21511 @noindent
21512 The use of the standard Ada 95 syntax for child packages (for
21513 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21514 packages, as defined in the Ada 95 Reference Manual.
21515 GNAT provides DIGITAL-compatible predefined instantiations
21516 of the @code{TEXT_IO} packages, and also
21517 provides the standard predefined instantiations required
21518 by the Ada 95 Reference Manual.
21519
21520 For further information on how GNAT interfaces to the file
21521 system or how I/O is implemented in programs written in
21522 mixed languages, see the chapter ``Implementation of the
21523 Standard I/O'' in the @cite{GNAT Reference Manual}.
21524 This chapter covers the following:
21525 @itemize @bullet
21526 @item  Standard I/O packages
21527
21528 @item  @code{FORM} strings
21529
21530 @item  @code{ADA.DIRECT_IO}
21531
21532 @item  @code{ADA.SEQUENTIAL_IO}
21533
21534 @item  @code{ADA.TEXT_IO}
21535
21536 @item  Stream pointer positioning
21537
21538 @item  Reading and writing non-regular files
21539
21540 @item  @code{GET_IMMEDIATE}
21541
21542 @item  Treating @code{TEXT_IO} files as streams
21543
21544 @item  Shared files
21545
21546 @item  Open modes
21547 @end itemize
21548
21549 @node Implementation Limits
21550 @section Implementation Limits
21551
21552 @noindent
21553 The following table lists implementation limits for DEC Ada
21554 and GNAT systems.
21555 @multitable @columnfractions .60 .20 .20
21556 @sp 1
21557 @item  @emph{Compilation Parameter}
21558 @tab   @emph{DEC Ada}
21559 @tab   @emph{GNAT}
21560 @sp 1
21561
21562 @item  In a subprogram or entry  declaration, maximum number of
21563        formal parameters that are of an unconstrained record type
21564 @tab   32
21565 @tab   No set limit
21566 @sp 1
21567
21568 @item  Maximum identifier length (number of characters)
21569 @tab   255
21570 @tab   255
21571 @sp 1
21572
21573 @item  Maximum number of characters in a source line
21574 @tab   255
21575 @tab   255
21576 @sp 1
21577
21578 @item  Maximum collection size   (number of bytes)
21579 @tab   2**31-1
21580 @tab   2**31-1
21581 @sp 1
21582
21583 @item  Maximum number of discriminants for a record type
21584 @tab   245
21585 @tab   No set limit
21586 @sp 1
21587
21588 @item  Maximum number of formal parameters in an entry or
21589        subprogram declaration
21590 @tab   246
21591 @tab    No set limit
21592 @sp 1
21593
21594 @item  Maximum number of dimensions in an array type
21595 @tab   255
21596 @tab   No set limit
21597 @sp 1
21598
21599 @item  Maximum number of library  units and subunits in a compilation.
21600 @tab   4095
21601 @tab   No set limit
21602 @sp 1
21603
21604 @item  Maximum number of library units and subunits in an execution.
21605 @tab   16383
21606 @tab   No set limit
21607 @sp 1
21608
21609 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21610        or @code{PSECT_OBJECT}
21611 @tab   32757
21612 @tab   No set limit
21613 @sp 1
21614
21615 @item  Maximum number of enumeration literals in an enumeration type
21616        definition
21617 @tab   65535
21618 @tab   No set limit
21619 @sp 1
21620
21621 @item  Maximum number of lines in a source file
21622 @tab   65534
21623 @tab   No set limit
21624 @sp 1
21625
21626 @item  Maximum number of bits in any object
21627 @tab   2**31-1
21628 @tab   2**31-1
21629 @sp 1
21630
21631 @item  Maximum size of the static portion of a stack frame (approximate)
21632 @tab   2**31-1
21633 @tab   2**31-1
21634 @end multitable
21635
21636 @node  Tools
21637 @section Tools
21638
21639 @end ifset
21640
21641 @c **************************************
21642 @node Platform-Specific Information for the Run-Time Libraries
21643 @appendix Platform-Specific Information for the Run-Time Libraries
21644 @cindex Tasking and threads libraries
21645 @cindex Threads libraries and tasking
21646 @cindex Run-time libraries (platform-specific information)
21647
21648 @noindent
21649 The GNAT run-time implementation may vary with respect to both the
21650 underlying threads library and the exception handling scheme.
21651 For threads support, one or more of the following are supplied:
21652 @itemize @bullet
21653 @item @b{native threads library}, a binding to the thread package from
21654 the underlying operating system
21655
21656 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21657 POSIX thread package
21658 @end itemize
21659
21660 @noindent
21661 For exception handling, either or both of two models are supplied:
21662 @itemize @bullet
21663 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21664 Most programs should experience a substantial speed improvement by
21665 being compiled with a ZCX run-time.
21666 This is especially true for
21667 tasking applications or applications with many exception handlers.}
21668 @cindex Zero-Cost Exceptions
21669 @cindex ZCX (Zero-Cost Exceptions)
21670 which uses binder-generated tables that
21671 are interrogated at run time to locate a handler
21672
21673 @item @b{setjmp / longjmp} (``SJLJ''),
21674 @cindex setjmp/longjmp Exception Model
21675 @cindex SJLJ (setjmp/longjmp Exception Model)
21676 which uses dynamically-set data to establish
21677 the set of handlers
21678 @end itemize
21679
21680 @noindent
21681 This appendix summarizes which combinations of threads and exception support
21682 are supplied on various GNAT platforms.
21683 It then shows how to select a particular library either
21684 permanently or temporarily,
21685 explains the properties of (and tradeoffs among) the various threads
21686 libraries, and provides some additional
21687 information about several specific platforms.
21688
21689 @menu
21690 * Summary of Run-Time Configurations::
21691 * Specifying a Run-Time Library::
21692 * Choosing the Scheduling Policy::
21693 * Solaris-Specific Considerations::
21694 * IRIX-Specific Considerations::
21695 * Linux-Specific Considerations::
21696 * AIX-Specific Considerations::
21697 @end menu
21698
21699 @node Summary of Run-Time Configurations
21700 @section Summary of Run-Time Configurations
21701
21702 @multitable @columnfractions .30 .70
21703 @item @b{alpha-openvms}
21704 @item @code{@ @ }@i{rts-native (default)}
21705 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21706 @item @code{@ @ @ @ }Exceptions @tab ZCX
21707 @*
21708 @item @b{pa-hpux}
21709 @item @code{@ @ }@i{rts-native (default)}
21710 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21711 @item @code{@ @ @ @ }Exceptions @tab ZCX
21712 @*
21713 @item @code{@ @ }@i{rts-sjlj}
21714 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21715 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21716 @*
21717 @item @b{sparc-solaris}  @tab
21718 @item @code{@ @ }@i{rts-native (default)}
21719 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21720 @item @code{@ @ @ @ }Exceptions @tab ZCX
21721 @*
21722 @item @code{@ @ }@i{rts-m64}
21723 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
21724 @item @code{@ @ @ @ }Exceptions  @tab ZCX
21725 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
21726 @item    @tab Use only on Solaris 8 or later.
21727 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
21728 @*
21729 @item @code{@ @ }@i{rts-pthread}
21730 @item @code{@ @ @ @ }Tasking    @tab pthreads library
21731 @item @code{@ @ @ @ }Exceptions @tab ZCX
21732 @*
21733 @item @code{@ @ }@i{rts-sjlj}
21734 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21735 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21736 @*
21737 @item @b{x86-linux}
21738 @item @code{@ @ }@i{rts-native (default)}
21739 @item @code{@ @ @ @ }Tasking    @tab pthread library
21740 @item @code{@ @ @ @ }Exceptions @tab ZCX
21741 @*
21742 @item @code{@ @ }@i{rts-sjlj}
21743 @item @code{@ @ @ @ }Tasking    @tab pthread library
21744 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21745 @*
21746 @item @b{x86-windows}
21747 @item @code{@ @ }@i{rts-native (default)}
21748 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21749 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21750 @*
21751 @end multitable
21752
21753 @node Specifying a Run-Time Library
21754 @section Specifying a Run-Time Library
21755
21756 @noindent
21757 The @file{adainclude} subdirectory containing the sources of the GNAT
21758 run-time library, and the @file{adalib} subdirectory containing the
21759 @file{ALI} files and the static and/or shared GNAT library, are located
21760 in the gcc target-dependent area:
21761
21762 @smallexample
21763 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21764 @end smallexample
21765
21766 @noindent
21767 As indicated above, on some platforms several run-time libraries are supplied.
21768 These libraries are installed in the target dependent area and
21769 contain a complete source and binary subdirectory. The detailed description
21770 below explains the differences between the different libraries in terms of
21771 their thread support.
21772
21773 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21774 This default run time is selected by the means of soft links.
21775 For example on x86-linux:
21776
21777 @smallexample
21778 @group
21779  $(target-dir)
21780      |
21781      +--- adainclude----------+
21782      |                        |
21783      +--- adalib-----------+  |
21784      |                     |  |
21785      +--- rts-native       |  |
21786      |    |                |  |
21787      |    +--- adainclude <---+
21788      |    |                |
21789      |    +--- adalib <----+
21790      |
21791      +--- rts-sjlj
21792           |
21793           +--- adainclude
21794           |
21795           +--- adalib
21796 @end group
21797 @end smallexample
21798
21799 @noindent
21800 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21801 these soft links can be modified with the following commands:
21802
21803 @smallexample
21804 $ cd $target
21805 $ rm -f adainclude adalib
21806 $ ln -s rts-sjlj/adainclude adainclude
21807 $ ln -s rts-sjlj/adalib adalib
21808 @end smallexample
21809
21810 @noindent
21811 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21812 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21813 @file{$target/ada_object_path}.
21814
21815 Selecting another run-time library temporarily can be
21816 achieved by the regular mechanism for GNAT object or source path selection:
21817
21818 @itemize @bullet
21819 @item
21820 Set the environment variables:
21821
21822 @smallexample
21823 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
21824 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
21825 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21826 @end smallexample
21827
21828 @item
21829 Use @option{-aI$target/rts-sjlj/adainclude}
21830 and @option{-aO$target/rts-sjlj/adalib}
21831 on the @command{gnatmake} command line
21832
21833 @item
21834 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
21835 @cindex @option{--RTS} option
21836 @end itemize
21837
21838 @node Choosing the Scheduling Policy
21839 @section Choosing the Scheduling Policy
21840
21841 @noindent
21842 When using a POSIX threads implementation, you have a choice of several
21843 scheduling policies: @code{SCHED_FIFO},
21844 @cindex @code{SCHED_FIFO} scheduling policy
21845 @code{SCHED_RR}
21846 @cindex @code{SCHED_RR} scheduling policy
21847 and @code{SCHED_OTHER}.
21848 @cindex @code{SCHED_OTHER} scheduling policy
21849 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21850 or @code{SCHED_RR} requires special (e.g., root) privileges.
21851
21852 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21853 @code{SCHED_FIFO},
21854 @cindex @code{SCHED_FIFO} scheduling policy
21855 you can use one of the following:
21856
21857 @itemize @bullet
21858 @item
21859 @code{pragma Time_Slice (0.0)}
21860 @cindex pragma Time_Slice
21861 @item
21862 the corresponding binder option @option{-T0}
21863 @cindex @option{-T0} option
21864 @item
21865 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21866 @cindex pragma Task_Dispatching_Policy
21867 @end itemize
21868
21869 @noindent
21870 To specify @code{SCHED_RR},
21871 @cindex @code{SCHED_RR} scheduling policy
21872 you should use @code{pragma Time_Slice} with a
21873 value greater than @code{0.0}, or else use the corresponding @option{-T}
21874 binder option.
21875
21876 @node Solaris-Specific Considerations
21877 @section Solaris-Specific Considerations
21878 @cindex Solaris Sparc threads libraries
21879
21880 @noindent
21881 This section addresses some topics related to the various threads libraries
21882 on Sparc Solaris and then provides some information on building and
21883 debugging 64-bit applications.
21884
21885 @menu
21886 * Solaris Threads Issues::
21887 * Building and Debugging 64-bit Applications::
21888 @end menu
21889
21890 @node Solaris Threads Issues
21891 @subsection Solaris Threads Issues
21892
21893 @noindent
21894 GNAT under Solaris comes with an alternate tasking run-time library
21895 based on POSIX threads --- @emph{rts-pthread}.
21896 @cindex rts-pthread threads library
21897 This run-time library has the advantage of being mostly shared across all
21898 POSIX-compliant thread implementations, and it also provides under
21899 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21900 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21901 and @code{PTHREAD_PRIO_PROTECT}
21902 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21903 semantics that can be selected using the predefined pragma
21904 @code{Locking_Policy}
21905 @cindex pragma Locking_Policy (under rts-pthread)
21906 with respectively
21907 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21908 @cindex @code{Inheritance_Locking} (under rts-pthread)
21909 @cindex @code{Ceiling_Locking} (under rts-pthread)
21910
21911 As explained above, the native run-time library is based on the Solaris thread
21912 library (@code{libthread}) and is the default library.
21913
21914 When the Solaris threads library is used (this is the default), programs
21915 compiled with GNAT can automatically take advantage of
21916 and can thus execute on multiple processors.
21917 The user can alternatively specify a processor on which the program should run
21918 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21919 is made by
21920 setting the environment variable @code{GNAT_PROCESSOR}
21921 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21922 to one of the following:
21923
21924 @table @code
21925 @item -2
21926 Use the default configuration (run the program on all
21927          available processors) - this is the same as having
21928          @code{GNAT_PROCESSOR} unset
21929
21930 @item -1
21931 Let the run-time implementation choose one processor and run the program on
21932          that processor
21933
21934 @item 0 .. Last_Proc
21935 Run the program on the specified processor.
21936   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21937 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21938 @end table
21939
21940 @node Building and Debugging 64-bit Applications
21941 @subsection Building and Debugging 64-bit Applications
21942
21943 @noindent
21944 In a 64-bit application, all the sources involved must be compiled with the
21945 @option{-m64} command-line option, and a specific GNAT library (compiled with
21946 this option) is required.
21947 The easiest way to build a 64bit application is to add
21948 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21949
21950 To debug these applications, a special version of gdb called @command{gdb64}
21951 needs to be used.
21952
21953 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21954 amounts to:
21955
21956 @smallexample
21957      $ gnatmake -m64 -g --RTS=m64 hello.adb
21958      $ gdb64 hello
21959 @end smallexample
21960
21961 In addition, the following capabilities are not supported when using the
21962 @option{-m64} option:
21963
21964 @table @code
21965 @item -fstack-check does not work together with -m64.
21966 Any application combining these options crashes at startup time.
21967
21968 @item Call-chain backtrace computation does not work with -m64.
21969 Thus the gnatbind switch -E is not supported.
21970 @end table
21971
21972 @node IRIX-Specific Considerations
21973 @section IRIX-Specific Considerations
21974 @cindex IRIX thread library
21975
21976 @noindent
21977 On SGI IRIX, the thread library depends on which compiler is used.
21978 The @emph{o32 ABI} compiler comes with a run-time library based on the
21979 user-level @code{athread}
21980 library. Thus kernel-level capabilities such as nonblocking system
21981 calls or time slicing can only be achieved reliably by specifying different
21982 @code{sprocs} via the pragma @code{Task_Info}
21983 @cindex pragma Task_Info (and IRIX threads)
21984 and the
21985 @code{System.Task_Info} package.
21986 @cindex @code{System.Task_Info} package (and IRIX threads)
21987 See the @cite{GNAT Reference Manual} for further information.
21988
21989 The @emph{n32 ABI} compiler comes with a run-time library based on the
21990 kernel POSIX threads and thus does not have the limitations mentioned above.
21991
21992 @node Linux-Specific Considerations
21993 @section Linux-Specific Considerations
21994 @cindex Linux threads libraries
21995
21996 @noindent
21997 The default thread library under GNU/Linux has the following disadvantages
21998 compared to other native thread libraries:
21999
22000 @itemize @bullet
22001 @item The size of the task's stack is limited to 2 megabytes.
22002 @item  The signal model is not POSIX compliant, which means that to send a
22003   signal to the process, you need to send the signal to all threads,
22004   e.g. by using @code{killpg()}.
22005 @end itemize
22006
22007 @node AIX-Specific Considerations
22008 @section AIX-Specific Considerations
22009 @cindex AIX resolver library
22010
22011 @noindent
22012 On AIX, the resolver library initializes some internal structure on
22013 the first call to @code{get*by*} functions, which are used to implement
22014 @code{GNAT.Sockets.Get_Host_By_Name} and
22015 @code{GNAT.Sockets.Get_Host_By_Addrss}.
22016 If such initialization occurs within an Ada task, and the stack size for
22017 the task is the default size, a stack overflow may occur.
22018
22019 To avoid this overflow, the user should either ensure that the first call
22020 to @code{GNAT.Sockets.Get_Host_By_Name} or
22021 @code{GNAT.Sockets.Get_Host_By_Addrss}
22022 occurs in the environment task, or use @code{pragma Storage_Size} to
22023 specify a sufficiently large size for the stack of the task that contains
22024 this call.
22025
22026 @c *******************************
22027 @node Example of Binder Output File
22028 @appendix Example of Binder Output File
22029
22030 @noindent
22031 This Appendix displays the source code for @command{gnatbind}'s output
22032 file generated for a simple ``Hello World'' program.
22033 Comments have been added for clarification purposes.
22034
22035 @smallexample @c adanocomment
22036 @iftex
22037 @leftskip=0cm
22038 @end iftex
22039 --  The package is called Ada_Main unless this name is actually used
22040 --  as a unit name in the partition, in which case some other unique
22041 --  name is used.
22042
22043 with System;
22044 package ada_main is
22045
22046    Elab_Final_Code : Integer;
22047    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22048
22049    --  The main program saves the parameters (argument count,
22050    --  argument values, environment pointer) in global variables
22051    --  for later access by other units including
22052    --  Ada.Command_Line.
22053
22054    gnat_argc : Integer;
22055    gnat_argv : System.Address;
22056    gnat_envp : System.Address;
22057
22058    --  The actual variables are stored in a library routine. This
22059    --  is useful for some shared library situations, where there
22060    --  are problems if variables are not in the library.
22061
22062    pragma Import (C, gnat_argc);
22063    pragma Import (C, gnat_argv);
22064    pragma Import (C, gnat_envp);
22065
22066    --  The exit status is similarly an external location
22067
22068    gnat_exit_status : Integer;
22069    pragma Import (C, gnat_exit_status);
22070
22071    GNAT_Version : constant String :=
22072                     "GNAT Version: 3.15w (20010315)";
22073    pragma Export (C, GNAT_Version, "__gnat_version");
22074
22075    --  This is the generated adafinal routine that performs
22076    --  finalization at the end of execution. In the case where
22077    --  Ada is the main program, this main program makes a call
22078    --  to adafinal at program termination.
22079
22080    procedure adafinal;
22081    pragma Export (C, adafinal, "adafinal");
22082
22083    --  This is the generated adainit routine that performs
22084    --  initialization at the start of execution. In the case
22085    --  where Ada is the main program, this main program makes
22086    --  a call to adainit at program startup.
22087
22088    procedure adainit;
22089    pragma Export (C, adainit, "adainit");
22090
22091    --  This routine is called at the start of execution. It is
22092    --  a dummy routine that is used by the debugger to breakpoint
22093    --  at the start of execution.
22094
22095    procedure Break_Start;
22096    pragma Import (C, Break_Start, "__gnat_break_start");
22097
22098    --  This is the actual generated main program (it would be
22099    --  suppressed if the no main program switch were used). As
22100    --  required by standard system conventions, this program has
22101    --  the external name main.
22102
22103    function main
22104      (argc : Integer;
22105       argv : System.Address;
22106       envp : System.Address)
22107       return Integer;
22108    pragma Export (C, main, "main");
22109
22110    --  The following set of constants give the version
22111    --  identification values for every unit in the bound
22112    --  partition. This identification is computed from all
22113    --  dependent semantic units, and corresponds to the
22114    --  string that would be returned by use of the
22115    --  Body_Version or Version attributes.
22116
22117    type Version_32 is mod 2 ** 32;
22118    u00001 : constant Version_32 := 16#7880BEB3#;
22119    u00002 : constant Version_32 := 16#0D24CBD0#;
22120    u00003 : constant Version_32 := 16#3283DBEB#;
22121    u00004 : constant Version_32 := 16#2359F9ED#;
22122    u00005 : constant Version_32 := 16#664FB847#;
22123    u00006 : constant Version_32 := 16#68E803DF#;
22124    u00007 : constant Version_32 := 16#5572E604#;
22125    u00008 : constant Version_32 := 16#46B173D8#;
22126    u00009 : constant Version_32 := 16#156A40CF#;
22127    u00010 : constant Version_32 := 16#033DABE0#;
22128    u00011 : constant Version_32 := 16#6AB38FEA#;
22129    u00012 : constant Version_32 := 16#22B6217D#;
22130    u00013 : constant Version_32 := 16#68A22947#;
22131    u00014 : constant Version_32 := 16#18CC4A56#;
22132    u00015 : constant Version_32 := 16#08258E1B#;
22133    u00016 : constant Version_32 := 16#367D5222#;
22134    u00017 : constant Version_32 := 16#20C9ECA4#;
22135    u00018 : constant Version_32 := 16#50D32CB6#;
22136    u00019 : constant Version_32 := 16#39A8BB77#;
22137    u00020 : constant Version_32 := 16#5CF8FA2B#;
22138    u00021 : constant Version_32 := 16#2F1EB794#;
22139    u00022 : constant Version_32 := 16#31AB6444#;
22140    u00023 : constant Version_32 := 16#1574B6E9#;
22141    u00024 : constant Version_32 := 16#5109C189#;
22142    u00025 : constant Version_32 := 16#56D770CD#;
22143    u00026 : constant Version_32 := 16#02F9DE3D#;
22144    u00027 : constant Version_32 := 16#08AB6B2C#;
22145    u00028 : constant Version_32 := 16#3FA37670#;
22146    u00029 : constant Version_32 := 16#476457A0#;
22147    u00030 : constant Version_32 := 16#731E1B6E#;
22148    u00031 : constant Version_32 := 16#23C2E789#;
22149    u00032 : constant Version_32 := 16#0F1BD6A1#;
22150    u00033 : constant Version_32 := 16#7C25DE96#;
22151    u00034 : constant Version_32 := 16#39ADFFA2#;
22152    u00035 : constant Version_32 := 16#571DE3E7#;
22153    u00036 : constant Version_32 := 16#5EB646AB#;
22154    u00037 : constant Version_32 := 16#4249379B#;
22155    u00038 : constant Version_32 := 16#0357E00A#;
22156    u00039 : constant Version_32 := 16#3784FB72#;
22157    u00040 : constant Version_32 := 16#2E723019#;
22158    u00041 : constant Version_32 := 16#623358EA#;
22159    u00042 : constant Version_32 := 16#107F9465#;
22160    u00043 : constant Version_32 := 16#6843F68A#;
22161    u00044 : constant Version_32 := 16#63305874#;
22162    u00045 : constant Version_32 := 16#31E56CE1#;
22163    u00046 : constant Version_32 := 16#02917970#;
22164    u00047 : constant Version_32 := 16#6CCBA70E#;
22165    u00048 : constant Version_32 := 16#41CD4204#;
22166    u00049 : constant Version_32 := 16#572E3F58#;
22167    u00050 : constant Version_32 := 16#20729FF5#;
22168    u00051 : constant Version_32 := 16#1D4F93E8#;
22169    u00052 : constant Version_32 := 16#30B2EC3D#;
22170    u00053 : constant Version_32 := 16#34054F96#;
22171    u00054 : constant Version_32 := 16#5A199860#;
22172    u00055 : constant Version_32 := 16#0E7F912B#;
22173    u00056 : constant Version_32 := 16#5760634A#;
22174    u00057 : constant Version_32 := 16#5D851835#;
22175
22176    --  The following Export pragmas export the version numbers
22177    --  with symbolic names ending in B (for body) or S
22178    --  (for spec) so that they can be located in a link. The
22179    --  information provided here is sufficient to track down
22180    --  the exact versions of units used in a given build.
22181
22182    pragma Export (C, u00001, "helloB");
22183    pragma Export (C, u00002, "system__standard_libraryB");
22184    pragma Export (C, u00003, "system__standard_libraryS");
22185    pragma Export (C, u00004, "adaS");
22186    pragma Export (C, u00005, "ada__text_ioB");
22187    pragma Export (C, u00006, "ada__text_ioS");
22188    pragma Export (C, u00007, "ada__exceptionsB");
22189    pragma Export (C, u00008, "ada__exceptionsS");
22190    pragma Export (C, u00009, "gnatS");
22191    pragma Export (C, u00010, "gnat__heap_sort_aB");
22192    pragma Export (C, u00011, "gnat__heap_sort_aS");
22193    pragma Export (C, u00012, "systemS");
22194    pragma Export (C, u00013, "system__exception_tableB");
22195    pragma Export (C, u00014, "system__exception_tableS");
22196    pragma Export (C, u00015, "gnat__htableB");
22197    pragma Export (C, u00016, "gnat__htableS");
22198    pragma Export (C, u00017, "system__exceptionsS");
22199    pragma Export (C, u00018, "system__machine_state_operationsB");
22200    pragma Export (C, u00019, "system__machine_state_operationsS");
22201    pragma Export (C, u00020, "system__machine_codeS");
22202    pragma Export (C, u00021, "system__storage_elementsB");
22203    pragma Export (C, u00022, "system__storage_elementsS");
22204    pragma Export (C, u00023, "system__secondary_stackB");
22205    pragma Export (C, u00024, "system__secondary_stackS");
22206    pragma Export (C, u00025, "system__parametersB");
22207    pragma Export (C, u00026, "system__parametersS");
22208    pragma Export (C, u00027, "system__soft_linksB");
22209    pragma Export (C, u00028, "system__soft_linksS");
22210    pragma Export (C, u00029, "system__stack_checkingB");
22211    pragma Export (C, u00030, "system__stack_checkingS");
22212    pragma Export (C, u00031, "system__tracebackB");
22213    pragma Export (C, u00032, "system__tracebackS");
22214    pragma Export (C, u00033, "ada__streamsS");
22215    pragma Export (C, u00034, "ada__tagsB");
22216    pragma Export (C, u00035, "ada__tagsS");
22217    pragma Export (C, u00036, "system__string_opsB");
22218    pragma Export (C, u00037, "system__string_opsS");
22219    pragma Export (C, u00038, "interfacesS");
22220    pragma Export (C, u00039, "interfaces__c_streamsB");
22221    pragma Export (C, u00040, "interfaces__c_streamsS");
22222    pragma Export (C, u00041, "system__file_ioB");
22223    pragma Export (C, u00042, "system__file_ioS");
22224    pragma Export (C, u00043, "ada__finalizationB");
22225    pragma Export (C, u00044, "ada__finalizationS");
22226    pragma Export (C, u00045, "system__finalization_rootB");
22227    pragma Export (C, u00046, "system__finalization_rootS");
22228    pragma Export (C, u00047, "system__finalization_implementationB");
22229    pragma Export (C, u00048, "system__finalization_implementationS");
22230    pragma Export (C, u00049, "system__string_ops_concat_3B");
22231    pragma Export (C, u00050, "system__string_ops_concat_3S");
22232    pragma Export (C, u00051, "system__stream_attributesB");
22233    pragma Export (C, u00052, "system__stream_attributesS");
22234    pragma Export (C, u00053, "ada__io_exceptionsS");
22235    pragma Export (C, u00054, "system__unsigned_typesS");
22236    pragma Export (C, u00055, "system__file_control_blockS");
22237    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22238    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22239
22240    -- BEGIN ELABORATION ORDER
22241    -- ada (spec)
22242    -- gnat (spec)
22243    -- gnat.heap_sort_a (spec)
22244    -- gnat.heap_sort_a (body)
22245    -- gnat.htable (spec)
22246    -- gnat.htable (body)
22247    -- interfaces (spec)
22248    -- system (spec)
22249    -- system.machine_code (spec)
22250    -- system.parameters (spec)
22251    -- system.parameters (body)
22252    -- interfaces.c_streams (spec)
22253    -- interfaces.c_streams (body)
22254    -- system.standard_library (spec)
22255    -- ada.exceptions (spec)
22256    -- system.exception_table (spec)
22257    -- system.exception_table (body)
22258    -- ada.io_exceptions (spec)
22259    -- system.exceptions (spec)
22260    -- system.storage_elements (spec)
22261    -- system.storage_elements (body)
22262    -- system.machine_state_operations (spec)
22263    -- system.machine_state_operations (body)
22264    -- system.secondary_stack (spec)
22265    -- system.stack_checking (spec)
22266    -- system.soft_links (spec)
22267    -- system.soft_links (body)
22268    -- system.stack_checking (body)
22269    -- system.secondary_stack (body)
22270    -- system.standard_library (body)
22271    -- system.string_ops (spec)
22272    -- system.string_ops (body)
22273    -- ada.tags (spec)
22274    -- ada.tags (body)
22275    -- ada.streams (spec)
22276    -- system.finalization_root (spec)
22277    -- system.finalization_root (body)
22278    -- system.string_ops_concat_3 (spec)
22279    -- system.string_ops_concat_3 (body)
22280    -- system.traceback (spec)
22281    -- system.traceback (body)
22282    -- ada.exceptions (body)
22283    -- system.unsigned_types (spec)
22284    -- system.stream_attributes (spec)
22285    -- system.stream_attributes (body)
22286    -- system.finalization_implementation (spec)
22287    -- system.finalization_implementation (body)
22288    -- ada.finalization (spec)
22289    -- ada.finalization (body)
22290    -- ada.finalization.list_controller (spec)
22291    -- ada.finalization.list_controller (body)
22292    -- system.file_control_block (spec)
22293    -- system.file_io (spec)
22294    -- system.file_io (body)
22295    -- ada.text_io (spec)
22296    -- ada.text_io (body)
22297    -- hello (body)
22298    -- END ELABORATION ORDER
22299
22300 end ada_main;
22301
22302 --  The following source file name pragmas allow the generated file
22303 --  names to be unique for different main programs. They are needed
22304 --  since the package name will always be Ada_Main.
22305
22306 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22307 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22308
22309 --  Generated package body for Ada_Main starts here
22310
22311 package body ada_main is
22312
22313    --  The actual finalization is performed by calling the
22314    --  library routine in System.Standard_Library.Adafinal
22315
22316    procedure Do_Finalize;
22317    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22318
22319    -------------
22320    -- adainit --
22321    -------------
22322
22323 @findex adainit
22324    procedure adainit is
22325
22326       --  These booleans are set to True once the associated unit has
22327       --  been elaborated. It is also used to avoid elaborating the
22328       --  same unit twice.
22329
22330       E040 : Boolean;
22331       pragma Import (Ada, E040, "interfaces__c_streams_E");
22332
22333       E008 : Boolean;
22334       pragma Import (Ada, E008, "ada__exceptions_E");
22335
22336       E014 : Boolean;
22337       pragma Import (Ada, E014, "system__exception_table_E");
22338
22339       E053 : Boolean;
22340       pragma Import (Ada, E053, "ada__io_exceptions_E");
22341
22342       E017 : Boolean;
22343       pragma Import (Ada, E017, "system__exceptions_E");
22344
22345       E024 : Boolean;
22346       pragma Import (Ada, E024, "system__secondary_stack_E");
22347
22348       E030 : Boolean;
22349       pragma Import (Ada, E030, "system__stack_checking_E");
22350
22351       E028 : Boolean;
22352       pragma Import (Ada, E028, "system__soft_links_E");
22353
22354       E035 : Boolean;
22355       pragma Import (Ada, E035, "ada__tags_E");
22356
22357       E033 : Boolean;
22358       pragma Import (Ada, E033, "ada__streams_E");
22359
22360       E046 : Boolean;
22361       pragma Import (Ada, E046, "system__finalization_root_E");
22362
22363       E048 : Boolean;
22364       pragma Import (Ada, E048, "system__finalization_implementation_E");
22365
22366       E044 : Boolean;
22367       pragma Import (Ada, E044, "ada__finalization_E");
22368
22369       E057 : Boolean;
22370       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22371
22372       E055 : Boolean;
22373       pragma Import (Ada, E055, "system__file_control_block_E");
22374
22375       E042 : Boolean;
22376       pragma Import (Ada, E042, "system__file_io_E");
22377
22378       E006 : Boolean;
22379       pragma Import (Ada, E006, "ada__text_io_E");
22380
22381       --  Set_Globals is a library routine that stores away the
22382       --  value of the indicated set of global values in global
22383       --  variables within the library.
22384
22385       procedure Set_Globals
22386         (Main_Priority            : Integer;
22387          Time_Slice_Value         : Integer;
22388          WC_Encoding              : Character;
22389          Locking_Policy           : Character;
22390          Queuing_Policy           : Character;
22391          Task_Dispatching_Policy  : Character;
22392          Adafinal                 : System.Address;
22393          Unreserve_All_Interrupts : Integer;
22394          Exception_Tracebacks     : Integer);
22395 @findex __gnat_set_globals
22396       pragma Import (C, Set_Globals, "__gnat_set_globals");
22397
22398       --  SDP_Table_Build is a library routine used to build the
22399       --  exception tables. See unit Ada.Exceptions in files
22400       --  a-except.ads/adb for full details of how zero cost
22401       --  exception handling works. This procedure, the call to
22402       --  it, and the two following tables are all omitted if the
22403       --  build is in longjmp/setjump exception mode.
22404
22405 @findex SDP_Table_Build
22406 @findex Zero Cost Exceptions
22407       procedure SDP_Table_Build
22408         (SDP_Addresses   : System.Address;
22409          SDP_Count       : Natural;
22410          Elab_Addresses  : System.Address;
22411          Elab_Addr_Count : Natural);
22412       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22413
22414       --  Table of Unit_Exception_Table addresses. Used for zero
22415       --  cost exception handling to build the top level table.
22416
22417       ST : aliased constant array (1 .. 23) of System.Address := (
22418         Hello'UET_Address,
22419         Ada.Text_Io'UET_Address,
22420         Ada.Exceptions'UET_Address,
22421         Gnat.Heap_Sort_A'UET_Address,
22422         System.Exception_Table'UET_Address,
22423         System.Machine_State_Operations'UET_Address,
22424         System.Secondary_Stack'UET_Address,
22425         System.Parameters'UET_Address,
22426         System.Soft_Links'UET_Address,
22427         System.Stack_Checking'UET_Address,
22428         System.Traceback'UET_Address,
22429         Ada.Streams'UET_Address,
22430         Ada.Tags'UET_Address,
22431         System.String_Ops'UET_Address,
22432         Interfaces.C_Streams'UET_Address,
22433         System.File_Io'UET_Address,
22434         Ada.Finalization'UET_Address,
22435         System.Finalization_Root'UET_Address,
22436         System.Finalization_Implementation'UET_Address,
22437         System.String_Ops_Concat_3'UET_Address,
22438         System.Stream_Attributes'UET_Address,
22439         System.File_Control_Block'UET_Address,
22440         Ada.Finalization.List_Controller'UET_Address);
22441
22442       --  Table of addresses of elaboration routines. Used for
22443       --  zero cost exception handling to make sure these
22444       --  addresses are included in the top level procedure
22445       --  address table.
22446
22447       EA : aliased constant array (1 .. 23) of System.Address := (
22448         adainit'Code_Address,
22449         Do_Finalize'Code_Address,
22450         Ada.Exceptions'Elab_Spec'Address,
22451         System.Exceptions'Elab_Spec'Address,
22452         Interfaces.C_Streams'Elab_Spec'Address,
22453         System.Exception_Table'Elab_Body'Address,
22454         Ada.Io_Exceptions'Elab_Spec'Address,
22455         System.Stack_Checking'Elab_Spec'Address,
22456         System.Soft_Links'Elab_Body'Address,
22457         System.Secondary_Stack'Elab_Body'Address,
22458         Ada.Tags'Elab_Spec'Address,
22459         Ada.Tags'Elab_Body'Address,
22460         Ada.Streams'Elab_Spec'Address,
22461         System.Finalization_Root'Elab_Spec'Address,
22462         Ada.Exceptions'Elab_Body'Address,
22463         System.Finalization_Implementation'Elab_Spec'Address,
22464         System.Finalization_Implementation'Elab_Body'Address,
22465         Ada.Finalization'Elab_Spec'Address,
22466         Ada.Finalization.List_Controller'Elab_Spec'Address,
22467         System.File_Control_Block'Elab_Spec'Address,
22468         System.File_Io'Elab_Body'Address,
22469         Ada.Text_Io'Elab_Spec'Address,
22470         Ada.Text_Io'Elab_Body'Address);
22471
22472    --  Start of processing for adainit
22473
22474    begin
22475
22476       --  Call SDP_Table_Build to build the top level procedure
22477       --  table for zero cost exception handling (omitted in
22478       --  longjmp/setjump mode).
22479
22480       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22481
22482       --  Call Set_Globals to record various information for
22483       --  this partition.  The values are derived by the binder
22484       --  from information stored in the ali files by the compiler.
22485
22486 @findex __gnat_set_globals
22487       Set_Globals
22488         (Main_Priority            => -1,
22489          --  Priority of main program, -1 if no pragma Priority used
22490
22491          Time_Slice_Value         => -1,
22492          --  Time slice from Time_Slice pragma, -1 if none used
22493
22494          WC_Encoding              => 'b',
22495          --  Wide_Character encoding used, default is brackets
22496
22497          Locking_Policy           => ' ',
22498          --  Locking_Policy used, default of space means not
22499          --  specified, otherwise it is the first character of
22500          --  the policy name.
22501
22502          Queuing_Policy           => ' ',
22503          --  Queuing_Policy used, default of space means not
22504          --  specified, otherwise it is the first character of
22505          --  the policy name.
22506
22507          Task_Dispatching_Policy  => ' ',
22508          --  Task_Dispatching_Policy used, default of space means
22509          --  not specified, otherwise first character of the
22510          --  policy name.
22511
22512          Adafinal                 => System.Null_Address,
22513          --  Address of Adafinal routine, not used anymore
22514
22515          Unreserve_All_Interrupts => 0,
22516          --  Set true if pragma Unreserve_All_Interrupts was used
22517
22518          Exception_Tracebacks     => 0);
22519          --  Indicates if exception tracebacks are enabled
22520
22521       Elab_Final_Code := 1;
22522
22523       --  Now we have the elaboration calls for all units in the partition.
22524       --  The Elab_Spec and Elab_Body attributes generate references to the
22525       --  implicit elaboration procedures generated by the compiler for
22526       --  each unit that requires elaboration.
22527
22528       if not E040 then
22529          Interfaces.C_Streams'Elab_Spec;
22530       end if;
22531       E040 := True;
22532       if not E008 then
22533          Ada.Exceptions'Elab_Spec;
22534       end if;
22535       if not E014 then
22536          System.Exception_Table'Elab_Body;
22537          E014 := True;
22538       end if;
22539       if not E053 then
22540          Ada.Io_Exceptions'Elab_Spec;
22541          E053 := True;
22542       end if;
22543       if not E017 then
22544          System.Exceptions'Elab_Spec;
22545          E017 := True;
22546       end if;
22547       if not E030 then
22548          System.Stack_Checking'Elab_Spec;
22549       end if;
22550       if not E028 then
22551          System.Soft_Links'Elab_Body;
22552          E028 := True;
22553       end if;
22554       E030 := True;
22555       if not E024 then
22556          System.Secondary_Stack'Elab_Body;
22557          E024 := True;
22558       end if;
22559       if not E035 then
22560          Ada.Tags'Elab_Spec;
22561       end if;
22562       if not E035 then
22563          Ada.Tags'Elab_Body;
22564          E035 := True;
22565       end if;
22566       if not E033 then
22567          Ada.Streams'Elab_Spec;
22568          E033 := True;
22569       end if;
22570       if not E046 then
22571          System.Finalization_Root'Elab_Spec;
22572       end if;
22573       E046 := True;
22574       if not E008 then
22575          Ada.Exceptions'Elab_Body;
22576          E008 := True;
22577       end if;
22578       if not E048 then
22579          System.Finalization_Implementation'Elab_Spec;
22580       end if;
22581       if not E048 then
22582          System.Finalization_Implementation'Elab_Body;
22583          E048 := True;
22584       end if;
22585       if not E044 then
22586          Ada.Finalization'Elab_Spec;
22587       end if;
22588       E044 := True;
22589       if not E057 then
22590          Ada.Finalization.List_Controller'Elab_Spec;
22591       end if;
22592       E057 := True;
22593       if not E055 then
22594          System.File_Control_Block'Elab_Spec;
22595          E055 := True;
22596       end if;
22597       if not E042 then
22598          System.File_Io'Elab_Body;
22599          E042 := True;
22600       end if;
22601       if not E006 then
22602          Ada.Text_Io'Elab_Spec;
22603       end if;
22604       if not E006 then
22605          Ada.Text_Io'Elab_Body;
22606          E006 := True;
22607       end if;
22608
22609       Elab_Final_Code := 0;
22610    end adainit;
22611
22612    --------------
22613    -- adafinal --
22614    --------------
22615
22616 @findex adafinal
22617    procedure adafinal is
22618    begin
22619       Do_Finalize;
22620    end adafinal;
22621
22622    ----------
22623    -- main --
22624    ----------
22625
22626    --  main is actually a function, as in the ANSI C standard,
22627    --  defined to return the exit status. The three parameters
22628    --  are the argument count, argument values and environment
22629    --  pointer.
22630
22631 @findex Main Program
22632    function main
22633      (argc : Integer;
22634       argv : System.Address;
22635       envp : System.Address)
22636       return Integer
22637    is
22638       --  The initialize routine performs low level system
22639       --  initialization using a standard library routine which
22640       --  sets up signal handling and performs any other
22641       --  required setup. The routine can be found in file
22642       --  a-init.c.
22643
22644 @findex __gnat_initialize
22645       procedure initialize;
22646       pragma Import (C, initialize, "__gnat_initialize");
22647
22648       --  The finalize routine performs low level system
22649       --  finalization using a standard library routine. The
22650       --  routine is found in file a-final.c and in the standard
22651       --  distribution is a dummy routine that does nothing, so
22652       --  really this is a hook for special user finalization.
22653
22654 @findex __gnat_finalize
22655       procedure finalize;
22656       pragma Import (C, finalize, "__gnat_finalize");
22657
22658       --  We get to the main program of the partition by using
22659       --  pragma Import because if we try to with the unit and
22660       --  call it Ada style, then not only do we waste time
22661       --  recompiling it, but also, we don't really know the right
22662       --  switches (e.g. identifier character set) to be used
22663       --  to compile it.
22664
22665       procedure Ada_Main_Program;
22666       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22667
22668    --  Start of processing for main
22669
22670    begin
22671       --  Save global variables
22672
22673       gnat_argc := argc;
22674       gnat_argv := argv;
22675       gnat_envp := envp;
22676
22677       --  Call low level system initialization
22678
22679       Initialize;
22680
22681       --  Call our generated Ada initialization routine
22682
22683       adainit;
22684
22685       --  This is the point at which we want the debugger to get
22686       --  control
22687
22688       Break_Start;
22689
22690       --  Now we call the main program of the partition
22691
22692       Ada_Main_Program;
22693
22694       --  Perform Ada finalization
22695
22696       adafinal;
22697
22698       --  Perform low level system finalization
22699
22700       Finalize;
22701
22702       --  Return the proper exit status
22703       return (gnat_exit_status);
22704    end;
22705
22706 --  This section is entirely comments, so it has no effect on the
22707 --  compilation of the Ada_Main package. It provides the list of
22708 --  object files and linker options, as well as some standard
22709 --  libraries needed for the link. The gnatlink utility parses
22710 --  this b~hello.adb file to read these comment lines to generate
22711 --  the appropriate command line arguments for the call to the
22712 --  system linker. The BEGIN/END lines are used for sentinels for
22713 --  this parsing operation.
22714
22715 --  The exact file names will of course depend on the environment,
22716 --  host/target and location of files on the host system.
22717
22718 @findex Object file list
22719 -- BEGIN Object file/option list
22720    --   ./hello.o
22721    --   -L./
22722    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22723    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22724 -- END Object file/option list
22725
22726 end ada_main;
22727 @end smallexample
22728
22729 @noindent
22730 The Ada code in the above example is exactly what is generated by the
22731 binder. We have added comments to more clearly indicate the function
22732 of each part of the generated @code{Ada_Main} package.
22733
22734 The code is standard Ada in all respects, and can be processed by any
22735 tools that handle Ada. In particular, it is possible to use the debugger
22736 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22737 suppose that for reasons that you do not understand, your program is crashing
22738 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22739 you can place a breakpoint on the call:
22740
22741 @smallexample @c ada
22742 Ada.Text_Io'Elab_Body;
22743 @end smallexample
22744
22745 @noindent
22746 and trace the elaboration routine for this package to find out where
22747 the problem might be (more usually of course you would be debugging
22748 elaboration code in your own application).
22749
22750 @node Elaboration Order Handling in GNAT
22751 @appendix Elaboration Order Handling in GNAT
22752 @cindex Order of elaboration
22753 @cindex Elaboration control
22754
22755 @menu
22756 * Elaboration Code in Ada 95::
22757 * Checking the Elaboration Order in Ada 95::
22758 * Controlling the Elaboration Order in Ada 95::
22759 * Controlling Elaboration in GNAT - Internal Calls::
22760 * Controlling Elaboration in GNAT - External Calls::
22761 * Default Behavior in GNAT - Ensuring Safety::
22762 * Treatment of Pragma Elaborate::
22763 * Elaboration Issues for Library Tasks::
22764 * Mixing Elaboration Models::
22765 * What to Do If the Default Elaboration Behavior Fails::
22766 * Elaboration for Access-to-Subprogram Values::
22767 * Summary of Procedures for Elaboration Control::
22768 * Other Elaboration Order Considerations::
22769 @end menu
22770
22771 @noindent
22772 This chapter describes the handling of elaboration code in Ada 95 and
22773 in GNAT, and discusses how the order of elaboration of program units can
22774 be controlled in GNAT, either automatically or with explicit programming
22775 features.
22776
22777 @node Elaboration Code in Ada 95
22778 @section Elaboration Code in Ada 95
22779
22780 @noindent
22781 Ada 95 provides rather general mechanisms for executing code at elaboration
22782 time, that is to say before the main program starts executing. Such code arises
22783 in three contexts:
22784
22785 @table @asis
22786 @item Initializers for variables.
22787 Variables declared at the library level, in package specs or bodies, can
22788 require initialization that is performed at elaboration time, as in:
22789 @smallexample @c ada
22790 @cartouche
22791 Sqrt_Half : Float := Sqrt (0.5);
22792 @end cartouche
22793 @end smallexample
22794
22795 @item Package initialization code
22796 Code in a @code{BEGIN-END} section at the outer level of a package body is
22797 executed as part of the package body elaboration code.
22798
22799 @item Library level task allocators
22800 Tasks that are declared using task allocators at the library level
22801 start executing immediately and hence can execute at elaboration time.
22802 @end table
22803
22804 @noindent
22805 Subprogram calls are possible in any of these contexts, which means that
22806 any arbitrary part of the program may be executed as part of the elaboration
22807 code. It is even possible to write a program which does all its work at
22808 elaboration time, with a null main program, although stylistically this
22809 would usually be considered an inappropriate way to structure
22810 a program.
22811
22812 An important concern arises in the context of elaboration code:
22813 we have to be sure that it is executed in an appropriate order. What we
22814 have is a series of elaboration code sections, potentially one section
22815 for each unit in the program. It is important that these execute
22816 in the correct order. Correctness here means that, taking the above
22817 example of the declaration of @code{Sqrt_Half},
22818 if some other piece of
22819 elaboration code references @code{Sqrt_Half},
22820 then it must run after the
22821 section of elaboration code that contains the declaration of
22822 @code{Sqrt_Half}.
22823
22824 There would never be any order of elaboration problem if we made a rule
22825 that whenever you @code{with} a unit, you must elaborate both the spec and body
22826 of that unit before elaborating the unit doing the @code{with}'ing:
22827
22828 @smallexample @c ada
22829 @group
22830 @cartouche
22831 with Unit_1;
22832 package Unit_2 is ...
22833 @end cartouche
22834 @end group
22835 @end smallexample
22836
22837 @noindent
22838 would require that both the body and spec of @code{Unit_1} be elaborated
22839 before the spec of @code{Unit_2}. However, a rule like that would be far too
22840 restrictive. In particular, it would make it impossible to have routines
22841 in separate packages that were mutually recursive.
22842
22843 You might think that a clever enough compiler could look at the actual
22844 elaboration code and determine an appropriate correct order of elaboration,
22845 but in the general case, this is not possible. Consider the following
22846 example.
22847
22848 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22849 that references
22850 the variable @code{Sqrt_1}, which is declared in the elaboration code
22851 of the body of @code{Unit_1}:
22852
22853 @smallexample @c ada
22854 @cartouche
22855 Sqrt_1 : Float := Sqrt (0.1);
22856 @end cartouche
22857 @end smallexample
22858
22859 @noindent
22860 The elaboration code of the body of @code{Unit_1} also contains:
22861
22862 @smallexample @c ada
22863 @group
22864 @cartouche
22865 if expression_1 = 1 then
22866    Q := Unit_2.Func_2;
22867 end if;
22868 @end cartouche
22869 @end group
22870 @end smallexample
22871
22872 @noindent
22873 @code{Unit_2} is exactly parallel,
22874 it has a procedure @code{Func_2} that references
22875 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22876 the body @code{Unit_2}:
22877
22878 @smallexample @c ada
22879 @cartouche
22880 Sqrt_2 : Float := Sqrt (0.1);
22881 @end cartouche
22882 @end smallexample
22883
22884 @noindent
22885 The elaboration code of the body of @code{Unit_2} also contains:
22886
22887 @smallexample @c ada
22888 @group
22889 @cartouche
22890 if expression_2 = 2 then
22891    Q := Unit_1.Func_1;
22892 end if;
22893 @end cartouche
22894 @end group
22895 @end smallexample
22896
22897 @noindent
22898 Now the question is, which of the following orders of elaboration is
22899 acceptable:
22900
22901 @smallexample
22902 @group
22903 Spec of Unit_1
22904 Spec of Unit_2
22905 Body of Unit_1
22906 Body of Unit_2
22907 @end group
22908 @end smallexample
22909
22910 @noindent
22911 or
22912
22913 @smallexample
22914 @group
22915 Spec of Unit_2
22916 Spec of Unit_1
22917 Body of Unit_2
22918 Body of Unit_1
22919 @end group
22920 @end smallexample
22921
22922 @noindent
22923 If you carefully analyze the flow here, you will see that you cannot tell
22924 at compile time the answer to this question.
22925 If @code{expression_1} is not equal to 1,
22926 and @code{expression_2} is not equal to 2,
22927 then either order is acceptable, because neither of the function calls is
22928 executed. If both tests evaluate to true, then neither order is acceptable
22929 and in fact there is no correct order.
22930
22931 If one of the two expressions is true, and the other is false, then one
22932 of the above orders is correct, and the other is incorrect. For example,
22933 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22934 then the call to @code{Func_2}
22935 will occur, but not the call to @code{Func_1.}
22936 This means that it is essential
22937 to elaborate the body of @code{Unit_1} before
22938 the body of @code{Unit_2}, so the first
22939 order of elaboration is correct and the second is wrong.
22940
22941 By making @code{expression_1} and @code{expression_2}
22942 depend on input data, or perhaps
22943 the time of day, we can make it impossible for the compiler or binder
22944 to figure out which of these expressions will be true, and hence it
22945 is impossible to guarantee a safe order of elaboration at run time.
22946
22947 @node Checking the Elaboration Order in Ada 95
22948 @section Checking the Elaboration Order in Ada 95
22949
22950 @noindent
22951 In some languages that involve the same kind of elaboration problems,
22952 e.g. Java and C++, the programmer is expected to worry about these
22953 ordering problems himself, and it is common to
22954 write a program in which an incorrect elaboration order  gives
22955 surprising results, because it references variables before they
22956 are initialized.
22957 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22958 clearly not sufficient. Consequently, the language provides three lines
22959 of defense:
22960
22961 @table @asis
22962 @item Standard rules
22963 Some standard rules restrict the possible choice of elaboration
22964 order. In particular, if you @code{with} a unit, then its spec is always
22965 elaborated before the unit doing the @code{with}. Similarly, a parent
22966 spec is always elaborated before the child spec, and finally
22967 a spec is always elaborated before its corresponding body.
22968
22969 @item Dynamic elaboration checks
22970 @cindex Elaboration checks
22971 @cindex Checks, elaboration
22972 Dynamic checks are made at run time, so that if some entity is accessed
22973 before it is elaborated (typically  by means of a subprogram call)
22974 then the exception (@code{Program_Error}) is raised.
22975
22976 @item Elaboration control
22977 Facilities are provided for the programmer to specify the desired order
22978 of elaboration.
22979 @end table
22980
22981 Let's look at these facilities in more detail. First, the rules for
22982 dynamic checking. One possible rule would be simply to say that the
22983 exception is raised if you access a variable which has not yet been
22984 elaborated. The trouble with this approach is that it could require
22985 expensive checks on every variable reference. Instead Ada 95 has two
22986 rules which are a little more restrictive, but easier to check, and
22987 easier to state:
22988
22989 @table @asis
22990 @item Restrictions on calls
22991 A subprogram can only be called at elaboration time if its body
22992 has been elaborated. The rules for elaboration given above guarantee
22993 that the spec of the subprogram has been elaborated before the
22994 call, but not the body. If this rule is violated, then the
22995 exception @code{Program_Error} is raised.
22996
22997 @item Restrictions on instantiations
22998 A generic unit can only be instantiated if the body of the generic
22999 unit has been elaborated. Again, the rules for elaboration given above
23000 guarantee that the spec of the generic unit has been elaborated
23001 before the instantiation, but not the body. If this rule is
23002 violated, then the exception @code{Program_Error} is raised.
23003 @end table
23004
23005 @noindent
23006 The idea is that if the body has been elaborated, then any variables
23007 it references must have been elaborated; by checking for the body being
23008 elaborated we guarantee that none of its references causes any
23009 trouble. As we noted above, this is a little too restrictive, because a
23010 subprogram that has no non-local references in its body may in fact be safe
23011 to call. However, it really would be unsafe to rely on this, because
23012 it would mean that the caller was aware of details of the implementation
23013 in the body. This goes against the basic tenets of Ada.
23014
23015 A plausible implementation can be described as follows.
23016 A Boolean variable is associated with each subprogram
23017 and each generic unit. This variable is initialized to False, and is set to
23018 True at the point body is elaborated. Every call or instantiation checks the
23019 variable, and raises @code{Program_Error} if the variable is False.
23020
23021 Note that one might think that it would be good enough to have one Boolean
23022 variable for each package, but that would not deal with cases of trying
23023 to call a body in the same package as the call
23024 that has not been elaborated yet.
23025 Of course a compiler may be able to do enough analysis to optimize away
23026 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23027 does such optimizations, but still the easiest conceptual model is to
23028 think of there being one variable per subprogram.
23029
23030 @node Controlling the Elaboration Order in Ada 95
23031 @section Controlling the Elaboration Order in Ada 95
23032
23033 @noindent
23034 In the previous section we discussed the rules in Ada 95 which ensure
23035 that @code{Program_Error} is raised if an incorrect elaboration order is
23036 chosen. This prevents erroneous executions, but we need mechanisms to
23037 specify a correct execution and avoid the exception altogether.
23038 To achieve this, Ada 95 provides a number of features for controlling
23039 the order of elaboration. We discuss these features in this section.
23040
23041 First, there are several ways of indicating to the compiler that a given
23042 unit has no elaboration problems:
23043
23044 @table @asis
23045 @item packages that do not require a body
23046 In Ada 95, a library package that does not require a body does not permit
23047 a body. This means that if we have a such a package, as in:
23048
23049 @smallexample @c ada
23050 @group
23051 @cartouche
23052 package Definitions is
23053    generic
23054       type m is new integer;
23055    package Subp is
23056       type a is array (1 .. 10) of m;
23057       type b is array (1 .. 20) of m;
23058    end Subp;
23059 end Definitions;
23060 @end cartouche
23061 @end group
23062 @end smallexample
23063
23064 @noindent
23065 A package that @code{with}'s @code{Definitions} may safely instantiate
23066 @code{Definitions.Subp} because the compiler can determine that there
23067 definitely is no package body to worry about in this case
23068
23069 @item pragma Pure
23070 @cindex pragma Pure
23071 @findex Pure
23072 Places sufficient restrictions on a unit to guarantee that
23073 no call to any subprogram in the unit can result in an
23074 elaboration problem. This means that the compiler does not need
23075 to worry about the point of elaboration of such units, and in
23076 particular, does not need to check any calls to any subprograms
23077 in this unit.
23078
23079 @item pragma Preelaborate
23080 @findex Preelaborate
23081 @cindex pragma Preelaborate
23082 This pragma places slightly less stringent restrictions on a unit than
23083 does pragma Pure,
23084 but these restrictions are still sufficient to ensure that there
23085 are no elaboration problems with any calls to the unit.
23086
23087 @item pragma Elaborate_Body
23088 @findex Elaborate_Body
23089 @cindex pragma Elaborate_Body
23090 This pragma requires that the body of a unit be elaborated immediately
23091 after its spec. Suppose a unit @code{A} has such a pragma,
23092 and unit @code{B} does
23093 a @code{with} of unit @code{A}. Recall that the standard rules require
23094 the spec of unit @code{A}
23095 to be elaborated before the @code{with}'ing unit; given the pragma in
23096 @code{A}, we also know that the body of @code{A}
23097 will be elaborated before @code{B}, so
23098 that calls to @code{A} are safe and do not need a check.
23099 @end table
23100
23101 @noindent
23102 Note that,
23103 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23104 the use of
23105 @code{Elaborate_Body} does not guarantee that the program is
23106 free of elaboration problems, because it may not be possible
23107 to satisfy the requested elaboration order.
23108 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23109 If a programmer
23110 marks @code{Unit_1} as @code{Elaborate_Body},
23111 and not @code{Unit_2,} then the order of
23112 elaboration will be:
23113
23114 @smallexample
23115 @group
23116 Spec of Unit_2
23117 Spec of Unit_1
23118 Body of Unit_1
23119 Body of Unit_2
23120 @end group
23121 @end smallexample
23122
23123 @noindent
23124 Now that means that the call to @code{Func_1} in @code{Unit_2}
23125 need not be checked,
23126 it must be safe. But the call to @code{Func_2} in
23127 @code{Unit_1} may still fail if
23128 @code{Expression_1} is equal to 1,
23129 and the programmer must still take
23130 responsibility for this not being the case.
23131
23132 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23133 eliminated, except for calls entirely within a body, which are
23134 in any case fully under programmer control. However, using the pragma
23135 everywhere is not always possible.
23136 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23137 we marked both of them as having pragma @code{Elaborate_Body}, then
23138 clearly there would be no possible elaboration order.
23139
23140 The above pragmas allow a server to guarantee safe use by clients, and
23141 clearly this is the preferable approach. Consequently a good rule in
23142 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23143 and if this is not possible,
23144 mark them as @code{Elaborate_Body} if possible.
23145 As we have seen, there are situations where neither of these
23146 three pragmas can be used.
23147 So we also provide methods for clients to control the
23148 order of elaboration of the servers on which they depend:
23149
23150 @table @asis
23151 @item pragma Elaborate (unit)
23152 @findex Elaborate
23153 @cindex pragma Elaborate
23154 This pragma is placed in the context clause, after a @code{with} clause,
23155 and it requires that the body of the named unit be elaborated before
23156 the unit in which the pragma occurs. The idea is to use this pragma
23157 if the current unit calls at elaboration time, directly or indirectly,
23158 some subprogram in the named unit.
23159
23160 @item pragma Elaborate_All (unit)
23161 @findex Elaborate_All
23162 @cindex pragma Elaborate_All
23163 This is a stronger version of the Elaborate pragma. Consider the
23164 following example:
23165
23166 @smallexample
23167 Unit A @code{with}'s unit B and calls B.Func in elab code
23168 Unit B @code{with}'s unit C, and B.Func calls C.Func
23169 @end smallexample
23170
23171 @noindent
23172 Now if we put a pragma @code{Elaborate (B)}
23173 in unit @code{A}, this ensures that the
23174 body of @code{B} is elaborated before the call, but not the
23175 body of @code{C}, so
23176 the call to @code{C.Func} could still cause @code{Program_Error} to
23177 be raised.
23178
23179 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23180 not only that the body of the named unit be elaborated before the
23181 unit doing the @code{with}, but also the bodies of all units that the
23182 named unit uses, following @code{with} links transitively. For example,
23183 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23184 then it requires
23185 not only that the body of @code{B} be elaborated before @code{A},
23186 but also the
23187 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23188 @end table
23189
23190 @noindent
23191 We are now in a position to give a usage rule in Ada 95 for avoiding
23192 elaboration problems, at least if dynamic dispatching and access to
23193 subprogram values are not used. We will handle these cases separately
23194 later.
23195
23196 The rule is simple. If a unit has elaboration code that can directly or
23197 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23198 a generic unit in a @code{with}'ed unit,
23199 then if the @code{with}'ed unit does not have
23200 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23201 a pragma @code{Elaborate_All}
23202 for the @code{with}'ed unit. By following this rule a client is
23203 assured that calls can be made without risk of an exception.
23204 If this rule is not followed, then a program may be in one of four
23205 states:
23206
23207 @table @asis
23208 @item No order exists
23209 No order of elaboration exists which follows the rules, taking into
23210 account any @code{Elaborate}, @code{Elaborate_All},
23211 or @code{Elaborate_Body} pragmas. In
23212 this case, an Ada 95 compiler must diagnose the situation at bind
23213 time, and refuse to build an executable program.
23214
23215 @item One or more orders exist, all incorrect
23216 One or more acceptable elaboration orders exists, and all of them
23217 generate an elaboration order problem. In this case, the binder
23218 can build an executable program, but @code{Program_Error} will be raised
23219 when the program is run.
23220
23221 @item Several orders exist, some right, some incorrect
23222 One or more acceptable elaboration orders exists, and some of them
23223 work, and some do not. The programmer has not controlled
23224 the order of elaboration, so the binder may or may not pick one of
23225 the correct orders, and the program may or may not raise an
23226 exception when it is run. This is the worst case, because it means
23227 that the program may fail when moved to another compiler, or even
23228 another version of the same compiler.
23229
23230 @item One or more orders exists, all correct
23231 One ore more acceptable elaboration orders exist, and all of them
23232 work. In this case the program runs successfully. This state of
23233 affairs can be guaranteed by following the rule we gave above, but
23234 may be true even if the rule is not followed.
23235 @end table
23236
23237 @noindent
23238 Note that one additional advantage of following our Elaborate_All rule
23239 is that the program continues to stay in the ideal (all orders OK) state
23240 even if maintenance
23241 changes some bodies of some subprograms. Conversely, if a program that does
23242 not follow this rule happens to be safe at some point, this state of affairs
23243 may deteriorate silently as a result of maintenance changes.
23244
23245 You may have noticed that the above discussion did not mention
23246 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23247 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23248 code in the body makes calls to some other unit, so it is still necessary
23249 to use @code{Elaborate_All} on such units.
23250
23251 @node Controlling Elaboration in GNAT - Internal Calls
23252 @section Controlling Elaboration in GNAT - Internal Calls
23253
23254 @noindent
23255 In the case of internal calls, i.e. calls within a single package, the
23256 programmer has full control over the order of elaboration, and it is up
23257 to the programmer to elaborate declarations in an appropriate order. For
23258 example writing:
23259
23260 @smallexample @c ada
23261 @group
23262 @cartouche
23263 function One return Float;
23264
23265 Q : Float := One;
23266
23267 function One return Float is
23268 begin
23269      return 1.0;
23270 end One;
23271 @end cartouche
23272 @end group
23273 @end smallexample
23274
23275 @noindent
23276 will obviously raise @code{Program_Error} at run time, because function
23277 One will be called before its body is elaborated. In this case GNAT will
23278 generate a warning that the call will raise @code{Program_Error}:
23279
23280 @smallexample
23281 @group
23282 @cartouche
23283  1. procedure y is
23284  2.    function One return Float;
23285  3.
23286  4.    Q : Float := One;
23287                     |
23288     >>> warning: cannot call "One" before body is elaborated
23289     >>> warning: Program_Error will be raised at run time
23290
23291  5.
23292  6.    function One return Float is
23293  7.    begin
23294  8.         return 1.0;
23295  9.    end One;
23296 10.
23297 11. begin
23298 12.    null;
23299 13. end;
23300 @end cartouche
23301 @end group
23302 @end smallexample
23303
23304 @noindent
23305 Note that in this particular case, it is likely that the call is safe, because
23306 the function @code{One} does not access any global variables.
23307 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23308 the contents of the body (think about the separate compilation case), so this
23309 is still wrong, as we discussed in the previous sections.
23310
23311 The error is easily corrected by rearranging the declarations so that the
23312 body of One appears before the declaration containing the call
23313 (note that in Ada 95,
23314 declarations can appear in any order, so there is no restriction that
23315 would prevent this reordering, and if we write:
23316
23317 @smallexample @c ada
23318 @group
23319 @cartouche
23320 function One return Float;
23321
23322 function One return Float is
23323 begin
23324      return 1.0;
23325 end One;
23326
23327 Q : Float := One;
23328 @end cartouche
23329 @end group
23330 @end smallexample
23331
23332 @noindent
23333 then all is well, no warning is generated, and no
23334 @code{Program_Error} exception
23335 will be raised.
23336 Things are more complicated when a chain of subprograms is executed:
23337
23338 @smallexample @c ada
23339 @group
23340 @cartouche
23341 function A return Integer;
23342 function B return Integer;
23343 function C return Integer;
23344
23345 function B return Integer is begin return A; end;
23346 function C return Integer is begin return B; end;
23347
23348 X : Integer := C;
23349
23350 function A return Integer is begin return 1; end;
23351 @end cartouche
23352 @end group
23353 @end smallexample
23354
23355 @noindent
23356 Now the call to @code{C}
23357 at elaboration time in the declaration of @code{X} is correct, because
23358 the body of @code{C} is already elaborated,
23359 and the call to @code{B} within the body of
23360 @code{C} is correct, but the call
23361 to @code{A} within the body of @code{B} is incorrect, because the body
23362 of @code{A} has not been elaborated, so @code{Program_Error}
23363 will be raised on the call to @code{A}.
23364 In this case GNAT will generate a
23365 warning that @code{Program_Error} may be
23366 raised at the point of the call. Let's look at the warning:
23367
23368 @smallexample
23369 @group
23370 @cartouche
23371  1. procedure x is
23372  2.    function A return Integer;
23373  3.    function B return Integer;
23374  4.    function C return Integer;
23375  5.
23376  6.    function B return Integer is begin return A; end;
23377                                                     |
23378     >>> warning: call to "A" before body is elaborated may
23379                  raise Program_Error
23380     >>> warning: "B" called at line 7
23381     >>> warning: "C" called at line 9
23382
23383  7.    function C return Integer is begin return B; end;
23384  8.
23385  9.    X : Integer := C;
23386 10.
23387 11.    function A return Integer is begin return 1; end;
23388 12.
23389 13. begin
23390 14.    null;
23391 15. end;
23392 @end cartouche
23393 @end group
23394 @end smallexample
23395
23396 @noindent
23397 Note that the message here says ``may raise'', instead of the direct case,
23398 where the message says ``will be raised''. That's because whether
23399 @code{A} is
23400 actually called depends in general on run-time flow of control.
23401 For example, if the body of @code{B} said
23402
23403 @smallexample @c ada
23404 @group
23405 @cartouche
23406 function B return Integer is
23407 begin
23408    if some-condition-depending-on-input-data then
23409       return A;
23410    else
23411       return 1;
23412    end if;
23413 end B;
23414 @end cartouche
23415 @end group
23416 @end smallexample
23417
23418 @noindent
23419 then we could not know until run time whether the incorrect call to A would
23420 actually occur, so @code{Program_Error} might
23421 or might not be raised. It is possible for a compiler to
23422 do a better job of analyzing bodies, to
23423 determine whether or not @code{Program_Error}
23424 might be raised, but it certainly
23425 couldn't do a perfect job (that would require solving the halting problem
23426 and is provably impossible), and because this is a warning anyway, it does
23427 not seem worth the effort to do the analysis. Cases in which it
23428 would be relevant are rare.
23429
23430 In practice, warnings of either of the forms given
23431 above will usually correspond to
23432 real errors, and should be examined carefully and eliminated.
23433 In the rare case where a warning is bogus, it can be suppressed by any of
23434 the following methods:
23435
23436 @itemize @bullet
23437 @item
23438 Compile with the @option{-gnatws} switch set
23439
23440 @item
23441 Suppress @code{Elaboration_Check} for the called subprogram
23442
23443 @item
23444 Use pragma @code{Warnings_Off} to turn warnings off for the call
23445 @end itemize
23446
23447 @noindent
23448 For the internal elaboration check case,
23449 GNAT by default generates the
23450 necessary run-time checks to ensure
23451 that @code{Program_Error} is raised if any
23452 call fails an elaboration check. Of course this can only happen if a
23453 warning has been issued as described above. The use of pragma
23454 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23455 some of these checks, meaning that it may be possible (but is not
23456 guaranteed) for a program to be able to call a subprogram whose body
23457 is not yet elaborated, without raising a @code{Program_Error} exception.
23458
23459 @node Controlling Elaboration in GNAT - External Calls
23460 @section Controlling Elaboration in GNAT - External Calls
23461
23462 @noindent
23463 The previous section discussed the case in which the execution of a
23464 particular thread of elaboration code occurred entirely within a
23465 single unit. This is the easy case to handle, because a programmer
23466 has direct and total control over the order of elaboration, and
23467 furthermore, checks need only be generated in cases which are rare
23468 and which the compiler can easily detect.
23469 The situation is more complex when separate compilation is taken into account.
23470 Consider the following:
23471
23472 @smallexample @c ada
23473 @cartouche
23474 @group
23475 package Math is
23476    function Sqrt (Arg : Float) return Float;
23477 end Math;
23478
23479 package body Math is
23480    function Sqrt (Arg : Float) return Float is
23481    begin
23482          ...
23483    end Sqrt;
23484 end Math;
23485 @end group
23486 @group
23487 with Math;
23488 package Stuff is
23489    X : Float := Math.Sqrt (0.5);
23490 end Stuff;
23491
23492 with Stuff;
23493 procedure Main is
23494 begin
23495    ...
23496 end Main;
23497 @end group
23498 @end cartouche
23499 @end smallexample
23500
23501 @noindent
23502 where @code{Main} is the main program. When this program is executed, the
23503 elaboration code must first be executed, and one of the jobs of the
23504 binder is to determine the order in which the units of a program are
23505 to be elaborated. In this case we have four units: the spec and body
23506 of @code{Math},
23507 the spec of @code{Stuff} and the body of @code{Main}).
23508 In what order should the four separate sections of elaboration code
23509 be executed?
23510
23511 There are some restrictions in the order of elaboration that the binder
23512 can choose. In particular, if unit U has a @code{with}
23513 for a package @code{X}, then you
23514 are assured that the spec of @code{X}
23515 is elaborated before U , but you are
23516 not assured that the body of @code{X}
23517 is elaborated before U.
23518 This means that in the above case, the binder is allowed to choose the
23519 order:
23520
23521 @smallexample
23522 spec of Math
23523 spec of Stuff
23524 body of Math
23525 body of Main
23526 @end smallexample
23527
23528 @noindent
23529 but that's not good, because now the call to @code{Math.Sqrt}
23530 that happens during
23531 the elaboration of the @code{Stuff}
23532 spec happens before the body of @code{Math.Sqrt} is
23533 elaborated, and hence causes @code{Program_Error} exception to be raised.
23534 At first glance, one might say that the binder is misbehaving, because
23535 obviously you want to elaborate the body of something you @code{with}
23536 first, but
23537 that is not a general rule that can be followed in all cases. Consider
23538
23539 @smallexample @c ada
23540 @group
23541 @cartouche
23542 package X is ...
23543
23544 package Y is ...
23545
23546 with X;
23547 package body Y is ...
23548
23549 with Y;
23550 package body X is ...
23551 @end cartouche
23552 @end group
23553 @end smallexample
23554
23555 @noindent
23556 This is a common arrangement, and, apart from the order of elaboration
23557 problems that might arise in connection with elaboration code, this works fine.
23558 A rule that says that you must first elaborate the body of anything you
23559 @code{with} cannot work in this case:
23560 the body of @code{X} @code{with}'s @code{Y},
23561 which means you would have to
23562 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23563 which means
23564 you have to elaborate the body of @code{X} first, but ... and we have a
23565 loop that cannot be broken.
23566
23567 It is true that the binder can in many cases guess an order of elaboration
23568 that is unlikely to cause a @code{Program_Error}
23569 exception to be raised, and it tries to do so (in the
23570 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23571 by default
23572 elaborate the body of @code{Math} right after its spec, so all will be well).
23573
23574 However, a program that blindly relies on the binder to be helpful can
23575 get into trouble, as we discussed in the previous sections, so
23576 GNAT
23577 provides a number of facilities for assisting the programmer in
23578 developing programs that are robust with respect to elaboration order.
23579
23580 @node Default Behavior in GNAT - Ensuring Safety
23581 @section Default Behavior in GNAT - Ensuring Safety
23582
23583 @noindent
23584 The default behavior in GNAT ensures elaboration safety. In its
23585 default mode GNAT implements the
23586 rule we previously described as the right approach. Let's restate it:
23587
23588 @itemize
23589 @item
23590 @emph{If a unit has elaboration code that can directly or indirectly make a
23591 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
23592 in a @code{with}'ed unit, then if the @code{with}'ed unit
23593 does not have pragma @code{Pure} or
23594 @code{Preelaborate}, then the client should have an
23595 @code{Elaborate_All} for the @code{with}'ed unit.}
23596 @end itemize
23597
23598 @noindent
23599 By following this rule a client is assured that calls and instantiations
23600 can be made without risk of an exception.
23601
23602 In this mode GNAT traces all calls that are potentially made from
23603 elaboration code, and puts in any missing implicit @code{Elaborate_All}
23604 pragmas.
23605 The advantage of this approach is that no elaboration problems
23606 are possible if the binder can find an elaboration order that is
23607 consistent with these implicit @code{Elaborate_All} pragmas. The
23608 disadvantage of this approach is that no such order may exist.
23609
23610 If the binder does not generate any diagnostics, then it means that it
23611 has found an elaboration order that is guaranteed to be safe. However,
23612 the binder may still be relying on implicitly generated
23613 @code{Elaborate_All} pragmas so portability to other compilers than
23614 GNAT is not guaranteed.
23615
23616 If it is important to guarantee portability, then the compilations should
23617 use the
23618 @option{-gnatwl}
23619 (warn on elaboration problems) switch. This will cause warning messages
23620 to be generated indicating the missing @code{Elaborate_All} pragmas.
23621 Consider the following source program:
23622
23623 @smallexample @c ada
23624 @group
23625 @cartouche
23626 with k;
23627 package j is
23628   m : integer := k.r;
23629 end;
23630 @end cartouche
23631 @end group
23632 @end smallexample
23633
23634 @noindent
23635 where it is clear that there
23636 should be a pragma @code{Elaborate_All}
23637 for unit @code{k}. An implicit pragma will be generated, and it is
23638 likely that the binder will be able to honor it. However, if you want
23639 to port this program to some other Ada compiler than GNAT.
23640 it is safer to include the pragma explicitly in the source. If this
23641 unit is compiled with the
23642 @option{-gnatwl}
23643 switch, then the compiler outputs a warning:
23644
23645 @smallexample
23646 @group
23647 @cartouche
23648 1. with k;
23649 2. package j is
23650 3.   m : integer := k.r;
23651                      |
23652    >>> warning: call to "r" may raise Program_Error
23653    >>> warning: missing pragma Elaborate_All for "k"
23654
23655 4. end;
23656 @end cartouche
23657 @end group
23658 @end smallexample
23659
23660 @noindent
23661 and these warnings can be used as a guide for supplying manually
23662 the missing pragmas. It is usually a bad idea to use this warning
23663 option during development. That's because it will warn you when
23664 you need to put in a pragma, but cannot warn you when it is time
23665 to take it out. So the use of pragma Elaborate_All may lead to
23666 unnecessary dependencies and even false circularities.
23667
23668 This default mode is more restrictive than the Ada Reference
23669 Manual, and it is possible to construct programs which will compile
23670 using the dynamic model described there, but will run into a
23671 circularity using the safer static model we have described.
23672
23673 Of course any Ada compiler must be able to operate in a mode
23674 consistent with the requirements of the Ada Reference Manual,
23675 and in particular must have the capability of implementing the
23676 standard dynamic model of elaboration with run-time checks.
23677
23678 In GNAT, this standard mode can be achieved either by the use of
23679 the @option{-gnatE} switch on the compiler (@command{gcc} or
23680 @command{gnatmake}) command, or by the use of the configuration pragma:
23681
23682 @smallexample @c ada
23683 pragma Elaboration_Checks (RM);
23684 @end smallexample
23685
23686 @noindent
23687 Either approach will cause the unit affected to be compiled using the
23688 standard dynamic run-time elaboration checks described in the Ada
23689 Reference Manual. The static model is generally preferable, since it
23690 is clearly safer to rely on compile and link time checks rather than
23691 run-time checks. However, in the case of legacy code, it may be
23692 difficult to meet the requirements of the static model. This
23693 issue is further discussed in
23694 @ref{What to Do If the Default Elaboration Behavior Fails}.
23695
23696 Note that the static model provides a strict subset of the allowed
23697 behavior and programs of the Ada Reference Manual, so if you do
23698 adhere to the static model and no circularities exist,
23699 then you are assured that your program will
23700 work using the dynamic model, providing that you remove any
23701 pragma Elaborate statements from the source.
23702
23703 @node Treatment of Pragma Elaborate
23704 @section Treatment of Pragma Elaborate
23705 @cindex Pragma Elaborate
23706
23707 @noindent
23708 The use of @code{pragma Elaborate}
23709 should generally be avoided in Ada 95 programs.
23710 The reason for this is that there is no guarantee that transitive calls
23711 will be properly handled. Indeed at one point, this pragma was placed
23712 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23713
23714 Now that's a bit restrictive. In practice, the case in which
23715 @code{pragma Elaborate} is useful is when the caller knows that there
23716 are no transitive calls, or that the called unit contains all necessary
23717 transitive @code{pragma Elaborate} statements, and legacy code often
23718 contains such uses.
23719
23720 Strictly speaking the static mode in GNAT should ignore such pragmas,
23721 since there is no assurance at compile time that the necessary safety
23722 conditions are met. In practice, this would cause GNAT to be incompatible
23723 with correctly written Ada 83 code that had all necessary
23724 @code{pragma Elaborate} statements in place. Consequently, we made the
23725 decision that GNAT in its default mode will believe that if it encounters
23726 a @code{pragma Elaborate} then the programmer knows what they are doing,
23727 and it will trust that no elaboration errors can occur.
23728
23729 The result of this decision is two-fold. First to be safe using the
23730 static mode, you should remove all @code{pragma Elaborate} statements.
23731 Second, when fixing circularities in existing code, you can selectively
23732 use @code{pragma Elaborate} statements to convince the static mode of
23733 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23734 statement.
23735
23736 When using the static mode with @option{-gnatwl}, any use of
23737 @code{pragma Elaborate} will generate a warning about possible
23738 problems.
23739
23740 @node Elaboration Issues for Library Tasks
23741 @section Elaboration Issues for Library Tasks
23742 @cindex Library tasks, elaboration issues
23743 @cindex Elaboration of library tasks
23744
23745 @noindent
23746 In this section we examine special elaboration issues that arise for
23747 programs that declare library level tasks.
23748
23749 Generally the model of execution of an Ada program is that all units are
23750 elaborated, and then execution of the program starts. However, the
23751 declaration of library tasks definitely does not fit this model. The
23752 reason for this is that library tasks start as soon as they are declared
23753 (more precisely, as soon as the statement part of the enclosing package
23754 body is reached), that is to say before elaboration
23755 of the program is complete. This means that if such a task calls a
23756 subprogram, or an entry in another task, the callee may or may not be
23757 elaborated yet, and in the standard
23758 Reference Manual model of dynamic elaboration checks, you can even
23759 get timing dependent Program_Error exceptions, since there can be
23760 a race between the elaboration code and the task code.
23761
23762 The static model of elaboration in GNAT seeks to avoid all such
23763 dynamic behavior, by being conservative, and the conservative
23764 approach in this particular case is to assume that all the code
23765 in a task body is potentially executed at elaboration time if
23766 a task is declared at the library level.
23767
23768 This can definitely result in unexpected circularities. Consider
23769 the following example
23770
23771 @smallexample @c ada
23772 package Decls is
23773   task Lib_Task is
23774      entry Start;
23775   end Lib_Task;
23776
23777   type My_Int is new Integer;
23778
23779   function Ident (M : My_Int) return My_Int;
23780 end Decls;
23781
23782 with Utils;
23783 package body Decls is
23784   task body Lib_Task is
23785   begin
23786      accept Start;
23787      Utils.Put_Val (2);
23788   end Lib_Task;
23789
23790   function Ident (M : My_Int) return My_Int is
23791   begin
23792      return M;
23793   end Ident;
23794 end Decls;
23795
23796 with Decls;
23797 package Utils is
23798   procedure Put_Val (Arg : Decls.My_Int);
23799 end Utils;
23800
23801 with Text_IO;
23802 package body Utils is
23803   procedure Put_Val (Arg : Decls.My_Int) is
23804   begin
23805      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23806   end Put_Val;
23807 end Utils;
23808
23809 with Decls;
23810 procedure Main is
23811 begin
23812    Decls.Lib_Task.Start;
23813 end;
23814 @end smallexample
23815
23816 @noindent
23817 If the above example is compiled in the default static elaboration
23818 mode, then a circularity occurs. The circularity comes from the call
23819 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23820 this call occurs in elaboration code, we need an implicit pragma
23821 @code{Elaborate_All} for @code{Utils}. This means that not only must
23822 the spec and body of @code{Utils} be elaborated before the body
23823 of @code{Decls}, but also the spec and body of any unit that is
23824 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23825 the body of @code{Decls}. This is the transitive implication of
23826 pragma @code{Elaborate_All} and it makes sense, because in general
23827 the body of @code{Put_Val} might have a call to something in a
23828 @code{with'ed} unit.
23829
23830 In this case, the body of Utils (actually its spec) @code{with's}
23831 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23832 must be elaborated before itself, in case there is a call from the
23833 body of @code{Utils}.
23834
23835 Here is the exact chain of events we are worrying about:
23836
23837 @enumerate
23838 @item
23839 In the body of @code{Decls} a call is made from within the body of a library
23840 task to a subprogram in the package @code{Utils}. Since this call may
23841 occur at elaboration time (given that the task is activated at elaboration
23842 time), we have to assume the worst, i.e. that the
23843 call does happen at elaboration time.
23844
23845 @item
23846 This means that the body and spec of @code{Util} must be elaborated before
23847 the body of @code{Decls} so that this call does not cause an access before
23848 elaboration.
23849
23850 @item
23851 Within the body of @code{Util}, specifically within the body of
23852 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23853 by this package.
23854
23855 @item
23856 One such @code{with}'ed package is package @code{Decls}, so there
23857 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23858 In fact there is such a call in this example, but we would have to
23859 assume that there was such a call even if it were not there, since
23860 we are not supposed to write the body of @code{Decls} knowing what
23861 is in the body of @code{Utils}; certainly in the case of the
23862 static elaboration model, the compiler does not know what is in
23863 other bodies and must assume the worst.
23864
23865 @item
23866 This means that the spec and body of @code{Decls} must also be
23867 elaborated before we elaborate the unit containing the call, but
23868 that unit is @code{Decls}! This means that the body of @code{Decls}
23869 must be elaborated before itself, and that's a circularity.
23870 @end enumerate
23871
23872 @noindent
23873 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23874 the body of @code{Decls} you will get a true Ada Reference Manual
23875 circularity that makes the program illegal.
23876
23877 In practice, we have found that problems with the static model of
23878 elaboration in existing code often arise from library tasks, so
23879 we must address this particular situation.
23880
23881 Note that if we compile and run the program above, using the dynamic model of
23882 elaboration (that is to say use the @option{-gnatE} switch),
23883 then it compiles, binds,
23884 links, and runs, printing the expected result of 2. Therefore in some sense
23885 the circularity here is only apparent, and we need to capture
23886 the properties of this program that  distinguish it from other library-level
23887 tasks that have real elaboration problems.
23888
23889 We have four possible answers to this question:
23890
23891 @itemize @bullet
23892
23893 @item
23894 Use the dynamic model of elaboration.
23895
23896 If we use the @option{-gnatE} switch, then as noted above, the program works.
23897 Why is this? If we examine the task body, it is apparent that the task cannot
23898 proceed past the
23899 @code{accept} statement until after elaboration has been completed, because
23900 the corresponding entry call comes from the main program, not earlier.
23901 This is why the dynamic model works here. But that's really giving
23902 up on a precise analysis, and we prefer to take this approach only if we cannot
23903 solve the
23904 problem in any other manner. So let us examine two ways to reorganize
23905 the program to avoid the potential elaboration problem.
23906
23907 @item
23908 Split library tasks into separate packages.
23909
23910 Write separate packages, so that library tasks are isolated from
23911 other declarations as much as possible. Let us look at a variation on
23912 the above program.
23913
23914 @smallexample @c ada
23915 package Decls1 is
23916   task Lib_Task is
23917      entry Start;
23918   end Lib_Task;
23919 end Decls1;
23920
23921 with Utils;
23922 package body Decls1 is
23923   task body Lib_Task is
23924   begin
23925      accept Start;
23926      Utils.Put_Val (2);
23927   end Lib_Task;
23928 end Decls1;
23929
23930 package Decls2 is
23931   type My_Int is new Integer;
23932   function Ident (M : My_Int) return My_Int;
23933 end Decls2;
23934
23935 with Utils;
23936 package body Decls2 is
23937   function Ident (M : My_Int) return My_Int is
23938   begin
23939      return M;
23940   end Ident;
23941 end Decls2;
23942
23943 with Decls2;
23944 package Utils is
23945   procedure Put_Val (Arg : Decls2.My_Int);
23946 end Utils;
23947
23948 with Text_IO;
23949 package body Utils is
23950   procedure Put_Val (Arg : Decls2.My_Int) is
23951   begin
23952      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23953   end Put_Val;
23954 end Utils;
23955
23956 with Decls1;
23957 procedure Main is
23958 begin
23959    Decls1.Lib_Task.Start;
23960 end;
23961 @end smallexample
23962
23963 @noindent
23964 All we have done is to split @code{Decls} into two packages, one
23965 containing the library task, and one containing everything else. Now
23966 there is no cycle, and the program compiles, binds, links and executes
23967 using the default static model of elaboration.
23968
23969 @item
23970 Declare separate task types.
23971
23972 A significant part of the problem arises because of the use of the
23973 single task declaration form. This means that the elaboration of
23974 the task type, and the elaboration of the task itself (i.e. the
23975 creation of the task) happen at the same time. A good rule
23976 of style in Ada 95 is to always create explicit task types. By
23977 following the additional step of placing task objects in separate
23978 packages from the task type declaration, many elaboration problems
23979 are avoided. Here is another modified example of the example program:
23980
23981 @smallexample @c ada
23982 package Decls is
23983   task type Lib_Task_Type is
23984      entry Start;
23985   end Lib_Task_Type;
23986
23987   type My_Int is new Integer;
23988
23989   function Ident (M : My_Int) return My_Int;
23990 end Decls;
23991
23992 with Utils;
23993 package body Decls is
23994   task body Lib_Task_Type is
23995   begin
23996      accept Start;
23997      Utils.Put_Val (2);
23998   end Lib_Task_Type;
23999
24000   function Ident (M : My_Int) return My_Int is
24001   begin
24002      return M;
24003   end Ident;
24004 end Decls;
24005
24006 with Decls;
24007 package Utils is
24008   procedure Put_Val (Arg : Decls.My_Int);
24009 end Utils;
24010
24011 with Text_IO;
24012 package body Utils is
24013   procedure Put_Val (Arg : Decls.My_Int) is
24014   begin
24015      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24016   end Put_Val;
24017 end Utils;
24018
24019 with Decls;
24020 package Declst is
24021    Lib_Task : Decls.Lib_Task_Type;
24022 end Declst;
24023
24024 with Declst;
24025 procedure Main is
24026 begin
24027    Declst.Lib_Task.Start;
24028 end;
24029 @end smallexample
24030
24031 @noindent
24032 What we have done here is to replace the @code{task} declaration in
24033 package @code{Decls} with a @code{task type} declaration. Then we
24034 introduce a separate package @code{Declst} to contain the actual
24035 task object. This separates the elaboration issues for
24036 the @code{task type}
24037 declaration, which causes no trouble, from the elaboration issues
24038 of the task object, which is also unproblematic, since it is now independent
24039 of the elaboration of  @code{Utils}.
24040 This separation of concerns also corresponds to
24041 a generally sound engineering principle of separating declarations
24042 from instances. This version of the program also compiles, binds, links,
24043 and executes, generating the expected output.
24044
24045 @item
24046 Use No_Entry_Calls_In_Elaboration_Code restriction.
24047 @cindex No_Entry_Calls_In_Elaboration_Code
24048
24049 The previous two approaches described how a program can be restructured
24050 to avoid the special problems caused by library task bodies. in practice,
24051 however, such restructuring may be difficult to apply to existing legacy code,
24052 so we must consider solutions that do not require massive rewriting.
24053
24054 Let us consider more carefully why our original sample program works
24055 under the dynamic model of elaboration. The reason is that the code
24056 in the task body blocks immediately on the @code{accept}
24057 statement. Now of course there is nothing to prohibit elaboration
24058 code from making entry calls (for example from another library level task),
24059 so we cannot tell in isolation that
24060 the task will not execute the accept statement  during elaboration.
24061
24062 However, in practice it is very unusual to see elaboration code
24063 make any entry calls, and the pattern of tasks starting
24064 at elaboration time and then immediately blocking on @code{accept} or
24065 @code{select} statements is very common. What this means is that
24066 the compiler is being too pessimistic when it analyzes the
24067 whole package body as though it might be executed at elaboration
24068 time.
24069
24070 If we know that the elaboration code contains no entry calls, (a very safe
24071 assumption most of the time, that could almost be made the default
24072 behavior), then we can compile all units of the program under control
24073 of the following configuration pragma:
24074
24075 @smallexample
24076 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24077 @end smallexample
24078
24079 @noindent
24080 This pragma can be placed in the @file{gnat.adc} file in the usual
24081 manner. If we take our original unmodified program and compile it
24082 in the presence of a @file{gnat.adc} containing the above pragma,
24083 then once again, we can compile, bind, link, and execute, obtaining
24084 the expected result. In the presence of this pragma, the compiler does
24085 not trace calls in a task body, that appear after the first @code{accept}
24086 or @code{select} statement, and therefore does not report a potential
24087 circularity in the original program.
24088
24089 The compiler will check to the extent it can that the above
24090 restriction is not violated, but it is not always possible to do a
24091 complete check at compile time, so it is important to use this
24092 pragma only if the stated restriction is in fact met, that is to say
24093 no task receives an entry call before elaboration of all units is completed.
24094
24095 @end itemize
24096
24097 @node Mixing Elaboration Models
24098 @section Mixing Elaboration Models
24099 @noindent
24100 So far, we have assumed that the entire program is either compiled
24101 using the dynamic model or static model, ensuring consistency. It
24102 is possible to mix the two models, but rules have to be followed
24103 if this mixing is done to ensure that elaboration checks are not
24104 omitted.
24105
24106 The basic rule is that @emph{a unit compiled with the static model cannot
24107 be @code{with'ed} by a unit compiled with the dynamic model}. The
24108 reason for this is that in the static model, a unit assumes that
24109 its clients guarantee to use (the equivalent of) pragma
24110 @code{Elaborate_All} so that no elaboration checks are required
24111 in inner subprograms, and this assumption is violated if the
24112 client is compiled with dynamic checks.
24113
24114 The precise rule is as follows. A unit that is compiled with dynamic
24115 checks can only @code{with} a unit that meets at least one of the
24116 following criteria:
24117
24118 @itemize @bullet
24119
24120 @item
24121 The @code{with'ed} unit is itself compiled with dynamic elaboration
24122 checks (that is with the @option{-gnatE} switch.
24123
24124 @item
24125 The @code{with'ed} unit is an internal GNAT implementation unit from
24126 the System, Interfaces, Ada, or GNAT hierarchies.
24127
24128 @item
24129 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24130
24131 @item
24132 The @code{with'ing} unit (that is the client) has an explicit pragma
24133 @code{Elaborate_All} for the @code{with'ed} unit.
24134
24135 @end itemize
24136
24137 @noindent
24138 If this rule is violated, that is if a unit with dynamic elaboration
24139 checks @code{with's} a unit that does not meet one of the above four
24140 criteria, then the binder (@code{gnatbind}) will issue a warning
24141 similar to that in the following example:
24142
24143 @smallexample
24144 warning: "x.ads" has dynamic elaboration checks and with's
24145 warning:   "y.ads" which has static elaboration checks
24146 @end smallexample
24147
24148 @noindent
24149 These warnings indicate that the rule has been violated, and that as a result
24150 elaboration checks may be missed in the resulting executable file.
24151 This warning may be suppressed using the @option{-ws} binder switch
24152 in the usual manner.
24153
24154 One useful application of this mixing rule is in the case of a subsystem
24155 which does not itself @code{with} units from the remainder of the
24156 application. In this case, the entire subsystem can be compiled with
24157 dynamic checks to resolve a circularity in the subsystem, while
24158 allowing the main application that uses this subsystem to be compiled
24159 using the more reliable default static model.
24160
24161 @node What to Do If the Default Elaboration Behavior Fails
24162 @section What to Do If the Default Elaboration Behavior Fails
24163
24164 @noindent
24165 If the binder cannot find an acceptable order, it outputs detailed
24166 diagnostics. For example:
24167 @smallexample
24168 @group
24169 @iftex
24170 @leftskip=0cm
24171 @end iftex
24172 error: elaboration circularity detected
24173 info:   "proc (body)" must be elaborated before "pack (body)"
24174 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24175 info:     recompile "pack (body)" with -gnatwl
24176 info:                             for full details
24177 info:       "proc (body)"
24178 info:         is needed by its spec:
24179 info:       "proc (spec)"
24180 info:         which is withed by:
24181 info:       "pack (body)"
24182 info:  "pack (body)" must be elaborated before "proc (body)"
24183 info:     reason: pragma Elaborate in unit "proc (body)"
24184 @end group
24185
24186 @end smallexample
24187
24188 @noindent
24189 In this case we have a cycle that the binder cannot break. On the one
24190 hand, there is an explicit pragma Elaborate in @code{proc} for
24191 @code{pack}. This means that the body of @code{pack} must be elaborated
24192 before the body of @code{proc}. On the other hand, there is elaboration
24193 code in @code{pack} that calls a subprogram in @code{proc}. This means
24194 that for maximum safety, there should really be a pragma
24195 Elaborate_All in @code{pack} for @code{proc} which would require that
24196 the body of @code{proc} be elaborated before the body of
24197 @code{pack}. Clearly both requirements cannot be satisfied.
24198 Faced with a circularity of this kind, you have three different options.
24199
24200 @table @asis
24201 @item Fix the program
24202 The most desirable option from the point of view of long-term maintenance
24203 is to rearrange the program so that the elaboration problems are avoided.
24204 One useful technique is to place the elaboration code into separate
24205 child packages. Another is to move some of the initialization code to
24206 explicitly called subprograms, where the program controls the order
24207 of initialization explicitly. Although this is the most desirable option,
24208 it may be impractical and involve too much modification, especially in
24209 the case of complex legacy code.
24210
24211 @item Perform dynamic checks
24212 If the compilations are done using the
24213 @option{-gnatE}
24214 (dynamic elaboration check) switch, then GNAT behaves in
24215 a quite different manner. Dynamic checks are generated for all calls
24216 that could possibly result in raising an exception. With this switch,
24217 the compiler does not generate implicit @code{Elaborate_All} pragmas.
24218 The behavior then is exactly as specified in the Ada 95 Reference Manual.
24219 The binder will generate an executable program that may or may not
24220 raise @code{Program_Error}, and then it is the programmer's job to ensure
24221 that it does not raise an exception. Note that it is important to
24222 compile all units with the switch, it cannot be used selectively.
24223
24224 @item Suppress checks
24225 The drawback of dynamic checks is that they generate a
24226 significant overhead at run time, both in space and time. If you
24227 are absolutely sure that your program cannot raise any elaboration
24228 exceptions, and you still want to use the dynamic elaboration model,
24229 then you can use the configuration pragma
24230 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24231 example this pragma could be placed in the @file{gnat.adc} file.
24232
24233 @item Suppress checks selectively
24234 When you know that certain calls in elaboration code cannot possibly
24235 lead to an elaboration error, and the binder nevertheless generates warnings
24236 on those calls and inserts Elaborate_All pragmas that lead to elaboration
24237 circularities, it is possible to remove those warnings locally and obtain
24238 a program that will bind. Clearly this can be unsafe, and it is the
24239 responsibility of the programmer to make sure that the resulting program has
24240 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
24241 be used with different granularity to suppress warnings and break
24242 elaboration circularities:
24243
24244 @itemize @bullet
24245 @item
24246 Place the pragma that names the called subprogram in the declarative part
24247 that contains the call.
24248
24249 @item
24250 Place the pragma in the declarative part, without naming an entity. This
24251 disables warnings on all calls in the corresponding  declarative region.
24252
24253 @item
24254 Place the pragma in the package spec that declares the called subprogram,
24255 and name the subprogram. This disables warnings on all elaboration calls to
24256 that subprogram.
24257
24258 @item
24259 Place the pragma in the package spec that declares the called subprogram,
24260 without naming any entity. This disables warnings on all elaboration calls to
24261 all subprograms declared in this spec.
24262
24263 @item Use Pragma Elaborate
24264 As previously described in section @xref{Treatment of Pragma Elaborate},
24265 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24266 that no elaboration checks are required on calls to the designated unit.
24267 There may be cases in which the caller knows that no transitive calls
24268 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24269 case where @code{pragma Elaborate_All} would cause a circularity.
24270 @end itemize
24271
24272 @noindent
24273 These five cases are listed in order of decreasing safety, and therefore
24274 require increasing programmer care in their application. Consider the
24275 following program:
24276
24277 @smallexample @c adanocomment
24278 package Pack1 is
24279   function F1 return Integer;
24280   X1 : Integer;
24281 end Pack1;
24282
24283 package Pack2 is
24284   function F2 return Integer;
24285   function Pure (x : integer) return integer;
24286   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24287   --  pragma Suppress (Elaboration_Check);              -- (4)
24288 end Pack2;
24289
24290 with Pack2;
24291 package body Pack1 is
24292   function F1 return Integer is
24293   begin
24294     return 100;
24295   end F1;
24296   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24297 begin
24298   declare
24299     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24300     --  pragma Suppress(Elaboration_Check);             -- (2)
24301   begin
24302     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24303   end;
24304 end Pack1;
24305
24306 with Pack1;
24307 package body Pack2 is
24308   function F2 return Integer is
24309   begin
24310      return Pack1.F1;
24311   end F2;
24312   function Pure (x : integer) return integer is
24313   begin
24314      return x ** 3 - 3 * x;
24315   end;
24316 end Pack2;
24317
24318 with Pack1, Ada.Text_IO;
24319 procedure Proc3 is
24320 begin
24321   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24322 end Proc3;
24323 @end smallexample
24324 In the absence of any pragmas, an attempt to bind this program produces
24325 the following diagnostics:
24326 @smallexample
24327 @group
24328 @iftex
24329 @leftskip=.5cm
24330 @end iftex
24331 error: elaboration circularity detected
24332 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24333 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24334 info:       recompile "pack1 (body)" with -gnatwl for full details
24335 info:          "pack1 (body)"
24336 info:             must be elaborated along with its spec:
24337 info:          "pack1 (spec)"
24338 info:             which is withed by:
24339 info:          "pack2 (body)"
24340 info:             which must be elaborated along with its spec:
24341 info:          "pack2 (spec)"
24342 info:             which is withed by:
24343 info:          "pack1 (body)"
24344 @end group
24345 @end smallexample
24346 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24347 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24348 F2 is safe, even though F2 calls F1, because the call appears after the
24349 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24350 remove the warning on the call. It is also possible to use pragma (2)
24351 because there are no other potentially unsafe calls in the block.
24352
24353 @noindent
24354 The call to @code{Pure} is safe because this function does not depend on the
24355 state of @code{Pack2}. Therefore any call to this function is safe, and it
24356 is correct to place pragma (3) in the corresponding package spec.
24357
24358 @noindent
24359 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24360 warnings on all calls to functions declared therein. Note that this is not
24361 necessarily safe, and requires more detailed examination of the subprogram
24362 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24363 be already elaborated.
24364 @end table
24365
24366 @noindent
24367 It is hard to generalize on which of these four approaches should be
24368 taken. Obviously if it is possible to fix the program so that the default
24369 treatment works, this is preferable, but this may not always be practical.
24370 It is certainly simple enough to use
24371 @option{-gnatE}
24372 but the danger in this case is that, even if the GNAT binder
24373 finds a correct elaboration order, it may not always do so,
24374 and certainly a binder from another Ada compiler might not. A
24375 combination of testing and analysis (for which the warnings generated
24376 with the
24377 @option{-gnatwl}
24378 switch can be useful) must be used to ensure that the program is free
24379 of errors. One switch that is useful in this testing is the
24380 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24381 switch for
24382 @code{gnatbind}.
24383 Normally the binder tries to find an order that has the best chance of
24384 of avoiding elaboration problems. With this switch, the binder
24385 plays a devil's advocate role, and tries to choose the order that
24386 has the best chance of failing. If your program works even with this
24387 switch, then it has a better chance of being error free, but this is still
24388 not a guarantee.
24389
24390 For an example of this approach in action, consider the C-tests (executable
24391 tests) from the ACVC suite. If these are compiled and run with the default
24392 treatment, then all but one of them succeed without generating any error
24393 diagnostics from the binder. However, there is one test that fails, and
24394 this is not surprising, because the whole point of this test is to ensure
24395 that the compiler can handle cases where it is impossible to determine
24396 a correct order statically, and it checks that an exception is indeed
24397 raised at run time.
24398
24399 This one test must be compiled and run using the
24400 @option{-gnatE}
24401 switch, and then it passes. Alternatively, the entire suite can
24402 be run using this switch. It is never wrong to run with the dynamic
24403 elaboration switch if your code is correct, and we assume that the
24404 C-tests are indeed correct (it is less efficient, but efficiency is
24405 not a factor in running the ACVC tests.)
24406
24407 @node Elaboration for Access-to-Subprogram Values
24408 @section Elaboration for Access-to-Subprogram Values
24409 @cindex Access-to-subprogram
24410
24411 @noindent
24412 The introduction of access-to-subprogram types in Ada 95 complicates
24413 the handling of elaboration. The trouble is that it becomes
24414 impossible to tell at compile time which procedure
24415 is being called. This means that it is not possible for the binder
24416 to analyze the elaboration requirements in this case.
24417
24418 If at the point at which the access value is created
24419 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24420 the body of the subprogram is
24421 known to have been elaborated, then the access value is safe, and its use
24422 does not require a check. This may be achieved by appropriate arrangement
24423 of the order of declarations if the subprogram is in the current unit,
24424 or, if the subprogram is in another unit, by using pragma
24425 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24426 on the referenced unit.
24427
24428 If the referenced body is not known to have been elaborated at the point
24429 the access value is created, then any use of the access value must do a
24430 dynamic check, and this dynamic check will fail and raise a
24431 @code{Program_Error} exception if the body has not been elaborated yet.
24432 GNAT will generate the necessary checks, and in addition, if the
24433 @option{-gnatwl}
24434 switch is set, will generate warnings that such checks are required.
24435
24436 The use of dynamic dispatching for tagged types similarly generates
24437 a requirement for dynamic checks, and premature calls to any primitive
24438 operation of a tagged type before the body of the operation has been
24439 elaborated, will result in the raising of @code{Program_Error}.
24440
24441 @node Summary of Procedures for Elaboration Control
24442 @section Summary of Procedures for Elaboration Control
24443 @cindex Elaboration control
24444
24445 @noindent
24446 First, compile your program with the default options, using none of
24447 the special elaboration control switches. If the binder successfully
24448 binds your program, then you can be confident that, apart from issues
24449 raised by the use of access-to-subprogram types and dynamic dispatching,
24450 the program is free of elaboration errors. If it is important that the
24451 program be portable, then use the
24452 @option{-gnatwl}
24453 switch to generate warnings about missing @code{Elaborate_All}
24454 pragmas, and supply the missing pragmas.
24455
24456 If the program fails to bind using the default static elaboration
24457 handling, then you can fix the program to eliminate the binder
24458 message, or recompile the entire program with the
24459 @option{-gnatE} switch to generate dynamic elaboration checks,
24460 and, if you are sure there really are no elaboration problems,
24461 use a global pragma @code{Suppress (Elaboration_Check)}.
24462
24463 @node Other Elaboration Order Considerations
24464 @section Other Elaboration Order Considerations
24465 @noindent
24466 This section has been entirely concerned with the issue of finding a valid
24467 elaboration order, as defined by the Ada Reference Manual. In a case
24468 where several elaboration orders are valid, the task is to find one
24469 of the possible valid elaboration orders (and the static model in GNAT
24470 will ensure that this is achieved).
24471
24472 The purpose of the elaboration rules in the Ada Reference Manual is to
24473 make sure that no entity is accessed before it has been elaborated. For
24474 a subprogram, this means that the spec and body must have been elaborated
24475 before the subprogram is called. For an object, this means that the object
24476 must have been elaborated before its value is read or written. A violation
24477 of either of these two requirements is an access before elaboration order,
24478 and this section has been all about avoiding such errors.
24479
24480 In the case where more than one order of elaboration is possible, in the
24481 sense that access before elaboration errors are avoided, then any one of
24482 the orders is ``correct'' in the sense that it meets the requirements of
24483 the Ada Reference Manual, and no such error occurs.
24484
24485 However, it may be the case for a given program, that there are
24486 constraints on the order of elaboration that come not from consideration
24487 of avoiding elaboration errors, but rather from extra-lingual logic
24488 requirements. Consider this example:
24489
24490 @smallexample @c ada
24491 with Init_Constants;
24492 package Constants is
24493    X : Integer := 0;
24494    Y : Integer := 0;
24495 end Constants;
24496
24497 package Init_Constants is
24498    procedure P; -- require a body
24499 end Init_Constants;
24500
24501 with Constants;
24502 package body Init_Constants is
24503    procedure P is begin null; end;
24504 begin
24505    Constants.X := 3;
24506    Constants.Y := 4;
24507 end Init_Constants;
24508
24509 with Constants;
24510 package Calc is
24511    Z : Integer := Constants.X + Constants.Y;
24512 end Calc;
24513
24514 with Calc;
24515 with Text_IO; use Text_IO;
24516 procedure Main is
24517 begin
24518    Put_Line (Calc.Z'Img);
24519 end Main;
24520 @end smallexample
24521
24522 @noindent
24523 In this example, there is more than one valid order of elaboration. For
24524 example both the following are correct orders:
24525
24526 @smallexample
24527 Init_Constants spec
24528 Constants spec
24529 Calc spec
24530 Init_Constants body
24531 Main body
24532
24533   and
24534
24535 Init_Constants spec
24536 Init_Constants body
24537 Constants spec
24538 Calc spec
24539 Main body
24540 @end smallexample
24541
24542 @noindent
24543 There is no language rule to prefer one or the other, both are correct
24544 from an order of elaboration point of view. But the programmatic effects
24545 of the two orders are very different. In the first, the elaboration routine
24546 of @code{Calc} initializes @code{Z} to zero, and then the main program
24547 runs with this value of zero. But in the second order, the elaboration
24548 routine of @code{Calc} runs after the body of Init_Constants has set
24549 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24550 runs.
24551
24552 One could perhaps by applying pretty clever non-artificial intelligence
24553 to the situation guess that it is more likely that the second order of
24554 elaboration is the one desired, but there is no formal linguistic reason
24555 to prefer one over the other. In fact in this particular case, GNAT will
24556 prefer the second order, because of the rule that bodies are elaborated
24557 as soon as possible, but it's just luck that this is what was wanted
24558 (if indeed the second order was preferred).
24559
24560 If the program cares about the order of elaboration routines in a case like
24561 this, it is important to specify the order required. In this particular
24562 case, that could have been achieved by adding to the spec of Calc:
24563
24564 @smallexample @c ada
24565 pragma Elaborate_All (Constants);
24566 @end smallexample
24567
24568 @noindent
24569 which requires that the body (if any) and spec of @code{Constants},
24570 as well as the body and spec of any unit @code{with}'ed by
24571 @code{Constants} be elaborated before @code{Calc} is elaborated.
24572
24573 Clearly no automatic method can always guess which alternative you require,
24574 and if you are working with legacy code that had constraints of this kind
24575 which were not properly specified by adding @code{Elaborate} or
24576 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24577 compilers can choose different orders.
24578
24579 The @code{gnatbind}
24580 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24581 out problems. This switch causes bodies to be elaborated as late as possible
24582 instead of as early as possible. In the example above, it would have forced
24583 the choice of the first elaboration order. If you get different results
24584 when using this switch, and particularly if one set of results is right,
24585 and one is wrong as far as you are concerned, it shows that you have some
24586 missing @code{Elaborate} pragmas. For the example above, we have the
24587 following output:
24588
24589 @smallexample
24590 gnatmake -f -q main
24591 main
24592  7
24593 gnatmake -f -q main -bargs -p
24594 main
24595  0
24596 @end smallexample
24597
24598 @noindent
24599 It is of course quite unlikely that both these results are correct, so
24600 it is up to you in a case like this to investigate the source of the
24601 difference, by looking at the two elaboration orders that are chosen,
24602 and figuring out which is correct, and then adding the necessary
24603 @code{Elaborate_All} pragmas to ensure the desired order.
24604
24605 @node Inline Assembler
24606 @appendix Inline Assembler
24607
24608 @noindent
24609 If you need to write low-level software that interacts directly
24610 with the hardware, Ada provides two ways to incorporate assembly
24611 language code into your program.  First, you can import and invoke
24612 external routines written in assembly language, an Ada feature fully
24613 supported by GNAT.  However, for small sections of code it may be simpler
24614 or more efficient to include assembly language statements directly
24615 in your Ada source program, using the facilities of the implementation-defined
24616 package @code{System.Machine_Code}, which incorporates the gcc
24617 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24618 including the following:
24619
24620 @itemize @bullet
24621 @item No need to use non-Ada tools
24622 @item Consistent interface over different targets
24623 @item Automatic usage of the proper calling conventions
24624 @item Access to Ada constants and variables
24625 @item Definition of intrinsic routines
24626 @item Possibility of inlining a subprogram comprising assembler code
24627 @item Code optimizer can take Inline Assembler code into account
24628 @end itemize
24629
24630 This chapter presents a series of examples to show you how to use
24631 the Inline Assembler.  Although it focuses on the Intel x86,
24632 the general approach applies also to other processors.
24633 It is assumed that you are familiar with Ada
24634 and with assembly language programming.
24635
24636 @menu
24637 * Basic Assembler Syntax::
24638 * A Simple Example of Inline Assembler::
24639 * Output Variables in Inline Assembler::
24640 * Input Variables in Inline Assembler::
24641 * Inlining Inline Assembler Code::
24642 * Other Asm Functionality::
24643 @end menu
24644
24645 @c ---------------------------------------------------------------------------
24646 @node Basic Assembler Syntax
24647 @section Basic Assembler Syntax
24648
24649 @noindent
24650 The assembler used by GNAT and gcc is based not on the Intel assembly
24651 language, but rather on a language that descends from the AT&T Unix
24652 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24653 The following table summarizes the main features of @emph{as} syntax
24654 and points out the differences from the Intel conventions.
24655 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24656 pre-processor) documentation for further information.
24657
24658 @table @asis
24659 @item Register names
24660 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24661 @*
24662 Intel: No extra punctuation; for example @code{eax}
24663
24664 @item Immediate operand
24665 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24666 @*
24667 Intel: No extra punctuation; for example @code{4}
24668
24669 @item Address
24670 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24671 @*
24672 Intel: No extra punctuation; for example @code{loc}
24673
24674 @item Memory contents
24675 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24676 @*
24677 Intel: Square brackets; for example @code{[loc]}
24678
24679 @item Register contents
24680 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24681 @*
24682 Intel: Square brackets; for example @code{[eax]}
24683
24684 @item Hexadecimal numbers
24685 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24686 @*
24687 Intel: Trailing ``h''; for example @code{A0h}
24688
24689 @item Operand size
24690 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24691 a 16-bit word
24692 @*
24693 Intel: Implicit, deduced by assembler; for example @code{mov}
24694
24695 @item Instruction repetition
24696 gcc / @emph{as}: Split into two lines; for example
24697 @*
24698 @code{rep}
24699 @*
24700 @code{stosl}
24701 @*
24702 Intel: Keep on one line; for example @code{rep stosl}
24703
24704 @item Order of operands
24705 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24706 @*
24707 Intel: Destination first; for example @code{mov eax, 4}
24708 @end table
24709
24710 @c ---------------------------------------------------------------------------
24711 @node A Simple Example of Inline Assembler
24712 @section A Simple Example of Inline Assembler
24713
24714 @noindent
24715 The following example will generate a single assembly language statement,
24716 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24717 the example will be useful in illustrating the basics of
24718 the Inline Assembler facility.
24719
24720 @smallexample @c ada
24721 @group
24722 with System.Machine_Code; use System.Machine_Code;
24723 procedure Nothing is
24724 begin
24725    Asm ("nop");
24726 end Nothing;
24727 @end group
24728 @end smallexample
24729
24730 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24731 here it takes one parameter, a @emph{template string} that must be a static
24732 expression and that will form the generated instruction.
24733 @code{Asm} may be regarded as a compile-time procedure that parses
24734 the template string and additional parameters (none here),
24735 from which it generates a sequence of assembly language instructions.
24736
24737 The examples in this chapter will illustrate several of the forms
24738 for invoking @code{Asm}; a complete specification of the syntax
24739 is found in the @cite{GNAT Reference Manual}.
24740
24741 Under the standard GNAT conventions, the @code{Nothing} procedure
24742 should be in a file named @file{nothing.adb}.
24743 You can build the executable in the usual way:
24744 @smallexample
24745 gnatmake nothing
24746 @end smallexample
24747 However, the interesting aspect of this example is not its run-time behavior
24748 but rather the generated assembly code.
24749 To see this output, invoke the compiler as follows:
24750 @smallexample
24751    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24752 @end smallexample
24753 where the options are:
24754
24755 @table @code
24756 @item -c
24757 compile only (no bind or link)
24758 @item -S
24759 generate assembler listing
24760 @item -fomit-frame-pointer
24761 do not set up separate stack frames
24762 @item -gnatp
24763 do not add runtime checks
24764 @end table
24765
24766 This gives a human-readable assembler version of the code. The resulting
24767 file will have the same name as the Ada source file, but with a @code{.s}
24768 extension. In our example, the file @file{nothing.s} has the following
24769 contents:
24770
24771 @smallexample
24772 @group
24773 .file "nothing.adb"
24774 gcc2_compiled.:
24775 ___gnu_compiled_ada:
24776 .text
24777    .align 4
24778 .globl __ada_nothing
24779 __ada_nothing:
24780 #APP
24781    nop
24782 #NO_APP
24783    jmp L1
24784    .align 2,0x90
24785 L1:
24786    ret
24787 @end group
24788 @end smallexample
24789
24790 The assembly code you included is clearly indicated by
24791 the compiler, between the @code{#APP} and @code{#NO_APP}
24792 delimiters. The character before the 'APP' and 'NOAPP'
24793 can differ on different targets. For example, GNU/Linux uses '#APP' while
24794 on NT you will see '/APP'.
24795
24796 If you make a mistake in your assembler code (such as using the
24797 wrong size modifier, or using a wrong operand for the instruction) GNAT
24798 will report this error in a temporary file, which will be deleted when
24799 the compilation is finished.  Generating an assembler file will help
24800 in such cases, since you can assemble this file separately using the
24801 @emph{as} assembler that comes with gcc.
24802
24803 Assembling the file using the command
24804
24805 @smallexample
24806 as @file{nothing.s}
24807 @end smallexample
24808 @noindent
24809 will give you error messages whose lines correspond to the assembler
24810 input file, so you can easily find and correct any mistakes you made.
24811 If there are no errors, @emph{as} will generate an object file
24812 @file{nothing.out}.
24813
24814 @c ---------------------------------------------------------------------------
24815 @node Output Variables in Inline Assembler
24816 @section Output Variables in Inline Assembler
24817
24818 @noindent
24819 The examples in this section, showing how to access the processor flags,
24820 illustrate how to specify the destination operands for assembly language
24821 statements.
24822
24823 @smallexample @c ada
24824 @group
24825 with Interfaces; use Interfaces;
24826 with Ada.Text_IO; use Ada.Text_IO;
24827 with System.Machine_Code; use System.Machine_Code;
24828 procedure Get_Flags is
24829    Flags : Unsigned_32;
24830    use ASCII;
24831 begin
24832    Asm ("pushfl"          & LF & HT & -- push flags on stack
24833         "popl %%eax"      & LF & HT & -- load eax with flags
24834         "movl %%eax, %0",             -- store flags in variable
24835         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24836    Put_Line ("Flags register:" & Flags'Img);
24837 end Get_Flags;
24838 @end group
24839 @end smallexample
24840
24841 In order to have a nicely aligned assembly listing, we have separated
24842 multiple assembler statements in the Asm template string with linefeed
24843 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24844 The resulting section of the assembly output file is:
24845
24846 @smallexample
24847 @group
24848 #APP
24849    pushfl
24850    popl %eax
24851    movl %eax, -40(%ebp)
24852 #NO_APP
24853 @end group
24854 @end smallexample
24855
24856 It would have been legal to write the Asm invocation as:
24857
24858 @smallexample
24859 Asm ("pushfl popl %%eax movl %%eax, %0")
24860 @end smallexample
24861
24862 but in the generated assembler file, this would come out as:
24863
24864 @smallexample
24865 #APP
24866    pushfl popl %eax movl %eax, -40(%ebp)
24867 #NO_APP
24868 @end smallexample
24869
24870 which is not so convenient for the human reader.
24871
24872 We use Ada comments
24873 at the end of each line to explain what the assembler instructions
24874 actually do.  This is a useful convention.
24875
24876 When writing Inline Assembler instructions, you need to precede each register
24877 and variable name with a percent sign.  Since the assembler already requires
24878 a percent sign at the beginning of a register name, you need two consecutive
24879 percent signs for such names in the Asm template string, thus @code{%%eax}.
24880 In the generated assembly code, one of the percent signs will be stripped off.
24881
24882 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24883 variables: operands you later define using @code{Input} or @code{Output}
24884 parameters to @code{Asm}.
24885 An output variable is illustrated in
24886 the third statement in the Asm template string:
24887 @smallexample
24888 movl %%eax, %0
24889 @end smallexample
24890 The intent is to store the contents of the eax register in a variable that can
24891 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24892 necessarily work, since the compiler might optimize by using a register
24893 to hold Flags, and the expansion of the @code{movl} instruction would not be
24894 aware of this optimization.  The solution is not to store the result directly
24895 but rather to advise the compiler to choose the correct operand form;
24896 that is the purpose of the @code{%0} output variable.
24897
24898 Information about the output variable is supplied in the @code{Outputs}
24899 parameter to @code{Asm}:
24900 @smallexample
24901 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24902 @end smallexample
24903
24904 The output is defined by the @code{Asm_Output} attribute of the target type;
24905 the general format is
24906 @smallexample
24907 Type'Asm_Output (constraint_string, variable_name)
24908 @end smallexample
24909
24910 The constraint string directs the compiler how
24911 to store/access the associated variable.  In the example
24912 @smallexample
24913 Unsigned_32'Asm_Output ("=m", Flags);
24914 @end smallexample
24915 the @code{"m"} (memory) constraint tells the compiler that the variable
24916 @code{Flags} should be stored in a memory variable, thus preventing
24917 the optimizer from keeping it in a register.  In contrast,
24918 @smallexample
24919 Unsigned_32'Asm_Output ("=r", Flags);
24920 @end smallexample
24921 uses the @code{"r"} (register) constraint, telling the compiler to
24922 store the variable in a register.
24923
24924 If the constraint is preceded by the equal character (@strong{=}), it tells
24925 the compiler that the variable will be used to store data into it.
24926
24927 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24928 allowing the optimizer to choose whatever it deems best.
24929
24930 There are a fairly large number of constraints, but the ones that are
24931 most useful (for the Intel x86 processor) are the following:
24932
24933 @table @code
24934 @item =
24935 output constraint
24936 @item g
24937 global (i.e. can be stored anywhere)
24938 @item m
24939 in memory
24940 @item I
24941 a constant
24942 @item a
24943 use eax
24944 @item b
24945 use ebx
24946 @item c
24947 use ecx
24948 @item d
24949 use edx
24950 @item S
24951 use esi
24952 @item D
24953 use edi
24954 @item r
24955 use one of eax, ebx, ecx or edx
24956 @item q
24957 use one of eax, ebx, ecx, edx, esi or edi
24958 @end table
24959
24960 The full set of constraints is described in the gcc and @emph{as}
24961 documentation; note that it is possible to combine certain constraints
24962 in one constraint string.
24963
24964 You specify the association of an output variable with an assembler operand
24965 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24966 integer.  Thus in
24967 @smallexample @c ada
24968 @group
24969 Asm ("pushfl"          & LF & HT & -- push flags on stack
24970      "popl %%eax"      & LF & HT & -- load eax with flags
24971      "movl %%eax, %0",             -- store flags in variable
24972      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24973 @end group
24974 @end smallexample
24975 @noindent
24976 @code{%0} will be replaced in the expanded code by the appropriate operand,
24977 whatever
24978 the compiler decided for the @code{Flags} variable.
24979
24980 In general, you may have any number of output variables:
24981 @itemize @bullet
24982 @item
24983 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24984 @item
24985 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24986 of @code{Asm_Output} attributes
24987 @end itemize
24988
24989 For example:
24990 @smallexample @c ada
24991 @group
24992 Asm ("movl %%eax, %0" & LF & HT &
24993      "movl %%ebx, %1" & LF & HT &
24994      "movl %%ecx, %2",
24995      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24996                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24997                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24998 @end group
24999 @end smallexample
25000 @noindent
25001 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25002 in the Ada program.
25003
25004 As a variation on the @code{Get_Flags} example, we can use the constraints
25005 string to direct the compiler to store the eax register into the @code{Flags}
25006 variable, instead of including the store instruction explicitly in the
25007 @code{Asm} template string:
25008
25009 @smallexample @c ada
25010 @group
25011 with Interfaces; use Interfaces;
25012 with Ada.Text_IO; use Ada.Text_IO;
25013 with System.Machine_Code; use System.Machine_Code;
25014 procedure Get_Flags_2 is
25015    Flags : Unsigned_32;
25016    use ASCII;
25017 begin
25018    Asm ("pushfl"      & LF & HT & -- push flags on stack
25019         "popl %%eax",             -- save flags in eax
25020         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25021    Put_Line ("Flags register:" & Flags'Img);
25022 end Get_Flags_2;
25023 @end group
25024 @end smallexample
25025
25026 @noindent
25027 The @code{"a"} constraint tells the compiler that the @code{Flags}
25028 variable will come from the eax register. Here is the resulting code:
25029
25030 @smallexample
25031 @group
25032 #APP
25033    pushfl
25034    popl %eax
25035 #NO_APP
25036    movl %eax,-40(%ebp)
25037 @end group
25038 @end smallexample
25039
25040 @noindent
25041 The compiler generated the store of eax into Flags after
25042 expanding the assembler code.
25043
25044 Actually, there was no need to pop the flags into the eax register;
25045 more simply, we could just pop the flags directly into the program variable:
25046
25047 @smallexample @c ada
25048 @group
25049 with Interfaces; use Interfaces;
25050 with Ada.Text_IO; use Ada.Text_IO;
25051 with System.Machine_Code; use System.Machine_Code;
25052 procedure Get_Flags_3 is
25053    Flags : Unsigned_32;
25054    use ASCII;
25055 begin
25056    Asm ("pushfl"  & LF & HT & -- push flags on stack
25057         "pop %0",             -- save flags in Flags
25058         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25059    Put_Line ("Flags register:" & Flags'Img);
25060 end Get_Flags_3;
25061 @end group
25062 @end smallexample
25063
25064 @c ---------------------------------------------------------------------------
25065 @node Input Variables in Inline Assembler
25066 @section Input Variables in Inline Assembler
25067
25068 @noindent
25069 The example in this section illustrates how to specify the source operands
25070 for assembly language statements.
25071 The program simply increments its input value by 1:
25072
25073 @smallexample @c ada
25074 @group
25075 with Interfaces; use Interfaces;
25076 with Ada.Text_IO; use Ada.Text_IO;
25077 with System.Machine_Code; use System.Machine_Code;
25078 procedure Increment is
25079
25080    function Incr (Value : Unsigned_32) return Unsigned_32 is
25081       Result : Unsigned_32;
25082    begin
25083       Asm ("incl %0",
25084            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25085            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25086       return Result;
25087    end Incr;
25088
25089    Value : Unsigned_32;
25090
25091 begin
25092    Value := 5;
25093    Put_Line ("Value before is" & Value'Img);
25094    Value := Incr (Value);
25095    Put_Line ("Value after is" & Value'Img);
25096 end Increment;
25097 @end group
25098 @end smallexample
25099
25100 The @code{Outputs} parameter to @code{Asm} specifies
25101 that the result will be in the eax register and that it is to be stored
25102 in the @code{Result} variable.
25103
25104 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25105 but with an @code{Asm_Input} attribute.
25106 The @code{"="} constraint, indicating an output value, is not present.
25107
25108 You can have multiple input variables, in the same way that you can have more
25109 than one output variable.
25110
25111 The parameter count (%0, %1) etc, now starts at the first input
25112 statement, and continues with the output statements.
25113 When both parameters use the same variable, the
25114 compiler will treat them as the same %n operand, which is the case here.
25115
25116 Just as the @code{Outputs} parameter causes the register to be stored into the
25117 target variable after execution of the assembler statements, so does the
25118 @code{Inputs} parameter cause its variable to be loaded into the register
25119 before execution of the assembler statements.
25120
25121 Thus the effect of the @code{Asm} invocation is:
25122 @enumerate
25123 @item load the 32-bit value of @code{Value} into eax
25124 @item execute the @code{incl %eax} instruction
25125 @item store the contents of eax into the @code{Result} variable
25126 @end enumerate
25127
25128 The resulting assembler file (with @option{-O2} optimization) contains:
25129 @smallexample
25130 @group
25131 _increment__incr.1:
25132    subl $4,%esp
25133    movl 8(%esp),%eax
25134 #APP
25135    incl %eax
25136 #NO_APP
25137    movl %eax,%edx
25138    movl %ecx,(%esp)
25139    addl $4,%esp
25140    ret
25141 @end group
25142 @end smallexample
25143
25144 @c ---------------------------------------------------------------------------
25145 @node Inlining Inline Assembler Code
25146 @section Inlining Inline Assembler Code
25147
25148 @noindent
25149 For a short subprogram such as the @code{Incr} function in the previous
25150 section, the overhead of the call and return (creating / deleting the stack
25151 frame) can be significant, compared to the amount of code in the subprogram
25152 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25153 which directs the compiler to expand invocations of the subprogram at the
25154 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25155 Here is the resulting program:
25156
25157 @smallexample @c ada
25158 @group
25159 with Interfaces; use Interfaces;
25160 with Ada.Text_IO; use Ada.Text_IO;
25161 with System.Machine_Code; use System.Machine_Code;
25162 procedure Increment_2 is
25163
25164    function Incr (Value : Unsigned_32) return Unsigned_32 is
25165       Result : Unsigned_32;
25166    begin
25167       Asm ("incl %0",
25168            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25169            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25170       return Result;
25171    end Incr;
25172    pragma Inline (Increment);
25173
25174    Value : Unsigned_32;
25175
25176 begin
25177    Value := 5;
25178    Put_Line ("Value before is" & Value'Img);
25179    Value := Increment (Value);
25180    Put_Line ("Value after is" & Value'Img);
25181 end Increment_2;
25182 @end group
25183 @end smallexample
25184
25185 Compile the program with both optimization (@option{-O2}) and inlining
25186 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25187
25188 The @code{Incr} function is still compiled as usual, but at the
25189 point in @code{Increment} where our function used to be called:
25190
25191 @smallexample
25192 @group
25193 pushl %edi
25194 call _increment__incr.1
25195 @end group
25196 @end smallexample
25197
25198 @noindent
25199 the code for the function body directly appears:
25200
25201 @smallexample
25202 @group
25203 movl %esi,%eax
25204 #APP
25205    incl %eax
25206 #NO_APP
25207    movl %eax,%edx
25208 @end group
25209 @end smallexample
25210
25211 @noindent
25212 thus saving the overhead of stack frame setup and an out-of-line call.
25213
25214 @c ---------------------------------------------------------------------------
25215 @node Other Asm Functionality
25216 @section Other @code{Asm} Functionality
25217
25218 @noindent
25219 This section describes two important parameters to the @code{Asm}
25220 procedure: @code{Clobber}, which identifies register usage;
25221 and @code{Volatile}, which inhibits unwanted optimizations.
25222
25223 @menu
25224 * The Clobber Parameter::
25225 * The Volatile Parameter::
25226 @end menu
25227
25228 @c ---------------------------------------------------------------------------
25229 @node The Clobber Parameter
25230 @subsection The @code{Clobber} Parameter
25231
25232 @noindent
25233 One of the dangers of intermixing assembly language and a compiled language
25234 such as Ada is that the compiler needs to be aware of which registers are
25235 being used by the assembly code.  In some cases, such as the earlier examples,
25236 the constraint string is sufficient to indicate register usage (e.g.,
25237 @code{"a"} for
25238 the eax register).  But more generally, the compiler needs an explicit
25239 identification of the registers that are used by the Inline Assembly
25240 statements.
25241
25242 Using a register that the compiler doesn't know about
25243 could be a side effect of an instruction (like @code{mull}
25244 storing its result in both eax and edx).
25245 It can also arise from explicit register usage in your
25246 assembly code; for example:
25247 @smallexample
25248 @group
25249 Asm ("movl %0, %%ebx" & LF & HT &
25250      "movl %%ebx, %1",
25251      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25252      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25253 @end group
25254 @end smallexample
25255 @noindent
25256 where the compiler (since it does not analyze the @code{Asm} template string)
25257 does not know you are using the ebx register.
25258
25259 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25260 to identify the registers that will be used by your assembly code:
25261
25262 @smallexample
25263 @group
25264 Asm ("movl %0, %%ebx" & LF & HT &
25265      "movl %%ebx, %1",
25266      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25267      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25268      Clobber => "ebx");
25269 @end group
25270 @end smallexample
25271
25272 The Clobber parameter is a static string expression specifying the
25273 register(s) you are using.  Note that register names are @emph{not} prefixed
25274 by a percent sign. Also, if more than one register is used then their names
25275 are separated by commas; e.g., @code{"eax, ebx"}
25276
25277 The @code{Clobber} parameter has several additional uses:
25278 @enumerate
25279 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25280 @item Use ``register'' name @code{memory} if you changed a memory location
25281 @end enumerate
25282
25283 @c ---------------------------------------------------------------------------
25284 @node The Volatile Parameter
25285 @subsection The @code{Volatile} Parameter
25286 @cindex Volatile parameter
25287
25288 @noindent
25289 Compiler optimizations in the presence of Inline Assembler may sometimes have
25290 unwanted effects.  For example, when an @code{Asm} invocation with an input
25291 variable is inside a loop, the compiler might move the loading of the input
25292 variable outside the loop, regarding it as a one-time initialization.
25293
25294 If this effect is not desired, you can disable such optimizations by setting
25295 the @code{Volatile} parameter to @code{True}; for example:
25296
25297 @smallexample @c ada
25298 @group
25299 Asm ("movl %0, %%ebx" & LF & HT &
25300      "movl %%ebx, %1",
25301      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25302      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25303      Clobber  => "ebx",
25304      Volatile => True);
25305 @end group
25306 @end smallexample
25307
25308 By default, @code{Volatile} is set to @code{False} unless there is no
25309 @code{Outputs} parameter.
25310
25311 Although setting @code{Volatile} to @code{True} prevents unwanted
25312 optimizations, it will also disable other optimizations that might be
25313 important for efficiency. In general, you should set @code{Volatile}
25314 to @code{True} only if the compiler's optimizations have created
25315 problems.
25316 @c END OF INLINE ASSEMBLER CHAPTER
25317 @c ===============================
25318
25319 @c ***********************************
25320 @c * Compatibility and Porting Guide *
25321 @c ***********************************
25322 @node Compatibility and Porting Guide
25323 @appendix Compatibility and Porting Guide
25324
25325 @noindent
25326 This chapter describes the compatibility issues that may arise between
25327 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25328 can expedite porting
25329 applications developed in other Ada environments.
25330
25331 @menu
25332 * Compatibility with Ada 83::
25333 * Implementation-dependent characteristics::
25334 * Compatibility with Other Ada 95 Systems::
25335 * Representation Clauses::
25336 * Compatibility with DEC Ada 83::
25337 @ifset vms
25338 * Transitioning from Alpha to Integrity OpenVMS::
25339 @end ifset
25340 @end menu
25341
25342 @node Compatibility with Ada 83
25343 @section Compatibility with Ada 83
25344 @cindex Compatibility (between Ada 83 and Ada 95)
25345
25346 @noindent
25347 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25348 particular, the design intention is that the difficulties associated
25349 with moving from Ada 83 to Ada 95 should be no greater than those
25350 that occur when moving from one Ada 83 system to another.
25351
25352 However, there are a number of points at which there are minor
25353 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25354 full details of these issues,
25355 and should be consulted for a complete treatment.
25356 In practice the
25357 following subsections treat the most likely issues to be encountered.
25358
25359 @menu
25360 * Legal Ada 83 programs that are illegal in Ada 95::
25361 * More deterministic semantics::
25362 * Changed semantics::
25363 * Other language compatibility issues::
25364 @end menu
25365
25366 @node Legal Ada 83 programs that are illegal in Ada 95
25367 @subsection Legal Ada 83 programs that are illegal in Ada 95
25368
25369 @table @asis
25370 @item Character literals
25371 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25372 @code{Wide_Character} as a new predefined character type, some uses of
25373 character literals that were legal in Ada 83 are illegal in Ada 95.
25374 For example:
25375 @smallexample @c ada
25376    for Char in 'A' .. 'Z' loop ... end loop;
25377 @end smallexample
25378 @noindent
25379 The problem is that @code{'A'} and @code{'Z'} could be from either
25380 @code{Character} or @code{Wide_Character}.  The simplest correction
25381 is to make the type explicit; e.g.:
25382 @smallexample @c ada
25383    for Char in Character range 'A' .. 'Z' loop ... end loop;
25384 @end smallexample
25385
25386 @item New reserved words
25387 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25388 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25389 Existing Ada 83 code using any of these identifiers must be edited to
25390 use some alternative name.
25391
25392 @item Freezing rules
25393 The rules in Ada 95 are slightly different with regard to the point at
25394 which entities are frozen, and representation pragmas and clauses are
25395 not permitted past the freeze point.  This shows up most typically in
25396 the form of an error message complaining that a representation item
25397 appears too late, and the appropriate corrective action is to move
25398 the item nearer to the declaration of the entity to which it refers.
25399
25400 A particular case is that representation pragmas
25401 @ifset vms
25402 (including the
25403 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25404 @end ifset
25405 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25406 declaration must be introduced to which the pragma can be applied.
25407
25408 @item Optional bodies for library packages
25409 In Ada 83, a package that did not require a package body was nevertheless
25410 allowed to have one.  This lead to certain surprises in compiling large
25411 systems (situations in which the body could be unexpectedly ignored by the
25412 binder).  In Ada 95, if a package does not require a body then it is not
25413 permitted to have a body.  To fix this problem, simply remove a redundant
25414 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25415 into the spec that makes the body required.  One approach is to add a private
25416 part to the package declaration (if necessary), and define a parameterless
25417 procedure called @code{Requires_Body}, which must then be given a dummy
25418 procedure body in the package body, which then becomes required.
25419 Another approach (assuming that this does not introduce elaboration
25420 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25421 since one effect of this pragma is to require the presence of a package body.
25422
25423 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25424 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25425 @code{Constraint_Error}.
25426 This means that it is illegal to have separate exception handlers for
25427 the two exceptions.  The fix is simply to remove the handler for the
25428 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25429 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25430
25431 @item Indefinite subtypes in generics
25432 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25433 as the actual for a generic formal private type, but then the instantiation
25434 would be illegal if there were any instances of declarations of variables
25435 of this type in the generic body.  In Ada 95, to avoid this clear violation
25436 of the methodological principle known as the ``contract model'',
25437 the generic declaration explicitly indicates whether
25438 or not such instantiations are permitted.  If a generic formal parameter
25439 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25440 type name, then it can be instantiated with indefinite types, but no
25441 stand-alone variables can be declared of this type.  Any attempt to declare
25442 such a variable will result in an illegality at the time the generic is
25443 declared.  If the @code{(<>)} notation is not used, then it is illegal
25444 to instantiate the generic with an indefinite type.
25445 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25446 It will show up as a compile time error, and
25447 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25448 @end table
25449
25450 @node More deterministic semantics
25451 @subsection More deterministic semantics
25452
25453 @table @asis
25454 @item Conversions
25455 Conversions from real types to integer types round away from 0.  In Ada 83
25456 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25457 implementation freedom was intended to support unbiased rounding in
25458 statistical applications, but in practice it interfered with portability.
25459 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25460 is required.  Numeric code may be affected by this change in semantics.
25461 Note, though, that this issue is no worse than already existed in Ada 83
25462 when porting code from one vendor to another.
25463
25464 @item Tasking
25465 The Real-Time Annex introduces a set of policies that define the behavior of
25466 features that were implementation dependent in Ada 83, such as the order in
25467 which open select branches are executed.
25468 @end table
25469
25470 @node Changed semantics
25471 @subsection Changed semantics
25472
25473 @noindent
25474 The worst kind of incompatibility is one where a program that is legal in
25475 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25476 possible in Ada 83.  Fortunately this is extremely rare, but the one
25477 situation that you should be alert to is the change in the predefined type
25478 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25479
25480 @table @asis
25481 @item range of @code{Character}
25482 The range of @code{Standard.Character} is now the full 256 characters
25483 of Latin-1, whereas in most Ada 83 implementations it was restricted
25484 to 128 characters. Although some of the effects of
25485 this change will be manifest in compile-time rejection of legal
25486 Ada 83 programs it is possible for a working Ada 83 program to have
25487 a different effect in Ada 95, one that was not permitted in Ada 83.
25488 As an example, the expression
25489 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25490 delivers @code{255} as its value.
25491 In general, you should look at the logic of any
25492 character-processing Ada 83 program and see whether it needs to be adapted
25493 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25494 character handling package that may be relevant if code needs to be adapted
25495 to account for the additional Latin-1 elements.
25496 The desirable fix is to
25497 modify the program to accommodate the full character set, but in some cases
25498 it may be convenient to define a subtype or derived type of Character that
25499 covers only the restricted range.
25500 @cindex Latin-1
25501 @end table
25502
25503 @node Other language compatibility issues
25504 @subsection Other language compatibility issues
25505 @table @asis
25506 @item @option{-gnat83 switch}
25507 All implementations of GNAT provide a switch that causes GNAT to operate
25508 in Ada 83 mode.  In this mode, some but not all compatibility problems
25509 of the type described above are handled automatically.  For example, the
25510 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25511 However,
25512 in practice, it is usually advisable to make the necessary modifications
25513 to the program to remove the need for using this switch.
25514 See @ref{Compiling Different Versions of Ada}.
25515
25516 @item Support for removed Ada 83 pragmas and attributes
25517 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25518 generally because they have been replaced by other mechanisms.  Ada 95
25519 compilers are allowed, but not required, to implement these missing
25520 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25521 such pragmas and attributes, eliminating this compatibility concern.  These
25522 include @code{pragma Interface} and the floating point type attributes
25523 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25524 @end table
25525
25526 @node Implementation-dependent characteristics
25527 @section Implementation-dependent characteristics
25528 @noindent
25529 Although the Ada language defines the semantics of each construct as
25530 precisely as practical, in some situations (for example for reasons of
25531 efficiency, or where the effect is heavily dependent on the host or target
25532 platform) the implementation is allowed some freedom.  In porting Ada 83
25533 code to GNAT, you need to be aware of whether / how the existing code
25534 exercised such implementation dependencies.  Such characteristics fall into
25535 several categories, and GNAT offers specific support in assisting the
25536 transition from certain Ada 83 compilers.
25537
25538 @menu
25539 * Implementation-defined pragmas::
25540 * Implementation-defined attributes::
25541 * Libraries::
25542 * Elaboration order::
25543 * Target-specific aspects::
25544 @end menu
25545
25546 @node Implementation-defined pragmas
25547 @subsection Implementation-defined pragmas
25548
25549 @noindent
25550 Ada compilers are allowed to supplement the language-defined pragmas, and
25551 these are a potential source of non-portability.  All GNAT-defined pragmas
25552 are described in the GNAT Reference Manual, and these include several that
25553 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25554 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25555 For
25556 compatibility with DEC Ada 83, GNAT supplies the pragmas
25557 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25558 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25559 and @code{Volatile}.
25560 Other relevant pragmas include @code{External} and @code{Link_With}.
25561 Some vendor-specific
25562 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25563 recognized, thus
25564 avoiding compiler rejection of units that contain such pragmas; they are not
25565 relevant in a GNAT context and hence are not otherwise implemented.
25566
25567 @node Implementation-defined attributes
25568 @subsection Implementation-defined attributes
25569
25570 Analogous to pragmas, the set of attributes may be extended by an
25571 implementation.  All GNAT-defined attributes are described in the
25572 @cite{GNAT Reference Manual}, and these include several that are specifically
25573 intended
25574 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25575 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25576 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25577 @code{Type_Class}.
25578
25579 @node Libraries
25580 @subsection Libraries
25581 @noindent
25582 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25583 code uses vendor-specific libraries then there are several ways to manage
25584 this in Ada 95:
25585 @enumerate
25586 @item
25587 If the source code for the libraries (specifications and bodies) are
25588 available, then the libraries can be migrated in the same way as the
25589 application.
25590 @item
25591 If the source code for the specifications but not the bodies are
25592 available, then you can reimplement the bodies.
25593 @item
25594 Some new Ada 95 features obviate the need for library support.  For
25595 example most Ada 83 vendors supplied a package for unsigned integers.  The
25596 Ada 95 modular type feature is the preferred way to handle this need, so
25597 instead of migrating or reimplementing the unsigned integer package it may
25598 be preferable to retrofit the application using modular types.
25599 @end enumerate
25600
25601 @node Elaboration order
25602 @subsection Elaboration order
25603 @noindent
25604 The implementation can choose any elaboration order consistent with the unit
25605 dependency relationship.  This freedom means that some orders can result in
25606 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25607 to invoke a subprogram its body has been elaborated, or to instantiate a
25608 generic before the generic body has been elaborated.  By default GNAT
25609 attempts to choose a safe order (one that will not encounter access before
25610 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25611 needed.  However, this can lead to the creation of elaboration circularities
25612 and a resulting rejection of the program by gnatbind.  This issue is
25613 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25614 In brief, there are several
25615 ways to deal with this situation:
25616
25617 @itemize @bullet
25618 @item
25619 Modify the program to eliminate the circularities, e.g. by moving
25620 elaboration-time code into explicitly-invoked procedures
25621 @item
25622 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25623 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25624 @code{Elaborate_All}
25625 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25626 (by selectively suppressing elaboration checks via pragma
25627 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25628 @end itemize
25629
25630 @node Target-specific aspects
25631 @subsection Target-specific aspects
25632 @noindent
25633 Low-level applications need to deal with machine addresses, data
25634 representations, interfacing with assembler code, and similar issues.  If
25635 such an Ada 83 application is being ported to different target hardware (for
25636 example where the byte endianness has changed) then you will need to
25637 carefully examine the program logic; the porting effort will heavily depend
25638 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25639 incompatible with typical Ada 83 compiler practices regarding implicit
25640 packing, the meaning of the Size attribute, and the size of access values.
25641 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25642
25643 @node Compatibility with Other Ada 95 Systems
25644 @section Compatibility with Other Ada 95 Systems
25645
25646 @noindent
25647 Providing that programs avoid the use of implementation dependent and
25648 implementation defined features of Ada 95, as documented in the Ada 95
25649 reference manual, there should be a high degree of portability between
25650 GNAT and other Ada 95 systems.  The following are specific items which
25651 have proved troublesome in moving GNAT programs to other Ada 95
25652 compilers, but do not affect porting code to GNAT@.
25653
25654 @table @asis
25655 @item Ada 83 Pragmas and Attributes
25656 Ada 95 compilers are allowed, but not required, to implement the missing
25657 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25658 GNAT implements all such pragmas and attributes, eliminating this as
25659 a compatibility concern, but some other Ada 95 compilers reject these
25660 pragmas and attributes.
25661
25662 @item Special-needs Annexes
25663 GNAT implements the full set of special needs annexes.  At the
25664 current time, it is the only Ada 95 compiler to do so.  This means that
25665 programs making use of these features may not be portable to other Ada
25666 95 compilation systems.
25667
25668 @item Representation Clauses
25669 Some other Ada 95 compilers implement only the minimal set of
25670 representation clauses required by the Ada 95 reference manual.  GNAT goes
25671 far beyond this minimal set, as described in the next section.
25672 @end table
25673
25674 @node Representation Clauses
25675 @section Representation Clauses
25676
25677 @noindent
25678 The Ada 83 reference manual was quite vague in describing both the minimal
25679 required implementation of representation clauses, and also their precise
25680 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25681 set of capabilities required in Ada 95 is quite limited.
25682
25683 GNAT implements the full required set of capabilities described in the
25684 Ada 95 reference manual, but also goes much beyond this, and in particular
25685 an effort has been made to be compatible with existing Ada 83 usage to the
25686 greatest extent possible.
25687
25688 A few cases exist in which Ada 83 compiler behavior is incompatible with
25689 requirements in the Ada 95 reference manual.  These are instances of
25690 intentional or accidental dependence on specific implementation dependent
25691 characteristics of these Ada 83 compilers.  The following is a list of
25692 the cases most likely to arise in existing legacy Ada 83 code.
25693
25694 @table @asis
25695 @item Implicit Packing
25696 Some Ada 83 compilers allowed a Size specification to cause implicit
25697 packing of an array or record.  This could cause expensive implicit
25698 conversions for change of representation in the presence of derived
25699 types, and the Ada design intends to avoid this possibility.
25700 Subsequent AI's were issued to make it clear that such implicit
25701 change of representation in response to a Size clause is inadvisable,
25702 and this recommendation is represented explicitly in the Ada 95 RM
25703 as implementation advice that is followed by GNAT@.
25704 The problem will show up as an error
25705 message rejecting the size clause.  The fix is simply to provide
25706 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25707 a Component_Size clause.
25708
25709 @item Meaning of Size Attribute
25710 The Size attribute in Ada 95 for discrete types is defined as being the
25711 minimal number of bits required to hold values of the type.  For example,
25712 on a 32-bit machine, the size of Natural will typically be 31 and not
25713 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25714 some 32 in this situation.  This problem will usually show up as a compile
25715 time error, but not always.  It is a good idea to check all uses of the
25716 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25717 Object_Size can provide a useful way of duplicating the behavior of
25718 some Ada 83 compiler systems.
25719
25720 @item Size of Access Types
25721 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25722 and that therefore it will be the same size as a System.Address value.  This
25723 assumption is true for GNAT in most cases with one exception.  For the case of
25724 a pointer to an unconstrained array type (where the bounds may vary from one
25725 value of the access type to another), the default is to use a ``fat pointer'',
25726 which is represented as two separate pointers, one to the bounds, and one to
25727 the array.  This representation has a number of advantages, including improved
25728 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25729 code which makes the assumption that, for example, pointers fit in 32 bits on
25730 a machine with 32-bit addressing.
25731
25732 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25733 access types in this case (where the designated type is an unconstrained array
25734 type).  These thin pointers are indeed the same size as a System.Address value.
25735 To specify a thin pointer, use a size clause for the type, for example:
25736
25737 @smallexample @c ada
25738 type X is access all String;
25739 for X'Size use Standard'Address_Size;
25740 @end smallexample
25741
25742 @noindent
25743 which will cause the type X to be represented using a single pointer.
25744 When using this representation, the bounds are right behind the array.
25745 This representation is slightly less efficient, and does not allow quite
25746 such flexibility in the use of foreign pointers or in using the
25747 Unrestricted_Access attribute to create pointers to non-aliased objects.
25748 But for any standard portable use of the access type it will work in
25749 a functionally correct manner and allow porting of existing code.
25750 Note that another way of forcing a thin pointer representation
25751 is to use a component size clause for the element size in an array,
25752 or a record representation clause for an access field in a record.
25753 @end table
25754
25755 @node Compatibility with DEC Ada 83
25756 @section Compatibility with DEC Ada 83
25757
25758 @noindent
25759 The VMS version of GNAT fully implements all the pragmas and attributes
25760 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25761 libraries, including Starlet.  In addition, data layouts and parameter
25762 passing conventions are highly compatible.  This means that porting
25763 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25764 most other porting efforts.  The following are some of the most
25765 significant differences between GNAT and DEC Ada 83.
25766
25767 @table @asis
25768 @item Default floating-point representation
25769 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25770 it is VMS format.  GNAT does implement the necessary pragmas
25771 (Long_Float, Float_Representation) for changing this default.
25772
25773 @item System
25774 The package System in GNAT exactly corresponds to the definition in the
25775 Ada 95 reference manual, which means that it excludes many of the
25776 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25777 that contains the additional definitions, and a special pragma,
25778 Extend_System allows this package to be treated transparently as an
25779 extension of package System.
25780
25781 @item To_Address
25782 The definitions provided by Aux_DEC are exactly compatible with those
25783 in the DEC Ada 83 version of System, with one exception.
25784 DEC Ada provides the following declarations:
25785
25786 @smallexample @c ada
25787 TO_ADDRESS (INTEGER)
25788 TO_ADDRESS (UNSIGNED_LONGWORD)
25789 TO_ADDRESS (universal_integer)
25790 @end smallexample
25791
25792 @noindent
25793 The version of TO_ADDRESS taking a universal integer argument is in fact
25794 an extension to Ada 83 not strictly compatible with the reference manual.
25795 In GNAT, we are constrained to be exactly compatible with the standard,
25796 and this means we cannot provide this capability.  In DEC Ada 83, the
25797 point of this definition is to deal with a call like:
25798
25799 @smallexample @c ada
25800 TO_ADDRESS (16#12777#);
25801 @end smallexample
25802
25803 @noindent
25804 Normally, according to the Ada 83 standard, one would expect this to be
25805 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25806 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25807 definition using universal_integer takes precedence.
25808
25809 In GNAT, since the version with universal_integer cannot be supplied, it is
25810 not possible to be 100% compatible.  Since there are many programs using
25811 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25812 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25813 declarations provided in the GNAT version of AUX_Dec are:
25814
25815 @smallexample @c ada
25816 function To_Address (X : Integer) return Address;
25817 pragma Pure_Function (To_Address);
25818
25819 function To_Address_Long (X : Unsigned_Longword)
25820  return Address;
25821 pragma Pure_Function (To_Address_Long);
25822 @end smallexample
25823
25824 @noindent
25825 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25826 change the name to TO_ADDRESS_LONG@.
25827
25828 @item Task_Id values
25829 The Task_Id values assigned will be different in the two systems, and GNAT
25830 does not provide a specified value for the Task_Id of the environment task,
25831 which in GNAT is treated like any other declared task.
25832 @end table
25833
25834 For full details on these and other less significant compatibility issues,
25835 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25836 Overview and Comparison on DIGITAL Platforms}.
25837
25838 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25839 attributes are recognized, although only a subset of them can sensibly
25840 be implemented.  The description of pragmas in this reference manual
25841 indicates whether or not they are applicable to non-VMS systems.
25842
25843
25844 @ifset vms
25845 @node Transitioning from Alpha to Integrity OpenVMS
25846 @section Transitioning from Alpha to Integrity OpenVMS
25847
25848 @menu
25849 * Introduction to transitioning::
25850 * Migration of 32 bit code::
25851 * Taking advantage of 64 bit addressing::
25852 * Technical details::
25853 @end menu
25854
25855 @node Introduction to transitioning
25856 @subsection Introduction to transitioning
25857
25858 @noindent
25859 This guide is meant to assist users of GNAT Pro
25860 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
25861 GNAT Pro for Open VMS Integrity has been designed to meet
25862 three main goals:
25863
25864 @enumerate
25865 @item
25866 Providing a full conforming implementation of the Ada 95 language
25867
25868 @item
25869 Allowing maximum backward compatibility, thus easing migration of existing
25870 Ada source code
25871
25872 @item
25873 Supplying a path for exploiting the full IA64 address range
25874 @end enumerate
25875
25876 @noindent
25877 Ada's strong typing semantics has made it
25878 impractical to have different 32-bit and 64-bit modes. As soon as
25879 one object could possibly be outside the 32-bit address space, this
25880 would make it necessary for the @code{System.Address} type to be 64 bits.
25881 In particular, this would cause inconsistencies if 32-bit code is
25882 called from 64-bit code that raises an exception.
25883
25884 This issue has been resolved by always using 64-bit addressing
25885 at the system level, but allowing for automatic conversions between
25886 32-bit and 64-bit addresses where required. Thus users who
25887 do not currently require 64-bit addressing capabilities, can
25888 recompile their code with only minimal changes (and indeed
25889 if the code is written in portable Ada, with no assumptions about
25890 the size of the @code{Address} type, then no changes at all are necessary).
25891 At the same time,
25892 this approach provides a simple, gradual upgrade path to future
25893 use of larger memories than available for 32-bit systems.
25894 Also, newly written applications or libraries will by default
25895 be fully compatible with future systems exploiting 64-bit
25896 addressing capabilities present in IA64.
25897
25898 @ref{Migration of 32 bit code}, will focus on porting applications
25899 that do not require more than 2 GB of
25900 addressable memory. This code will be referred to as
25901 @emph{32-bit code}.
25902 For applications intending to exploit the full ia64 address space,
25903 @ref{Taking advantage of 64 bit addressing},
25904 will consider further changes that may be required.
25905 Such code is called @emph{64-bit code} in the
25906 remainder of this guide.
25907
25908
25909 @node Migration of 32 bit code
25910 @subsection Migration of 32-bit code
25911
25912 @menu
25913 * Address types::
25914 * Access types::
25915 * Unchecked conversions::
25916 * Predefined constants::
25917 * Single source compatibility::
25918 * Experience with source compatibility::
25919 @end menu
25920
25921 @node Address types
25922 @subsubsection Address types
25923
25924 @noindent
25925 To solve the problem of mixing 64-bit and 32-bit addressing,
25926 while maintaining maximum backward compatibility, the following
25927 approach has been taken:
25928
25929 @itemize @bullet
25930 @item
25931 @code{System.Address} always has a size of 64 bits
25932
25933 @item
25934 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
25935 @end itemize
25936
25937
25938 @noindent
25939 Since @code{System.Short_Address} is a subtype of @code{System.Address},
25940 a @code{Short_Address}
25941 may be used where an @code{Address} is required, and vice versa, without
25942 needing explicit type conversions.
25943 By virtue of the Open VMS Integrity parameter passing conventions,
25944 even imported
25945 and exported subprograms that have 32-bit address parameters are
25946 compatible with those that have 64-bit address parameters.
25947 (See @ref{Making code 64 bit clean} for details.)
25948
25949 The areas that may need attention are those where record types have
25950 been defined that contain components of the type @code{System.Address}, and
25951 where objects of this type are passed to code expecting a record layout with
25952 32-bit addresses.
25953
25954 Different compilers on different platforms cannot be
25955 expected to represent the same type in the same way,
25956 since alignment constraints
25957 and other system-dependent properties affect the compiler's decision.
25958 For that reason, Ada code
25959 generally uses representation clauses to specify the expected
25960 layout where required.
25961
25962 If such a representation clause uses 32 bits for a component having
25963 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
25964 that error and produce a specific diagnostic message.
25965 The developer should then determine whether the representation
25966 should be 64 bits or not and make either of two changes:
25967 change the size to 64 bits and leave the type as @code{System.Address}, or
25968 leave the size as 32 bits and change the type to @code{System.Short_Address}.
25969 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
25970 required in any code setting or accessing the field; the compiler will
25971 automatically perform any needed conversions between address
25972 formats.
25973
25974 @node Access types
25975 @subsubsection Access types
25976
25977 @noindent
25978 By default, objects designated by access values are always
25979 allocated in the 32-bit
25980 address space. Thus legacy code will never contain
25981 any objects that are not addressable with 32-bit addresses, and
25982 the compiler will never raise exceptions as result of mixing
25983 32-bit and 64-bit addresses.
25984
25985 However, the access values themselves are represented in 64 bits, for optimum
25986 performance and future compatibility with 64-bit code. As was
25987 the case with @code{System.Address}, the compiler will give an error message
25988 if an object or record component has a representation clause that
25989 requires the access value to fit in 32 bits. In such a situation,
25990 an explicit size clause for the access type, specifying 32 bits,
25991 will have the desired effect.
25992
25993 General access types (declared with @code{access all}) can never be
25994 32 bits, as values of such types must be able to refer to any object
25995 of the  designated type,
25996 including objects residing outside the 32-bit address range.
25997 Existing Ada 83 code will not contain such type definitions,
25998 however, since general access types were introduced in Ada 95.
25999
26000 @node Unchecked conversions
26001 @subsubsection Unchecked conversions
26002
26003 @noindent
26004 In the case of an @code{Unchecked_Conversion} where the source type is a
26005 64-bit access type or the type @code{System.Address}, and the target
26006 type is a 32-bit type, the compiler will generate a warning.
26007 Even though the generated code will still perform the required
26008 conversions, it is highly recommended in these cases to use
26009 respectively a 32-bit access type or @code{System.Short_Address}
26010 as the source type.
26011
26012 @node Predefined constants
26013 @subsubsection Predefined constants
26014
26015 @noindent
26016 The following predefined constants have changed:
26017
26018 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26019 @item   @b{Constant}               @tab @b{Old} @tab @b{New}
26020 @item   @code{System.Word_Size}    @tab 32      @tab 64
26021 @item   @code{System.Memory_Size}  @tab 2**32   @tab 2**64
26022 @item   @code{System.Address_Size} @tab 32      @tab 64
26023 @end multitable
26024
26025 @noindent
26026 If you need to refer to the specific
26027 memory size of a 32-bit implementation, instead of the
26028 actual memory size, use @code{System.Short_Memory_Size}
26029 rather than @code{System.Memory_Size}.
26030 Similarly, references to @code{System.Address_Size} may need
26031 to be replaced by @code{System.Short_Address'Size}.
26032 The program @command{gnatfind} may be useful for locating
26033 references to the above constants, so that you can verify that they
26034 are still correct.
26035
26036 @node Single source compatibility
26037 @subsubsection Single source compatibility
26038
26039 @noindent
26040 In order to allow the same source code to be compiled on
26041 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26042 defines @code{System.Short_Address} and System.Short_Memory_Size
26043 as aliases of respectively @code{System.Address} and
26044 @code{System.Memory_Size}.
26045 (These aliases also leave the door open for a possible
26046 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26047
26048 @node Experience with source compatibility
26049 @subsubsection Experience with source compatibility
26050
26051 @noindent
26052 The Security Server and STARLET provide an interesting ``test case''
26053 for source compatibility issues, since it is in such system code
26054 where assumptions about @code{Address} size might be expected to occur.
26055 Indeed, there were a small number of occasions in the Security Server
26056 file @file{jibdef.ads}
26057 where a representation clause for a record type specified
26058 32 bits for a component of type @code{Address}.
26059 All of these errors were detected by the compiler.
26060 The repair was obvious and immediate; to simply replace @code{Address} by
26061 @code{Short_Address}.
26062
26063 In the case of STARLET, there were several record types that should
26064 have had representation clauses but did not.  In these record types
26065 there was an implicit assumption that an @code{Address} value occupied
26066 32 bits.
26067 These compiled without error, but their usage resulted in run-time error
26068 returns from STARLET system calls.
26069 To assist in the compile-time detection of such situations, we
26070 plan to include a switch to generate a warning message when a
26071 record component is of type @code{Address}.
26072
26073
26074 @c ****************************************
26075 @node Taking advantage of 64 bit addressing
26076 @subsection Taking advantage of 64-bit addressing
26077
26078 @menu
26079 * Making code 64 bit clean::
26080 * Allocating memory from the 64 bit storage pool::
26081 * Restrictions on use of 64 bit objects::
26082 * Using 64 bit storage pools by default::
26083 * General access types::
26084 * STARLET and other predefined libraries::
26085 @end menu
26086
26087 @node Making code 64 bit clean
26088 @subsubsection Making code 64-bit clean
26089
26090 @noindent
26091 In order to prevent problems that may occur when (parts of) a
26092 system start using memory outside the 32-bit address range,
26093 we recommend some additional guidelines:
26094
26095 @itemize @bullet
26096 @item
26097 For imported subprograms that take parameters of the
26098 type @code{System.Address}, ensure that these subprograms can
26099 indeed handle 64-bit addresses. If not, or when in doubt,
26100 change the subprogram declaration to specify
26101 @code{System.Short_Address} instead.
26102
26103 @item
26104 Resolve all warnings related to size mismatches in
26105 unchecked conversions. Failing to do so causes
26106 erroneous execution if the source object is outside
26107 the 32-bit address space.
26108
26109 @item
26110 (optional) Explicitly use the 32-bit storage pool
26111 for access types used in a 32-bit context, or use
26112 generic access types where possible
26113 (@pxref{Restrictions on use of 64 bit objects}).
26114 @end itemize
26115
26116 @noindent
26117 If these rules are followed, the compiler will automatically insert
26118 any necessary checks to ensure that no addresses or access values
26119 passed to 32-bit code ever refer to objects outside the 32-bit
26120 address range.
26121 Any attempt to do this will raise @code{Constraint_Error}.
26122
26123 @node Allocating memory from the 64 bit storage pool
26124 @subsubsection Allocating memory from the 64-bit storage pool
26125
26126 @noindent
26127 For any access type @code{T} that potentially requires memory allocations
26128 beyond the 32-bit address space,
26129 use the following representation clause:
26130
26131 @smallexample @c ada
26132    for T'Storage_Pool use System.Pool_64;
26133 @end smallexample
26134
26135
26136 @node Restrictions on use of 64 bit objects
26137 @subsubsection Restrictions on use of 64-bit objects
26138
26139 @noindent
26140 Taking the address of an object allocated from a 64-bit storage pool,
26141 and then passing this address to a subprogram expecting
26142 @code{System.Short_Address},
26143 or assigning it to a variable of type @code{Short_Address}, will cause
26144 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26145 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26146 no exception is raised and execution
26147 will become erroneous.
26148
26149 @node Using 64 bit storage pools by default
26150 @subsubsection Using 64-bit storage pools by default
26151
26152 @noindent
26153 In some cases it may be desirable to have the compiler allocate
26154 from 64-bit storage pools by default. This may be the case for
26155 libraries that are 64-bit clean, but may be used in both 32-bit
26156 and 64-bit contexts. For these cases the following configuration
26157 pragma may be specified:
26158
26159 @smallexample @c ada
26160   pragma Pool_64_Default;
26161 @end smallexample
26162
26163 @noindent
26164 Any code compiled in the context of this pragma will by default
26165 use the @code{System.Pool_64} storage pool. This default may be overridden
26166 for a specific access type @code{T} by the representation clause:
26167
26168 @smallexample @c ada
26169    for T'Storage_Pool use System.Pool_32;
26170 @end smallexample
26171
26172 @noindent
26173 Any object whose address may be passed to a subprogram with a
26174 @code{Short_Address} argument, or assigned to a variable of type
26175 @code{Short_Address}, needs to be allocated from this pool.
26176
26177 @node General access types
26178 @subsubsection General access types
26179
26180 @noindent
26181 Objects designated by access values from a
26182 general access type (declared with @code{access all}) are never allocated
26183 from a 64-bit storage pool. Code that uses general access types will
26184 accept objects allocated in either 32-bit or 64-bit address spaces,
26185 but never allocate objects outside the 32-bit address space.
26186 Using general access types ensures maximum compatibility with both
26187 32-bit and 64-bit code.
26188
26189
26190 @node STARLET and other predefined libraries
26191 @subsubsection STARLET and other predefined libraries
26192
26193 @noindent
26194 All code that comes as part of GNAT is 64-bit clean, but the
26195 restrictions given in @ref{Restrictions on use of 64 bit objects},
26196 still apply. Look at the package
26197 specifications to see in which contexts objects allocated
26198 in 64-bit address space are acceptable.
26199
26200 @node Technical details
26201 @subsection Technical details
26202
26203 @noindent
26204 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
26205 standard with respect to the type of @code{System.Address}. Previous versions
26206 of GNAT Pro have defined this type as private and implemented it as
26207 a modular type.
26208
26209 In order to allow defining @code{System.Short_Address} as a proper subtype,
26210 and to match the implicit sign extension in parameter passing,
26211 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
26212 visible (i.e., non-private) integer type.
26213 Standard operations on the type, such as the binary operators ``+'', ``-'',
26214 etc., that take @code{Address} operands and return an @code{Address} result,
26215 have been hidden by declaring these
26216 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
26217 that would otherwise result from overloading.
26218 (Note that, although @code{Address} is a visible integer type,
26219 good programming practice dictates against exploiting the type's
26220 integer properties such as literals, since this will compromise
26221 code portability.)
26222
26223 Defining @code{Address} as a visible integer type helps achieve
26224 maximum compatibility for existing Ada code,
26225 without sacrificing the capabilities of the IA64 architecture.
26226 @end ifset
26227
26228
26229 @c ************************************************
26230 @ifset unw
26231 @node Microsoft Windows Topics
26232 @appendix Microsoft Windows Topics
26233 @cindex Windows NT
26234 @cindex Windows 95
26235 @cindex Windows 98
26236
26237 @noindent
26238 This chapter describes topics that are specific to the Microsoft Windows
26239 platforms (NT, 2000, and XP Professional).
26240
26241 @menu
26242 * Using GNAT on Windows::
26243 * Using a network installation of GNAT::
26244 * CONSOLE and WINDOWS subsystems::
26245 * Temporary Files::
26246 * Mixed-Language Programming on Windows::
26247 * Windows Calling Conventions::
26248 * Introduction to Dynamic Link Libraries (DLLs)::
26249 * Using DLLs with GNAT::
26250 * Building DLLs with GNAT::
26251 * Building DLLs with GNAT Project files::
26252 * Building DLLs with gnatdll::
26253 * GNAT and Windows Resources::
26254 * Debugging a DLL::
26255 * GNAT and COM/DCOM Objects::
26256 @end menu
26257
26258 @node Using GNAT on Windows
26259 @section Using GNAT on Windows
26260
26261 @noindent
26262 One of the strengths of the GNAT technology is that its tool set
26263 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26264 @code{gdb} debugger, etc.) is used in the same way regardless of the
26265 platform.
26266
26267 On Windows this tool set is complemented by a number of Microsoft-specific
26268 tools that have been provided to facilitate interoperability with Windows
26269 when this is required. With these tools:
26270
26271 @itemize @bullet
26272
26273 @item
26274 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26275 subsystems.
26276
26277 @item
26278 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26279 relocatable and non-relocatable DLLs are supported).
26280
26281 @item
26282 You can build Ada DLLs for use in other applications. These applications
26283 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26284 relocatable and non-relocatable Ada DLLs are supported.
26285
26286 @item
26287 You can include Windows resources in your Ada application.
26288
26289 @item
26290 You can use or create COM/DCOM objects.
26291 @end itemize
26292
26293 @noindent
26294 Immediately below are listed all known general GNAT-for-Windows restrictions.
26295 Other restrictions about specific features like Windows Resources and DLLs
26296 are listed in separate sections below.
26297
26298 @itemize @bullet
26299
26300 @item
26301 It is not possible to use @code{GetLastError} and @code{SetLastError}
26302 when tasking, protected records, or exceptions are used. In these
26303 cases, in order to implement Ada semantics, the GNAT run-time system
26304 calls certain Win32 routines that set the last error variable to 0 upon
26305 success. It should be possible to use @code{GetLastError} and
26306 @code{SetLastError} when tasking, protected record, and exception
26307 features are not used, but it is not guaranteed to work.
26308
26309 @item
26310 It is not possible to link against Microsoft libraries except for
26311 import libraries. The library must be built to be compatible with
26312 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26313 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26314 not be compatible with the GNAT runtime. Even if the library is
26315 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26316
26317 @item
26318 When the compilation environment is located on FAT32 drives, users may
26319 experience recompilations of the source files that have not changed if
26320 Daylight Saving Time (DST) state has changed since the last time files
26321 were compiled. NTFS drives do not have this problem.
26322
26323 @item
26324 No components of the GNAT toolset use any entries in the Windows
26325 registry. The only entries that can be created are file associations and
26326 PATH settings, provided the user has chosen to create them at installation
26327 time, as well as some minimal book-keeping information needed to correctly
26328 uninstall or integrate different GNAT products.
26329 @end itemize
26330
26331 @node Using a network installation of GNAT
26332 @section Using a network installation of GNAT
26333
26334 @noindent
26335 Make sure the system on which GNAT is installed is accessible from the
26336 current machine, i.e. the install location is shared over the network.
26337 Shared resources are accessed on Windows by means of UNC paths, which
26338 have the format @code{\\server\sharename\path}
26339
26340 In order to use such a network installation, simply add the UNC path of the
26341 @file{bin} directory of your GNAT installation in front of your PATH. For
26342 example, if GNAT is installed in @file{\GNAT} directory of a share location
26343 called @file{c-drive} on a machine @file{LOKI}, the following command will
26344 make it available:
26345
26346 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26347
26348 Be aware that every compilation using the network installation results in the
26349 transfer of large amounts of data across the network and will likely cause
26350 serious performance penalty.
26351
26352 @node CONSOLE and WINDOWS subsystems
26353 @section CONSOLE and WINDOWS subsystems
26354 @cindex CONSOLE Subsystem
26355 @cindex WINDOWS Subsystem
26356 @cindex -mwindows
26357
26358 @noindent
26359 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26360 (which is the default subsystem) will always create a console when
26361 launching the application. This is not something desirable when the
26362 application has a Windows GUI. To get rid of this console the
26363 application must be using the @code{WINDOWS} subsystem. To do so
26364 the @option{-mwindows} linker option must be specified.
26365
26366 @smallexample
26367 $ gnatmake winprog -largs -mwindows
26368 @end smallexample
26369
26370 @node Temporary Files
26371 @section Temporary Files
26372 @cindex Temporary files
26373
26374 @noindent
26375 It is possible to control where temporary files gets created by setting
26376 the TMP environment variable. The file will be created:
26377
26378 @itemize
26379 @item Under the directory pointed to by the TMP environment variable if
26380 this directory exists.
26381
26382 @item Under c:\temp, if the TMP environment variable is not set (or not
26383 pointing to a directory) and if this directory exists.
26384
26385 @item Under the current working directory otherwise.
26386 @end itemize
26387
26388 @noindent
26389 This allows you to determine exactly where the temporary
26390 file will be created. This is particularly useful in networked
26391 environments where you may not have write access to some
26392 directories.
26393
26394 @node Mixed-Language Programming on Windows
26395 @section Mixed-Language Programming on Windows
26396
26397 @noindent
26398 Developing pure Ada applications on Windows is no different than on
26399 other GNAT-supported platforms. However, when developing or porting an
26400 application that contains a mix of Ada and C/C++, the choice of your
26401 Windows C/C++ development environment conditions your overall
26402 interoperability strategy.
26403
26404 If you use @command{gcc} to compile the non-Ada part of your application,
26405 there are no Windows-specific restrictions that affect the overall
26406 interoperability with your Ada code. If you plan to use
26407 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26408 the following limitations:
26409
26410 @itemize @bullet
26411 @item
26412 You cannot link your Ada code with an object or library generated with
26413 Microsoft tools if these use the @code{.tls} section (Thread Local
26414 Storage section) since the GNAT linker does not yet support this section.
26415
26416 @item
26417 You cannot link your Ada code with an object or library generated with
26418 Microsoft tools if these use I/O routines other than those provided in
26419 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26420 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26421 libraries can cause a conflict with @code{msvcrt.dll} services. For
26422 instance Visual C++ I/O stream routines conflict with those in
26423 @code{msvcrt.dll}.
26424 @end itemize
26425
26426 @noindent
26427 If you do want to use the Microsoft tools for your non-Ada code and hit one
26428 of the above limitations, you have two choices:
26429
26430 @enumerate
26431 @item
26432 Encapsulate your non Ada code in a DLL to be linked with your Ada
26433 application. In this case, use the Microsoft or whatever environment to
26434 build the DLL and use GNAT to build your executable
26435 (@pxref{Using DLLs with GNAT}).
26436
26437 @item
26438 Or you can encapsulate your Ada code in a DLL to be linked with the
26439 other part of your application. In this case, use GNAT to build the DLL
26440 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26441 environment to build your executable.
26442 @end enumerate
26443
26444 @node Windows Calling Conventions
26445 @section Windows Calling Conventions
26446 @findex Stdcall
26447 @findex APIENTRY
26448
26449 @menu
26450 * C Calling Convention::
26451 * Stdcall Calling Convention::
26452 * DLL Calling Convention::
26453 @end menu
26454
26455 @noindent
26456 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26457 (callee), there are several ways to push @code{G}'s parameters on the
26458 stack and there are several possible scenarios to clean up the stack
26459 upon @code{G}'s return. A calling convention is an agreed upon software
26460 protocol whereby the responsibilities between the caller (@code{F}) and
26461 the callee (@code{G}) are clearly defined. Several calling conventions
26462 are available for Windows:
26463
26464 @itemize @bullet
26465 @item
26466 @code{C} (Microsoft defined)
26467
26468 @item
26469 @code{Stdcall} (Microsoft defined)
26470
26471 @item
26472 @code{DLL} (GNAT specific)
26473 @end itemize
26474
26475 @node C Calling Convention
26476 @subsection @code{C} Calling Convention
26477
26478 @noindent
26479 This is the default calling convention used when interfacing to C/C++
26480 routines compiled with either @command{gcc} or Microsoft Visual C++.
26481
26482 In the @code{C} calling convention subprogram parameters are pushed on the
26483 stack by the caller from right to left. The caller itself is in charge of
26484 cleaning up the stack after the call. In addition, the name of a routine
26485 with @code{C} calling convention is mangled by adding a leading underscore.
26486
26487 The name to use on the Ada side when importing (or exporting) a routine
26488 with @code{C} calling convention is the name of the routine. For
26489 instance the C function:
26490
26491 @smallexample
26492 int get_val (long);
26493 @end smallexample
26494
26495 @noindent
26496 should be imported from Ada as follows:
26497
26498 @smallexample @c ada
26499 @group
26500 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26501 pragma Import (C, Get_Val, External_Name => "get_val");
26502 @end group
26503 @end smallexample
26504
26505 @noindent
26506 Note that in this particular case the @code{External_Name} parameter could
26507 have been omitted since, when missing, this parameter is taken to be the
26508 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26509 is missing, as in the above example, this parameter is set to be the
26510 @code{External_Name} with a leading underscore.
26511
26512 When importing a variable defined in C, you should always use the @code{C}
26513 calling convention unless the object containing the variable is part of a
26514 DLL (in which case you should use the @code{DLL} calling convention,
26515 @pxref{DLL Calling Convention}).
26516
26517 @node Stdcall Calling Convention
26518 @subsection @code{Stdcall} Calling Convention
26519
26520 @noindent
26521 This convention, which was the calling convention used for Pascal
26522 programs, is used by Microsoft for all the routines in the Win32 API for
26523 efficiency reasons. It must be used to import any routine for which this
26524 convention was specified.
26525
26526 In the @code{Stdcall} calling convention subprogram parameters are pushed
26527 on the stack by the caller from right to left. The callee (and not the
26528 caller) is in charge of cleaning the stack on routine exit. In addition,
26529 the name of a routine with @code{Stdcall} calling convention is mangled by
26530 adding a leading underscore (as for the @code{C} calling convention) and a
26531 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26532 bytes) of the parameters passed to the routine.
26533
26534 The name to use on the Ada side when importing a C routine with a
26535 @code{Stdcall} calling convention is the name of the C routine. The leading
26536 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26537 the compiler. For instance the Win32 function:
26538
26539 @smallexample
26540 @b{APIENTRY} int get_val (long);
26541 @end smallexample
26542
26543 @noindent
26544 should be imported from Ada as follows:
26545
26546 @smallexample @c ada
26547 @group
26548 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26549 pragma Import (Stdcall, Get_Val);
26550 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26551 @end group
26552 @end smallexample
26553
26554 @noindent
26555 As for the @code{C} calling convention, when the @code{External_Name}
26556 parameter is missing, it is taken to be the name of the Ada entity in lower
26557 case. If instead of writing the above import pragma you write:
26558
26559 @smallexample @c ada
26560 @group
26561 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26562 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26563 @end group
26564 @end smallexample
26565
26566 @noindent
26567 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26568 of specifying the @code{External_Name} parameter you specify the
26569 @code{Link_Name} as in the following example:
26570
26571 @smallexample @c ada
26572 @group
26573 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26574 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26575 @end group
26576 @end smallexample
26577
26578 @noindent
26579 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26580 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26581 added at the end of the @code{Link_Name} by the compiler.
26582
26583 @noindent
26584 Note, that in some special cases a DLL's entry point name lacks a trailing
26585 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26586 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26587 to handle those cases (@pxref{Using gnatdll} for the description of
26588 the switches).
26589
26590 @node DLL Calling Convention
26591 @subsection @code{DLL} Calling Convention
26592
26593 @noindent
26594 This convention, which is GNAT-specific, must be used when you want to
26595 import in Ada a variables defined in a DLL. For functions and procedures
26596 this convention is equivalent to the @code{Stdcall} convention. As an
26597 example, if a DLL contains a variable defined as:
26598
26599 @smallexample
26600 int my_var;
26601 @end smallexample
26602
26603 @noindent
26604 then, to access this variable from Ada you should write:
26605
26606 @smallexample @c ada
26607 @group
26608 My_Var : Interfaces.C.int;
26609 pragma Import (DLL, My_Var);
26610 @end group
26611 @end smallexample
26612
26613 The remarks concerning the @code{External_Name} and @code{Link_Name}
26614 parameters given in the previous sections equally apply to the @code{DLL}
26615 calling convention.
26616
26617 @node Introduction to Dynamic Link Libraries (DLLs)
26618 @section Introduction to Dynamic Link Libraries (DLLs)
26619 @findex DLL
26620
26621 @noindent
26622 A Dynamically Linked Library (DLL) is a library that can be shared by
26623 several applications running under Windows. A DLL can contain any number of
26624 routines and variables.
26625
26626 One advantage of DLLs is that you can change and enhance them without
26627 forcing all the applications that depend on them to be relinked or
26628 recompiled. However, you should be aware than all calls to DLL routines are
26629 slower since, as you will understand below, such calls are indirect.
26630
26631 To illustrate the remainder of this section, suppose that an application
26632 wants to use the services of a DLL @file{API.dll}. To use the services
26633 provided by @file{API.dll} you must statically link against the DLL or
26634 an import library which contains a jump table with an entry for each
26635 routine and variable exported by the DLL. In the Microsoft world this
26636 import library is called @file{API.lib}. When using GNAT this import
26637 library is called either @file{libAPI.a} or @file{libapi.a} (names are
26638 case insensitive).
26639
26640 After you have linked your application with the DLL or the import library
26641 and you run your application, here is what happens:
26642
26643 @enumerate
26644 @item
26645 Your application is loaded into memory.
26646
26647 @item
26648 The DLL @file{API.dll} is mapped into the address space of your
26649 application. This means that:
26650
26651 @itemize @bullet
26652 @item
26653 The DLL will use the stack of the calling thread.
26654
26655 @item
26656 The DLL will use the virtual address space of the calling process.
26657
26658 @item
26659 The DLL will allocate memory from the virtual address space of the calling
26660 process.
26661
26662 @item
26663 Handles (pointers) can be safely exchanged between routines in the DLL
26664 routines and routines in the application using the DLL.
26665 @end itemize
26666
26667 @item
26668 The entries in the jump table (from the import library @file{libAPI.a}
26669 or @file{API.lib} or automatically created when linking against a DLL)
26670 which is part of your application are initialized with the addresses
26671 of the routines and variables in @file{API.dll}.
26672
26673 @item
26674 If present in @file{API.dll}, routines @code{DllMain} or
26675 @code{DllMainCRTStartup} are invoked. These routines typically contain
26676 the initialization code needed for the well-being of the routines and
26677 variables exported by the DLL.
26678 @end enumerate
26679
26680 @noindent
26681 There is an additional point which is worth mentioning. In the Windows
26682 world there are two kind of DLLs: relocatable and non-relocatable
26683 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26684 in the target application address space. If the addresses of two
26685 non-relocatable DLLs overlap and these happen to be used by the same
26686 application, a conflict will occur and the application will run
26687 incorrectly. Hence, when possible, it is always preferable to use and
26688 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26689 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26690 User's Guide) removes the debugging symbols from the DLL but the DLL can
26691 still be relocated.
26692
26693 As a side note, an interesting difference between Microsoft DLLs and
26694 Unix shared libraries, is the fact that on most Unix systems all public
26695 routines are exported by default in a Unix shared library, while under
26696 Windows it is possible (but not required) to list exported routines in
26697 a definition file (@pxref{The Definition File}).
26698
26699 @node Using DLLs with GNAT
26700 @section Using DLLs with GNAT
26701
26702 @menu
26703 * Creating an Ada Spec for the DLL Services::
26704 * Creating an Import Library::
26705 @end menu
26706
26707 @noindent
26708 To use the services of a DLL, say @file{API.dll}, in your Ada application
26709 you must have:
26710
26711 @enumerate
26712 @item
26713 The Ada spec for the routines and/or variables you want to access in
26714 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26715 header files provided with the DLL.
26716
26717 @item
26718 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26719 mentioned an import library is a statically linked library containing the
26720 import table which will be filled at load time to point to the actual
26721 @file{API.dll} routines. Sometimes you don't have an import library for the
26722 DLL you want to use. The following sections will explain how to build
26723 one. Note that this is optional.
26724
26725 @item
26726 The actual DLL, @file{API.dll}.
26727 @end enumerate
26728
26729 @noindent
26730 Once you have all the above, to compile an Ada application that uses the
26731 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26732 you simply issue the command
26733
26734 @smallexample
26735 $ gnatmake my_ada_app -largs -lAPI
26736 @end smallexample
26737
26738 @noindent
26739 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26740 tells the GNAT linker to look first for a library named @file{API.lib}
26741 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26742 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26743 contains the following pragma
26744
26745 @smallexample @c ada
26746 pragma Linker_Options ("-lAPI");
26747 @end smallexample
26748
26749 @noindent
26750 you do not have to add @option{-largs -lAPI} at the end of the
26751 @command{gnatmake} command.
26752
26753 If any one of the items above is missing you will have to create it
26754 yourself. The following sections explain how to do so using as an
26755 example a fictitious DLL called @file{API.dll}.
26756
26757 @node Creating an Ada Spec for the DLL Services
26758 @subsection Creating an Ada Spec for the DLL Services
26759
26760 @noindent
26761 A DLL typically comes with a C/C++ header file which provides the
26762 definitions of the routines and variables exported by the DLL. The Ada
26763 equivalent of this header file is a package spec that contains definitions
26764 for the imported entities. If the DLL you intend to use does not come with
26765 an Ada spec you have to generate one such spec yourself. For example if
26766 the header file of @file{API.dll} is a file @file{api.h} containing the
26767 following two definitions:
26768
26769 @smallexample
26770 @group
26771 @cartouche
26772 int some_var;
26773 int get (char *);
26774 @end cartouche
26775 @end group
26776 @end smallexample
26777
26778 @noindent
26779 then the equivalent Ada spec could be:
26780
26781 @smallexample @c ada
26782 @group
26783 @cartouche
26784 with Interfaces.C.Strings;
26785 package API is
26786    use Interfaces;
26787
26788    Some_Var : C.int;
26789    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26790
26791 private
26792    pragma Import (C, Get);
26793    pragma Import (DLL, Some_Var);
26794 end API;
26795 @end cartouche
26796 @end group
26797 @end smallexample
26798
26799 @noindent
26800 Note that a variable is @strong{always imported with a DLL convention}. A
26801 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26802 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26803 (@pxref{Windows Calling Conventions}).
26804
26805 @node Creating an Import Library
26806 @subsection Creating an Import Library
26807 @cindex Import library
26808
26809 @menu
26810 * The Definition File::
26811 * GNAT-Style Import Library::
26812 * Microsoft-Style Import Library::
26813 @end menu
26814
26815 @noindent
26816 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26817 import library @file{libAPI.a} is available with @file{API.dll} you
26818 can skip this section. You can also skip this section if
26819 @file{API.dll} is built with GNU tools as in this case it is possible
26820 to link directly against the DLL. Otherwise read on.
26821
26822 @node The Definition File
26823 @subsubsection The Definition File
26824 @cindex Definition file
26825 @findex .def
26826
26827 @noindent
26828 As previously mentioned, and unlike Unix systems, the list of symbols
26829 that are exported from a DLL must be provided explicitly in Windows.
26830 The main goal of a definition file is precisely that: list the symbols
26831 exported by a DLL. A definition file (usually a file with a @code{.def}
26832 suffix) has the following structure:
26833
26834 @smallexample
26835 @group
26836 @cartouche
26837 [LIBRARY @i{name}]
26838 [DESCRIPTION @i{string}]
26839 EXPORTS
26840    @i{symbol1}
26841    @i{symbol2}
26842    ...
26843 @end cartouche
26844 @end group
26845 @end smallexample
26846
26847 @table @code
26848 @item LIBRARY @i{name}
26849 This section, which is optional, gives the name of the DLL.
26850
26851 @item DESCRIPTION @i{string}
26852 This section, which is optional, gives a description string that will be
26853 embedded in the import library.
26854
26855 @item EXPORTS
26856 This section gives the list of exported symbols (procedures, functions or
26857 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26858 section of @file{API.def} looks like:
26859
26860 @smallexample
26861 @group
26862 @cartouche
26863 EXPORTS
26864    some_var
26865    get
26866 @end cartouche
26867 @end group
26868 @end smallexample
26869 @end table
26870
26871 @noindent
26872 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26873 (@pxref{Windows Calling Conventions}) for a Stdcall
26874 calling convention function in the exported symbols list.
26875
26876 @noindent
26877 There can actually be other sections in a definition file, but these
26878 sections are not relevant to the discussion at hand.
26879
26880 @node GNAT-Style Import Library
26881 @subsubsection GNAT-Style Import Library
26882
26883 @noindent
26884 To create a static import library from @file{API.dll} with the GNAT tools
26885 you should proceed as follows:
26886
26887 @enumerate
26888 @item
26889 Create the definition file @file{API.def} (@pxref{The Definition File}).
26890 For that use the @code{dll2def} tool as follows:
26891
26892 @smallexample
26893 $ dll2def API.dll > API.def
26894 @end smallexample
26895
26896 @noindent
26897 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26898 to standard output the list of entry points in the DLL. Note that if
26899 some routines in the DLL have the @code{Stdcall} convention
26900 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26901 suffix then you'll have to edit @file{api.def} to add it, and specify
26902 @code{-k} to @code{gnatdll} when creating the import library.
26903
26904 @noindent
26905 Here are some hints to find the right @code{@@}@i{nn} suffix.
26906
26907 @enumerate
26908 @item
26909 If you have the Microsoft import library (.lib), it is possible to get
26910 the right symbols by using Microsoft @code{dumpbin} tool (see the
26911 corresponding Microsoft documentation for further details).
26912
26913 @smallexample
26914 $ dumpbin /exports api.lib
26915 @end smallexample
26916
26917 @item
26918 If you have a message about a missing symbol at link time the compiler
26919 tells you what symbol is expected. You just have to go back to the
26920 definition file and add the right suffix.
26921 @end enumerate
26922
26923 @item
26924 Build the import library @code{libAPI.a}, using @code{gnatdll}
26925 (@pxref{Using gnatdll}) as follows:
26926
26927 @smallexample
26928 $ gnatdll -e API.def -d API.dll
26929 @end smallexample
26930
26931 @noindent
26932 @code{gnatdll} takes as input a definition file @file{API.def} and the
26933 name of the DLL containing the services listed in the definition file
26934 @file{API.dll}. The name of the static import library generated is
26935 computed from the name of the definition file as follows: if the
26936 definition file name is @i{xyz}@code{.def}, the import library name will
26937 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26938 @option{-e} could have been removed because the name of the definition
26939 file (before the ``@code{.def}'' suffix) is the same as the name of the
26940 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26941 @end enumerate
26942
26943 @node Microsoft-Style Import Library
26944 @subsubsection Microsoft-Style Import Library
26945
26946 @noindent
26947 With GNAT you can either use a GNAT-style or Microsoft-style import
26948 library. A Microsoft import library is needed only if you plan to make an
26949 Ada DLL available to applications developed with Microsoft
26950 tools (@pxref{Mixed-Language Programming on Windows}).
26951
26952 To create a Microsoft-style import library for @file{API.dll} you
26953 should proceed as follows:
26954
26955 @enumerate
26956 @item
26957 Create the definition file @file{API.def} from the DLL. For this use either
26958 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26959 tool (see the corresponding Microsoft documentation for further details).
26960
26961 @item
26962 Build the actual import library using Microsoft's @code{lib} utility:
26963
26964 @smallexample
26965 $ lib -machine:IX86 -def:API.def -out:API.lib
26966 @end smallexample
26967
26968 @noindent
26969 If you use the above command the definition file @file{API.def} must
26970 contain a line giving the name of the DLL:
26971
26972 @smallexample
26973 LIBRARY      "API"
26974 @end smallexample
26975
26976 @noindent
26977 See the Microsoft documentation for further details about the usage of
26978 @code{lib}.
26979 @end enumerate
26980
26981 @node Building DLLs with GNAT
26982 @section Building DLLs with GNAT
26983 @cindex DLLs, building
26984
26985 @noindent
26986 This section explain how to build DLLs using the GNAT built-in DLL
26987 support. With the following procedure it is straight forward to build
26988 and use DLLs with GNAT.
26989
26990 @enumerate
26991
26992 @item building object files
26993
26994 The first step is to build all objects files that are to be included
26995 into the DLL. This is done by using the standard @command{gnatmake} tool.
26996
26997 @item building the DLL
26998
26999 To build the DLL you must use @command{gcc}'s @code{-shared}
27000 option. It is quite simple to use this method:
27001
27002 @smallexample
27003 $ gcc -shared -o api.dll obj1.o obj2.o ...
27004 @end smallexample
27005
27006 It is important to note that in this case all symbols found in the
27007 object files are automatically exported. It is possible to restrict
27008 the set of symbols to export by passing to @command{gcc} a definition
27009 file, @pxref{The Definition File}. For example:
27010
27011 @smallexample
27012 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27013 @end smallexample
27014
27015 If you use a definition file you must export the elaboration procedures
27016 for every package that required one. Elaboration procedures are named
27017 using the package name followed by "_E".
27018
27019 @item preparing DLL to be used
27020
27021 For the DLL to be used by client programs the bodies must be hidden
27022 from it and the .ali set with read-only attribute. This is very important
27023 otherwise GNAT will recompile all packages and will not actually use
27024 the code in the DLL. For example:
27025
27026 @smallexample
27027 $ mkdir apilib
27028 $ copy *.ads *.ali api.dll apilib
27029 $ attrib +R apilib\*.ali
27030 @end smallexample
27031
27032 @end enumerate
27033
27034 At this point it is possible to use the DLL by directly linking
27035 against it. Note that you must use the GNAT shared runtime when using
27036 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27037 option.
27038
27039 @smallexample
27040 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27041 @end smallexample
27042
27043 @node Building DLLs with GNAT Project files
27044 @section Building DLLs with GNAT Project files
27045 @cindex DLLs, building
27046
27047 @noindent
27048 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27049
27050 @node Building DLLs with gnatdll
27051 @section Building DLLs with gnatdll
27052 @cindex DLLs, building
27053
27054 @menu
27055 * Limitations When Using Ada DLLs from Ada::
27056 * Exporting Ada Entities::
27057 * Ada DLLs and Elaboration::
27058 * Ada DLLs and Finalization::
27059 * Creating a Spec for Ada DLLs::
27060 * Creating the Definition File::
27061 * Using gnatdll::
27062 @end menu
27063
27064 @noindent
27065 Note that it is prefered to use the built-in GNAT DLL support
27066 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27067 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27068
27069 This section explains how to build DLLs containing Ada code using
27070 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27071 remainder of this section.
27072
27073 The steps required to build an Ada DLL that is to be used by Ada as well as
27074 non-Ada applications are as follows:
27075
27076 @enumerate
27077 @item
27078 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27079 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27080 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27081 skip this step if you plan to use the Ada DLL only from Ada applications.
27082
27083 @item
27084 Your Ada code must export an initialization routine which calls the routine
27085 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27086 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27087 routine exported by the Ada DLL must be invoked by the clients of the DLL
27088 to initialize the DLL.
27089
27090 @item
27091 When useful, the DLL should also export a finalization routine which calls
27092 routine @code{adafinal} generated by @command{gnatbind} to perform the
27093 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27094 The finalization routine exported by the Ada DLL must be invoked by the
27095 clients of the DLL when the DLL services are no further needed.
27096
27097 @item
27098 You must provide a spec for the services exported by the Ada DLL in each
27099 of the programming languages to which you plan to make the DLL available.
27100
27101 @item
27102 You must provide a definition file listing the exported entities
27103 (@pxref{The Definition File}).
27104
27105 @item
27106 Finally you must use @code{gnatdll} to produce the DLL and the import
27107 library (@pxref{Using gnatdll}).
27108 @end enumerate
27109
27110 @noindent
27111 Note that a relocatable DLL stripped using the @code{strip} binutils
27112 tool will not be relocatable anymore. To build a DLL without debug
27113 information pass @code{-largs -s} to @code{gnatdll}.
27114
27115 @node Limitations When Using Ada DLLs from Ada
27116 @subsection Limitations When Using Ada DLLs from Ada
27117
27118 @noindent
27119 When using Ada DLLs from Ada applications there is a limitation users
27120 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27121 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27122 each Ada DLL includes the services of the GNAT run time that are necessary
27123 to the Ada code inside the DLL. As a result, when an Ada program uses an
27124 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27125 one in the main program.
27126
27127 It is therefore not possible to exchange GNAT run-time objects between the
27128 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27129 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27130 types, etc.
27131
27132 It is completely safe to exchange plain elementary, array or record types,
27133 Windows object handles, etc.
27134
27135 @node Exporting Ada Entities
27136 @subsection Exporting Ada Entities
27137 @cindex Export table
27138
27139 @noindent
27140 Building a DLL is a way to encapsulate a set of services usable from any
27141 application. As a result, the Ada entities exported by a DLL should be
27142 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27143 any Ada name mangling. Please note that the @code{Stdcall} convention
27144 should only be used for subprograms, not for variables. As an example here
27145 is an Ada package @code{API}, spec and body, exporting two procedures, a
27146 function, and a variable:
27147
27148 @smallexample @c ada
27149 @group
27150 @cartouche
27151 with Interfaces.C; use Interfaces;
27152 package API is
27153    Count : C.int := 0;
27154    function Factorial (Val : C.int) return C.int;
27155
27156    procedure Initialize_API;
27157    procedure Finalize_API;
27158    --  Initialization & Finalization routines. More in the next section.
27159 private
27160    pragma Export (C, Initialize_API);
27161    pragma Export (C, Finalize_API);
27162    pragma Export (C, Count);
27163    pragma Export (C, Factorial);
27164 end API;
27165 @end cartouche
27166 @end group
27167 @end smallexample
27168
27169 @smallexample @c ada
27170 @group
27171 @cartouche
27172 package body API is
27173    function Factorial (Val : C.int) return C.int is
27174       Fact : C.int := 1;
27175    begin
27176       Count := Count + 1;
27177       for K in 1 .. Val loop
27178          Fact := Fact * K;
27179       end loop;
27180       return Fact;
27181    end Factorial;
27182
27183    procedure Initialize_API is
27184       procedure Adainit;
27185       pragma Import (C, Adainit);
27186    begin
27187       Adainit;
27188    end Initialize_API;
27189
27190    procedure Finalize_API is
27191       procedure Adafinal;
27192       pragma Import (C, Adafinal);
27193    begin
27194       Adafinal;
27195    end Finalize_API;
27196 end API;
27197 @end cartouche
27198 @end group
27199 @end smallexample
27200
27201 @noindent
27202 If the Ada DLL you are building will only be used by Ada applications
27203 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27204 convention. As an example, the previous package could be written as
27205 follows:
27206
27207 @smallexample @c ada
27208 @group
27209 @cartouche
27210 package API is
27211    Count : Integer := 0;
27212    function Factorial (Val : Integer) return Integer;
27213
27214    procedure Initialize_API;
27215    procedure Finalize_API;
27216    --  Initialization and Finalization routines.
27217 end API;
27218 @end cartouche
27219 @end group
27220 @end smallexample
27221
27222 @smallexample @c ada
27223 @group
27224 @cartouche
27225 package body API is
27226    function Factorial (Val : Integer) return Integer is
27227       Fact : Integer := 1;
27228    begin
27229       Count := Count + 1;
27230       for K in 1 .. Val loop
27231          Fact := Fact * K;
27232       end loop;
27233       return Fact;
27234    end Factorial;
27235
27236    ...
27237    --  The remainder of this package body is unchanged.
27238 end API;
27239 @end cartouche
27240 @end group
27241 @end smallexample
27242
27243 @noindent
27244 Note that if you do not export the Ada entities with a @code{C} or
27245 @code{Stdcall} convention you will have to provide the mangled Ada names
27246 in the definition file of the Ada DLL
27247 (@pxref{Creating the Definition File}).
27248
27249 @node Ada DLLs and Elaboration
27250 @subsection Ada DLLs and Elaboration
27251 @cindex DLLs and elaboration
27252
27253 @noindent
27254 The DLL that you are building contains your Ada code as well as all the
27255 routines in the Ada library that are needed by it. The first thing a
27256 user of your DLL must do is elaborate the Ada code
27257 (@pxref{Elaboration Order Handling in GNAT}).
27258
27259 To achieve this you must export an initialization routine
27260 (@code{Initialize_API} in the previous example), which must be invoked
27261 before using any of the DLL services. This elaboration routine must call
27262 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27263 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27264 @code{Initialize_Api} for an example. Note that the GNAT binder is
27265 automatically invoked during the DLL build process by the @code{gnatdll}
27266 tool (@pxref{Using gnatdll}).
27267
27268 When a DLL is loaded, Windows systematically invokes a routine called
27269 @code{DllMain}. It would therefore be possible to call @code{adainit}
27270 directly from @code{DllMain} without having to provide an explicit
27271 initialization routine. Unfortunately, it is not possible to call
27272 @code{adainit} from the @code{DllMain} if your program has library level
27273 tasks because access to the @code{DllMain} entry point is serialized by
27274 the system (that is, only a single thread can execute ``through'' it at a
27275 time), which means that the GNAT run time will deadlock waiting for the
27276 newly created task to complete its initialization.
27277
27278 @node Ada DLLs and Finalization
27279 @subsection Ada DLLs and Finalization
27280 @cindex DLLs and finalization
27281
27282 @noindent
27283 When the services of an Ada DLL are no longer needed, the client code should
27284 invoke the DLL finalization routine, if available. The DLL finalization
27285 routine is in charge of releasing all resources acquired by the DLL. In the
27286 case of the Ada code contained in the DLL, this is achieved by calling
27287 routine @code{adafinal} generated by the GNAT binder
27288 (@pxref{Binding with Non-Ada Main Programs}).
27289 See the body of @code{Finalize_Api} for an
27290 example. As already pointed out the GNAT binder is automatically invoked
27291 during the DLL build process by the @code{gnatdll} tool
27292 (@pxref{Using gnatdll}).
27293
27294 @node Creating a Spec for Ada DLLs
27295 @subsection Creating a Spec for Ada DLLs
27296
27297 @noindent
27298 To use the services exported by the Ada DLL from another programming
27299 language (e.g. C), you have to translate the specs of the exported Ada
27300 entities in that language. For instance in the case of @code{API.dll},
27301 the corresponding C header file could look like:
27302
27303 @smallexample
27304 @group
27305 @cartouche
27306 extern int *_imp__count;
27307 #define count (*_imp__count)
27308 int factorial (int);
27309 @end cartouche
27310 @end group
27311 @end smallexample
27312
27313 @noindent
27314 It is important to understand that when building an Ada DLL to be used by
27315 other Ada applications, you need two different specs for the packages
27316 contained in the DLL: one for building the DLL and the other for using
27317 the DLL. This is because the @code{DLL} calling convention is needed to
27318 use a variable defined in a DLL, but when building the DLL, the variable
27319 must have either the @code{Ada} or @code{C} calling convention. As an
27320 example consider a DLL comprising the following package @code{API}:
27321
27322 @smallexample @c ada
27323 @group
27324 @cartouche
27325 package API is
27326    Count : Integer := 0;
27327    ...
27328    --  Remainder of the package omitted.
27329 end API;
27330 @end cartouche
27331 @end group
27332 @end smallexample
27333
27334 @noindent
27335 After producing a DLL containing package @code{API}, the spec that
27336 must be used to import @code{API.Count} from Ada code outside of the
27337 DLL is:
27338
27339 @smallexample @c ada
27340 @group
27341 @cartouche
27342 package API is
27343    Count : Integer;
27344    pragma Import (DLL, Count);
27345 end API;
27346 @end cartouche
27347 @end group
27348 @end smallexample
27349
27350 @node Creating the Definition File
27351 @subsection Creating the Definition File
27352
27353 @noindent
27354 The definition file is the last file needed to build the DLL. It lists
27355 the exported symbols. As an example, the definition file for a DLL
27356 containing only package @code{API} (where all the entities are exported
27357 with a @code{C} calling convention) is:
27358
27359 @smallexample
27360 @group
27361 @cartouche
27362 EXPORTS
27363     count
27364     factorial
27365     finalize_api
27366     initialize_api
27367 @end cartouche
27368 @end group
27369 @end smallexample
27370
27371 @noindent
27372 If the @code{C} calling convention is missing from package @code{API},
27373 then the definition file contains the mangled Ada names of the above
27374 entities, which in this case are:
27375
27376 @smallexample
27377 @group
27378 @cartouche
27379 EXPORTS
27380     api__count
27381     api__factorial
27382     api__finalize_api
27383     api__initialize_api
27384 @end cartouche
27385 @end group
27386 @end smallexample
27387
27388 @node Using gnatdll
27389 @subsection Using @code{gnatdll}
27390 @findex gnatdll
27391
27392 @menu
27393 * gnatdll Example::
27394 * gnatdll behind the Scenes::
27395 * Using dlltool::
27396 @end menu
27397
27398 @noindent
27399 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27400 and non-Ada sources that make up your DLL have been compiled.
27401 @code{gnatdll} is actually in charge of two distinct tasks: build the
27402 static import library for the DLL and the actual DLL. The form of the
27403 @code{gnatdll} command is
27404
27405 @smallexample
27406 @cartouche
27407 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27408 @end cartouche
27409 @end smallexample
27410
27411 @noindent
27412 where @i{list-of-files} is a list of ALI and object files. The object
27413 file list must be the exact list of objects corresponding to the non-Ada
27414 sources whose services are to be included in the DLL. The ALI file list
27415 must be the exact list of ALI files for the corresponding Ada sources
27416 whose services are to be included in the DLL. If @i{list-of-files} is
27417 missing, only the static import library is generated.
27418
27419 @noindent
27420 You may specify any of the following switches to @code{gnatdll}:
27421
27422 @table @code
27423 @item -a[@var{address}]
27424 @cindex @option{-a} (@code{gnatdll})
27425 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27426 specified the default address @var{0x11000000} will be used. By default,
27427 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27428 advise the reader to build relocatable DLL.
27429
27430 @item -b @var{address}
27431 @cindex @option{-b} (@code{gnatdll})
27432 Set the relocatable DLL base address. By default the address is
27433 @var{0x11000000}.
27434
27435 @item -bargs @var{opts}
27436 @cindex @option{-bargs} (@code{gnatdll})
27437 Binder options. Pass @var{opts} to the binder.
27438
27439 @item -d @var{dllfile}
27440 @cindex @option{-d} (@code{gnatdll})
27441 @var{dllfile} is the name of the DLL. This switch must be present for
27442 @code{gnatdll} to do anything. The name of the generated import library is
27443 obtained algorithmically from @var{dllfile} as shown in the following
27444 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27445 @code{libxyz.a}. The name of the definition file to use (if not specified
27446 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27447 as shown in the following example:
27448 if @var{dllfile} is @code{xyz.dll}, the definition
27449 file used is @code{xyz.def}.
27450
27451 @item -e @var{deffile}
27452 @cindex @option{-e} (@code{gnatdll})
27453 @var{deffile} is the name of the definition file.
27454
27455 @item -g
27456 @cindex @option{-g} (@code{gnatdll})
27457 Generate debugging information. This information is stored in the object
27458 file and copied from there to the final DLL file by the linker,
27459 where it can be read by the debugger. You must use the
27460 @option{-g} switch if you plan on using the debugger or the symbolic
27461 stack traceback.
27462
27463 @item -h
27464 @cindex @option{-h} (@code{gnatdll})
27465 Help mode. Displays @code{gnatdll} switch usage information.
27466
27467 @item -Idir
27468 @cindex @option{-I} (@code{gnatdll})
27469 Direct @code{gnatdll} to search the @var{dir} directory for source and
27470 object files needed to build the DLL.
27471 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27472
27473 @item -k
27474 @cindex @option{-k} (@code{gnatdll})
27475 Removes the @code{@@}@i{nn} suffix from the import library's exported
27476 names, but keeps them for the link names. You must specify this
27477 option if you want to use a @code{Stdcall} function in a DLL for which
27478 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27479 of the Windows NT DLL for example. This option has no effect when
27480 @option{-n} option is specified.
27481
27482 @item -l @var{file}
27483 @cindex @option{-l} (@code{gnatdll})
27484 The list of ALI and object files used to build the DLL are listed in
27485 @var{file}, instead of being given in the command line. Each line in
27486 @var{file} contains the name of an ALI or object file.
27487
27488 @item -n
27489 @cindex @option{-n} (@code{gnatdll})
27490 No Import. Do not create the import library.
27491
27492 @item -q
27493 @cindex @option{-q} (@code{gnatdll})
27494 Quiet mode. Do not display unnecessary messages.
27495
27496 @item -v
27497 @cindex @option{-v} (@code{gnatdll})
27498 Verbose mode. Display extra information.
27499
27500 @item -largs @var{opts}
27501 @cindex @option{-largs} (@code{gnatdll})
27502 Linker options. Pass @var{opts} to the linker.
27503 @end table
27504
27505 @node gnatdll Example
27506 @subsubsection @code{gnatdll} Example
27507
27508 @noindent
27509 As an example the command to build a relocatable DLL from @file{api.adb}
27510 once @file{api.adb} has been compiled and @file{api.def} created is
27511
27512 @smallexample
27513 $ gnatdll -d api.dll api.ali
27514 @end smallexample
27515
27516 @noindent
27517 The above command creates two files: @file{libapi.a} (the import
27518 library) and @file{api.dll} (the actual DLL). If you want to create
27519 only the DLL, just type:
27520
27521 @smallexample
27522 $ gnatdll -d api.dll -n api.ali
27523 @end smallexample
27524
27525 @noindent
27526 Alternatively if you want to create just the import library, type:
27527
27528 @smallexample
27529 $ gnatdll -d api.dll
27530 @end smallexample
27531
27532 @node gnatdll behind the Scenes
27533 @subsubsection @code{gnatdll} behind the Scenes
27534
27535 @noindent
27536 This section details the steps involved in creating a DLL. @code{gnatdll}
27537 does these steps for you. Unless you are interested in understanding what
27538 goes on behind the scenes, you should skip this section.
27539
27540 We use the previous example of a DLL containing the Ada package @code{API},
27541 to illustrate the steps necessary to build a DLL. The starting point is a
27542 set of objects that will make up the DLL and the corresponding ALI
27543 files. In the case of this example this means that @file{api.o} and
27544 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27545 the following:
27546
27547 @enumerate
27548 @item
27549 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27550 the information necessary to generate relocation information for the
27551 DLL.
27552
27553 @smallexample
27554 @group
27555 $ gnatbind -n api
27556 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27557 @end group
27558 @end smallexample
27559
27560 @noindent
27561 In addition to the base file, the @command{gnatlink} command generates an
27562 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27563 asks @command{gnatlink} to generate the routines @code{DllMain} and
27564 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27565 is loaded into memory.
27566
27567 @item
27568 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27569 export table (@file{api.exp}). The export table contains the relocation
27570 information in a form which can be used during the final link to ensure
27571 that the Windows loader is able to place the DLL anywhere in memory.
27572
27573 @smallexample
27574 @group
27575 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27576           --output-exp api.exp
27577 @end group
27578 @end smallexample
27579
27580 @item
27581 @code{gnatdll} builds the base file using the new export table. Note that
27582 @command{gnatbind} must be called once again since the binder generated file
27583 has been deleted during the previous call to @command{gnatlink}.
27584
27585 @smallexample
27586 @group
27587 $ gnatbind -n api
27588 $ gnatlink api -o api.jnk api.exp -mdll
27589       -Wl,--base-file,api.base
27590 @end group
27591 @end smallexample
27592
27593 @item
27594 @code{gnatdll} builds the new export table using the new base file and
27595 generates the DLL import library @file{libAPI.a}.
27596
27597 @smallexample
27598 @group
27599 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27600           --output-exp api.exp --output-lib libAPI.a
27601 @end group
27602 @end smallexample
27603
27604 @item
27605 Finally @code{gnatdll} builds the relocatable DLL using the final export
27606 table.
27607
27608 @smallexample
27609 @group
27610 $ gnatbind -n api
27611 $ gnatlink api api.exp -o api.dll -mdll
27612 @end group
27613 @end smallexample
27614 @end enumerate
27615
27616 @node Using dlltool
27617 @subsubsection Using @code{dlltool}
27618
27619 @noindent
27620 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27621 DLLs and static import libraries. This section summarizes the most
27622 common @code{dlltool} switches. The form of the @code{dlltool} command
27623 is
27624
27625 @smallexample
27626 $ dlltool [@var{switches}]
27627 @end smallexample
27628
27629 @noindent
27630 @code{dlltool} switches include:
27631
27632 @table @option
27633 @item --base-file @var{basefile}
27634 @cindex @option{--base-file} (@command{dlltool})
27635 Read the base file @var{basefile} generated by the linker. This switch
27636 is used to create a relocatable DLL.
27637
27638 @item --def @var{deffile}
27639 @cindex @option{--def} (@command{dlltool})
27640 Read the definition file.
27641
27642 @item --dllname @var{name}
27643 @cindex @option{--dllname} (@command{dlltool})
27644 Gives the name of the DLL. This switch is used to embed the name of the
27645 DLL in the static import library generated by @code{dlltool} with switch
27646 @option{--output-lib}.
27647
27648 @item -k
27649 @cindex @option{-k} (@command{dlltool})
27650 Kill @code{@@}@i{nn} from exported names
27651 (@pxref{Windows Calling Conventions}
27652 for a discussion about @code{Stdcall}-style symbols.
27653
27654 @item --help
27655 @cindex @option{--help} (@command{dlltool})
27656 Prints the @code{dlltool} switches with a concise description.
27657
27658 @item --output-exp @var{exportfile}
27659 @cindex @option{--output-exp} (@command{dlltool})
27660 Generate an export file @var{exportfile}. The export file contains the
27661 export table (list of symbols in the DLL) and is used to create the DLL.
27662
27663 @item --output-lib @i{libfile}
27664 @cindex @option{--output-lib} (@command{dlltool})
27665 Generate a static import library @var{libfile}.
27666
27667 @item -v
27668 @cindex @option{-v} (@command{dlltool})
27669 Verbose mode.
27670
27671 @item --as @i{assembler-name}
27672 @cindex @option{--as} (@command{dlltool})
27673 Use @i{assembler-name} as the assembler. The default is @code{as}.
27674 @end table
27675
27676 @node GNAT and Windows Resources
27677 @section GNAT and Windows Resources
27678 @cindex Resources, windows
27679
27680 @menu
27681 * Building Resources::
27682 * Compiling Resources::
27683 * Using Resources::
27684 @end menu
27685
27686 @noindent
27687 Resources are an easy way to add Windows specific objects to your
27688 application. The objects that can be added as resources include:
27689
27690 @itemize @bullet
27691 @item
27692 menus
27693
27694 @item
27695 accelerators
27696
27697 @item
27698 dialog boxes
27699
27700 @item
27701 string tables
27702
27703 @item
27704 bitmaps
27705
27706 @item
27707 cursors
27708
27709 @item
27710 icons
27711
27712 @item
27713 fonts
27714 @end itemize
27715
27716 @noindent
27717 This section explains how to build, compile and use resources.
27718
27719 @node Building Resources
27720 @subsection Building Resources
27721 @cindex Resources, building
27722
27723 @noindent
27724 A resource file is an ASCII file. By convention resource files have an
27725 @file{.rc} extension.
27726 The easiest way to build a resource file is to use Microsoft tools
27727 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27728 @code{dlgedit.exe} to build dialogs.
27729 It is always possible to build an @file{.rc} file yourself by writing a
27730 resource script.
27731
27732 It is not our objective to explain how to write a resource file. A
27733 complete description of the resource script language can be found in the
27734 Microsoft documentation.
27735
27736 @node Compiling Resources
27737 @subsection Compiling Resources
27738 @findex rc
27739 @findex windres
27740 @cindex Resources, compiling
27741
27742 @noindent
27743 This section describes how to build a GNAT-compatible (COFF) object file
27744 containing the resources. This is done using the Resource Compiler
27745 @code{windres} as follows:
27746
27747 @smallexample
27748 $ windres -i myres.rc -o myres.o
27749 @end smallexample
27750
27751 @noindent
27752 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
27753 file. You can specify an alternate preprocessor (usually named
27754 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27755 parameter. A list of all possible options may be obtained by entering
27756 the command @code{windres} @option{--help}.
27757
27758 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27759 to produce a @file{.res} file (binary resource file). See the
27760 corresponding Microsoft documentation for further details. In this case
27761 you need to use @code{windres} to translate the @file{.res} file to a
27762 GNAT-compatible object file as follows:
27763
27764 @smallexample
27765 $ windres -i myres.res -o myres.o
27766 @end smallexample
27767
27768 @node Using Resources
27769 @subsection Using Resources
27770 @cindex Resources, using
27771
27772 @noindent
27773 To include the resource file in your program just add the
27774 GNAT-compatible object file for the resource(s) to the linker
27775 arguments. With @command{gnatmake} this is done by using the @option{-largs}
27776 option:
27777
27778 @smallexample
27779 $ gnatmake myprog -largs myres.o
27780 @end smallexample
27781
27782 @node Debugging a DLL
27783 @section Debugging a DLL
27784 @cindex DLL debugging
27785
27786 @menu
27787 * Program and DLL Both Built with GCC/GNAT::
27788 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27789 @end menu
27790
27791 @noindent
27792 Debugging a DLL is similar to debugging a standard program. But
27793 we have to deal with two different executable parts: the DLL and the
27794 program that uses it. We have the following four possibilities:
27795
27796 @enumerate 1
27797 @item
27798 The program and the DLL are built with @code{GCC/GNAT}.
27799 @item
27800 The program is built with foreign tools and the DLL is built with
27801 @code{GCC/GNAT}.
27802 @item
27803 The program is built with @code{GCC/GNAT} and the DLL is built with
27804 foreign tools.
27805 @item
27806 @end enumerate
27807
27808 @noindent
27809 In this section we address only cases one and two above.
27810 There is no point in trying to debug
27811 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27812 information in it. To do so you must use a debugger compatible with the
27813 tools suite used to build the DLL.
27814
27815 @node Program and DLL Both Built with GCC/GNAT
27816 @subsection Program and DLL Both Built with GCC/GNAT
27817
27818 @noindent
27819 This is the simplest case. Both the DLL and the program have @code{GDB}
27820 compatible debugging information. It is then possible to break anywhere in
27821 the process. Let's suppose here that the main procedure is named
27822 @code{ada_main} and that in the DLL there is an entry point named
27823 @code{ada_dll}.
27824
27825 @noindent
27826 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27827 program must have been built with the debugging information (see GNAT -g
27828 switch). Here are the step-by-step instructions for debugging it:
27829
27830 @enumerate 1
27831 @item Launch @code{GDB} on the main program.
27832
27833 @smallexample
27834 $ gdb -nw ada_main
27835 @end smallexample
27836
27837 @item Break on the main procedure and run the program.
27838
27839 @smallexample
27840 (gdb) break ada_main
27841 (gdb) run
27842 @end smallexample
27843
27844 @noindent
27845 This step is required to be able to set a breakpoint inside the DLL. As long
27846 as the program is not run, the DLL is not loaded. This has the
27847 consequence that the DLL debugging information is also not loaded, so it is not
27848 possible to set a breakpoint in the DLL.
27849
27850 @item Set a breakpoint inside the DLL
27851
27852 @smallexample
27853 (gdb) break ada_dll
27854 (gdb) run
27855 @end smallexample
27856
27857 @end enumerate
27858
27859 @noindent
27860 At this stage a breakpoint is set inside the DLL. From there on
27861 you can use the standard approach to debug the whole program
27862 (@pxref{Running and Debugging Ada Programs}).
27863
27864 To break on the @code{DllMain} routine it is not possible to follow
27865 the procedure above. At the time the program stop on @code{ada_main}
27866 the @code{DllMain} routine as already been called. Either you can use
27867 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
27868
27869 @enumerate 1
27870 @item Launch @code{GDB} on the main program.
27871
27872 @smallexample
27873 $ gdb -nw ada_main
27874 @end smallexample
27875
27876 @item Load DLL symbols
27877
27878 @smallexample
27879 (gdb) add-sym api.dll
27880 @end smallexample
27881
27882 @item Set a breakpoint inside the DLL
27883
27884 @smallexample
27885 (gdb) break ada_dll.adb:45
27886 @end smallexample
27887
27888 Note that at this point it is not possible to break using the routine symbol
27889 directly as the program is not yet running. The solution is to break
27890 on the proper line (break in @file{ada_dll.adb} line 45).
27891
27892 @item Start the program
27893
27894 @smallexample
27895 (gdb) run
27896 @end smallexample
27897
27898 @end enumerate
27899
27900 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27901 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27902
27903 @menu
27904 * Debugging the DLL Directly::
27905 * Attaching to a Running Process::
27906 @end menu
27907
27908 @noindent
27909 In this case things are slightly more complex because it is not possible to
27910 start the main program and then break at the beginning to load the DLL and the
27911 associated DLL debugging information. It is not possible to break at the
27912 beginning of the program because there is no @code{GDB} debugging information,
27913 and therefore there is no direct way of getting initial control. This
27914 section addresses this issue by describing some methods that can be used
27915 to break somewhere in the DLL to debug it.
27916
27917 @noindent
27918 First suppose that the main procedure is named @code{main} (this is for
27919 example some C code built with Microsoft Visual C) and that there is a
27920 DLL named @code{test.dll} containing an Ada entry point named
27921 @code{ada_dll}.
27922
27923 @noindent
27924 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27925 been built with debugging information (see GNAT -g option).
27926
27927 @node Debugging the DLL Directly
27928 @subsubsection Debugging the DLL Directly
27929
27930 @enumerate 1
27931 @item
27932 Launch the debugger on the DLL.
27933
27934 @smallexample
27935 $ gdb -nw test.dll
27936 @end smallexample
27937
27938 @item Set a breakpoint on a DLL subroutine.
27939
27940 @smallexample
27941 (gdb) break ada_dll.adb:45
27942 @end smallexample
27943
27944 Note that at this point it is not possible to break using the routine symbol
27945 directly as the program is not yet running. The solution is to break
27946 on the proper line (break in @file{ada_dll.adb} line 45).
27947
27948 @item
27949 Specify the executable file to @code{GDB}.
27950
27951 @smallexample
27952 (gdb) exec-file main.exe
27953 @end smallexample
27954
27955 @item
27956 Run the program.
27957
27958 @smallexample
27959 (gdb) run
27960 @end smallexample
27961
27962 @noindent
27963 This will run the program until it reaches the breakpoint that has been
27964 set. From that point you can use the standard way to debug a program
27965 as described in (@pxref{Running and Debugging Ada Programs}).
27966
27967 @end enumerate
27968
27969 @noindent
27970 It is also possible to debug the DLL by attaching to a running process.
27971
27972 @node Attaching to a Running Process
27973 @subsubsection Attaching to a Running Process
27974 @cindex DLL debugging, attach to process
27975
27976 @noindent
27977 With @code{GDB} it is always possible to debug a running process by
27978 attaching to it. It is possible to debug a DLL this way. The limitation
27979 of this approach is that the DLL must run long enough to perform the
27980 attach operation. It may be useful for instance to insert a time wasting
27981 loop in the code of the DLL to meet this criterion.
27982
27983 @enumerate 1
27984
27985 @item Launch the main program @file{main.exe}.
27986
27987 @smallexample
27988 $ main
27989 @end smallexample
27990
27991 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27992 that the process PID for @file{main.exe} is 208.
27993
27994 @item Launch gdb.
27995
27996 @smallexample
27997 $ gdb -nw
27998 @end smallexample
27999
28000 @item Attach to the running process to be debugged.
28001
28002 @smallexample
28003 (gdb) attach 208
28004 @end smallexample
28005
28006 @item Load the process debugging information.
28007
28008 @smallexample
28009 (gdb) symbol-file main.exe
28010 @end smallexample
28011
28012 @item Break somewhere in the DLL.
28013
28014 @smallexample
28015 (gdb) break ada_dll
28016 @end smallexample
28017
28018 @item Continue process execution.
28019
28020 @smallexample
28021 (gdb) continue
28022 @end smallexample
28023
28024 @end enumerate
28025
28026 @noindent
28027 This last step will resume the process execution, and stop at
28028 the breakpoint we have set. From there you can use the standard
28029 approach to debug a program as described in
28030 (@pxref{Running and Debugging Ada Programs}).
28031
28032 @node GNAT and COM/DCOM Objects
28033 @section GNAT and COM/DCOM Objects
28034 @findex COM
28035 @findex DCOM
28036
28037 @noindent
28038 This section is temporarily left blank.
28039
28040 @end ifset
28041
28042 @c **********************************
28043 @c * GNU Free Documentation License *
28044 @c **********************************
28045 @include fdl.texi
28046 @c GNU Free Documentation License
28047
28048 @node Index,,GNU Free Documentation License, Top
28049 @unnumbered Index
28050
28051 @printindex cp
28052
28053 @contents
28054 @c Put table of contents at end, otherwise it precedes the "title page" in
28055 @c the .txt version
28056 @c Edit the pdf file to move the contents to the beginning, after the title
28057 @c page
28058
28059 @bye